Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Django how to set value of hidden input in template

Tags:

python

django

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
like image 272
Barburka Avatar asked Aug 16 '17 11:08

Barburka


1 Answers

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
like image 56
YellowShark Avatar answered Sep 25 '22 15:09

YellowShark