How to set value of who and image in template?
class CommentForm(ModelForm):
who = forms.CharField(widget=forms.HiddenInput())
image = forms.ImageField(widget=forms.HiddenInput())
class Meta:
model = Comments
fields = ['who', 'image', 'content']
It doesn't work (raw text):
<form method='POST' action=''>
{% csrf_token %}
{% render_field comment_form.content class="form-control form-control-sm" placeholder='Comment..' %}
{% render_field comment_form.who class="form-control form-control-sm" value='{{ request.user.profile.pk }}' %}
{% render_field comment_form.image class="form-control form-control-sm" value='{{ image.pk }}' %}
<input class="btn btn-primary btn-sm" type="submit" value="Add comment">
</form>
My views.py:
class ProfileView(DetailView):
comment_form = CommentForm()
queryset = Profile.objects.all()
context_object_name = 'me'
template_name = 'profile.html'
def get_context_data(self, **kwargs):
context = super(ProfileView, self).get_context_data(**kwargs)
context['comment_form'] = self.comment_form
return context
You need to set the initial property of the form field, after you've instantiated the form in your view. Like so:
class ProfileView(DetailView):
comment_form = CommentForm()
queryset = Profile.objects.all()
context_object_name = 'me'
template_name = 'profile.html'
def get_context_data(self, **kwargs):
context = super(ProfileView, self).get_context_data(**kwargs)
context['comment_form'] = self.comment_form
# This sets the initial value for the field:
context['comment_form'].fields['who'].initial = self.request.user.profile.pk
return context
It is an old question, but I will put my answers to try to help those in need.
You can set initial value dynamical in your view
link in Django documentation: https://docs.djangoproject.com/en/3.1/ref/forms/api/#dynamic-initial-values
Use initial to declare the initial value of form fields at runtime. For example, you might want to fill in a username field with the username of the current session.
To accomplish this, use the initial argument to a Form. This argument, if given, should be a dictionary mapping field names to initial values. Only include the fields for which you’re specifying an initial value; it’s not necessary to include every field in your form
eg
comment_form = CommentForm(initial={'who ': request.user.profile.pk})
You can do some thing like this. This is a pure HTML approach.
Inside the from add the
<input type="hidden" name="content" value="{{value}}">
Put the field inside the name attribute and set the value to anything you want inside the value attribute.
<form method='POST' action=''>
{% csrf_token %}
{% render_field comment_form.content class="form-control form-control-sm" placeholder='Comment..' %}
{% render_field comment_form.who class="form-control form-control-sm" value='{{ comment_form.who }}' %}
{% render_field comment_form.image class="form-control form-control-sm" value='{{ comment_form.image }}' %}
<input class="btn btn-primary btn-sm" type="submit" value="Add comment">
</form>
Related
In order to have a better overview on which page I'm loading which form, I would like to change the name with which it is accessed in the template. By default as far as I know it is set to 'form'. In the snipped below I'm trying to load the form with 'form_inv' but that doesn't work.
{% extends "dashboard/base.html" %}
{% load crispy_forms_tags %}
{% block content %}
<div class="content-section">
<form method="POST">
{% csrf_token %}
<fieldset class="form-group">
<legend class="border-bottom mb-4">Create Investment</legend>
{{ form_inv|crispy }}
</fieldset>
<div class="form-group">
<button class="btn btn-outline-info" type="submit">Create</button>
</div>
</form>
</div>
{% endblock content %}
The following is the Model I created and the respective view.
The Model:
class MoneyGroups(models.Model):
title = models.CharField(max_length=100)
size = models.IntegerField()
interest = models.FloatField()
The Django View:
class MoneyCreateView(LoginRequiredMixin, CreateView):
model = MoneyGroups
template_name = 'dashboard/scenario_form.html' # <app>/<model>_<viewtype>.html
context_object_name = 'investments'
fields = ['title', 'size', 'interest']
success_url = '/dashboard/'
def form_valid(self, form):
form.instance.author = self.request.user #add the author to the form before it is submitted
return super().form_valid(form)
What parameter do I have to change/add in my model or view in order to change the name with which I can access it in the template?
Thanks for your help!
Not sure why you would want to do this but add get_context_data method to your view like so:
def get_context_data(self, **kwargs):
context = super().get_context_data(**kwargs)
context[‘form_inv’] = context[‘form’]
return context
I extend the django User model with a profile model. I want add update user's profile function. Because I make the num field a unique field, in my update view function, the update form's is_valid was always False. I also cannot update the photo png? Here is my code;
Models:
class Profile(models.model):
user = models.OneToOneField(User,on_delete=models.CASCADE)
num =models.CharField('identity',max_length=254,unique=True)
photo = models.ImageField('image',upload_to = 'images/licences')
forms:
class ProfileForm(forms.ModelForm):
class Meta:
model= Profile
fields = ['num','photo']
views:
def modify_view(request):
user = request.user
if request.method=="POST":
form = ProfileForm(request.POST,request.FILES)
if form.is_valid()
user_profile = Profile.objects.get(user=user)
user_profile.image = form.clean_data['image']
user_profile.save()
else:
form = ProfileForm()
return render(request,"profile.html",{form:form})
template
{% extends 'account/home/index.html' %}
{% block content %}
<div class="row">
<div class="col-md-8 col-sm-8 col-8">
<form class="signup needs-validation" id="signup_form" method="post" enctype="multipart/form-data" >
{% csrf_token %}
{{form.as_p}}
{% if redirect_field_value %}
<input type="hidden" name="{{ redirect_field_name }}" value="{{ redirect_field_value }}" />
{% endif %}
<div class="form-group">
<button type="submit" class="col-sm-8 offset-sm-4 btn btn-success btn-block">update</button>
</div>
</form>
</div>
</div>
{% endblock %}
Since num field is unique and will not be generated again on updating the profile image, you can ignore request.POST and pass the instance argument to the ProfileForm class.
Example:
def modify_view(request):
user = request.user
if request.method=="POST":
user_profile = Profile.objects.get(user=user)
form = ProfileForm(files=request.FILES, instance=user_profile)
if form.is_valid():
user_profile.image = form.clean_data['image']
user_profile.save()
else:
form = ProfileForm()
return render(request,"profile.html",{form:form}
I have a website where user submitted entries are displayed and have an upvote count along with a button to upvote it yourself. These are represented with the Entry model. How do I pass the id of the particular Entry instance the user upvotes to a view?
html:
{% for entry in entries %}
<div id="upvote_count">
<form action="upvote" method="GET">
{% csrf_token %}
{{ entry.upvotes }}
<button id="upvote" type="submit">Upvote</button>
</form>
</div>
{% endfor %}
models.py:
class Entry(models.Model):
#...
upvotes = models.IntegerField( blank = True, null=True)
current url:
url(r'^upvote$', views.upvote),
You can pass it inside a hidden input, such as:
<form ...>
...
<input type="hidden" name="id" value="{{ entry.id }}">
<button ...>
</form>
and access to it in your view:
def upvote(request):
entry_id = int(request.GET.get("id"))
...
I want to save the data in the form and go back to previous page when I click on 'Add' button. It's showing some errors. Can anyone suggest the correct way to do it?
template.html
<div class="panel panel-default">
<div class="panel-heading">
<h3 class="panel-title">Add your own Category </h3>
</div>
<div class="panel-body">
<form method="POST" class="post-form">
{% csrf_token %}
{{ form.as_p }}
</div>
</div>
</div>
<input type="hidden" name="next" value="{{ request.path }}">
<button type="submit" class="save btn btn-default" >Add</button>
</form>
views.py
class CustomCategory(LoginRequiredMixin,CreateView):
model = Category
form_class = CategoryForm
def form_valid(self, form):
obj = form.save(commit=False)
def category(request):
next = request.POST.get('next', '/')
return render (request,HttpResponseRedirect(next))
Instead of adding the redirect as an element of the form, why don't you use the success_url field on the view, or if the URL you need to go to depends on an object, use the get_success_url method on the view?
https://docs.djangoproject.com/en/2.0/ref/class-based-views/mixins-editing/
I want to redirect to another view after a successful update, this is my code
Template
<div class="col-sm-6 col-sm-offset-3">
<h3>{% trans "Editar información" %}</h3>
<form method="post" action="">
{% csrf_token %}
{{ form|crispy }}
<input class="btn btn-primary" type="submit" value="{% trans 'Confirmar' %}" />
<input type="hidden" name="pk" value="{{ request.user.id }}" />
</form>
</div>
urls.py
from django.contrib.auth.decorators import login_required as LR
url(r'^editperfil/(?P<pk>\d+)/$' , LR(EditarPerfil.as_view()), {}, name="editar_perfil"),
url(r'^edituser/(?P<pk>\d+)/$' , LR(EditarUsuario.as_view()), {}, name="editar_user"),
This is my view
class EditarUsuario(UpdateView):
model=User
form_class=EditUserForm
template_name = "editarUsuario.html"
def get_success_url(self):
return reverse('editar_perfil', args=(), kwargs={'pk':"pk" })
I need the pk parameter but I don't know how I can get it.
Try this:
from django.core.urlresolvers import reverse_lazy
class EditarUsuario(UpdateView):
model=User
form_class=EditUserForm
template_name = "editarUsuario.html"
def get_success_url(self):
return reverse_lazy('editar_perfil', args = (self.object.id,))