Django how to set value of hidden input in template

Viewed 14365

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
4 Answers

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.

Related