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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With