[Django]-Django: posting a template value to a view

10👍

✅

views.py

def make_comment(request):
    if request.method == 'POST':
        if 'prepair_comment' in request.POST:
            review = get_object_or_404(Review, pk=request.POST.get('id'))
            form = CommentForm({'review': review.id})
            return render(request, 'stamped/comment.html', {
                'form': form,
                })
        else: # save the comment

models.py

class CommentForm(ModelForm):
        class Meta:
               model = Comment
               exclude = ('user',)
               widgets = {'review': forms.HiddenInput()}

restaurant.html

<form method='POST' action='/add_comment/'>
    {% csrf_token %}
    <input type='hidden' value='{{ r.id }}' name='id'>
    <input type="submit" name='prepair_comment' value="Make a Comment">
</form>

0👍

You can access the form with form.cleaned_data. You could also use a if form.is_valid() or if you want to ignore the hidden test value when there is no comment, then you could use a if/else logic to ignore the hidden value if comment is None: logic.

To access the form and only record the test value if comment is not None, the views.py might look like this:

 def form_view(request):
      if request.method == 'POST'
        form = form(request.POST)
        if form.is_valid():
          comment = form.cleaned_data['comment']
          # do something with other fields
          if comment is not None:
            id = form.cleaned_data['test']
            # do something with the hidden 'id' test value from the form
         return HttpResponseRedirect('/thanks/')
       else:
         form = form()
       return render(request, 'form.html', {'form': form})

Here are the Django Docs that I would reference for this:

https://docs.djangoproject.com/en/dev/topics/forms/

Leave a comment