Django: posting a template value to a view

django, html, python

Solution

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>

Problem

The Problem: I'm tying to post to a view and pass on a value from the template by using a hidden value field and a submit button. The values from the submit button (ie the csrf_token) gets through but the hidden value does not. I've checked from the Wezkrug debugger that `request.POST` only contains form values and not my `'id'` value from the hidden field. Background: The button takes you to a form where you can enter a comment. I'm trying to include the `review.id` that the user is commenting on to make commenting easy. I have the value as 'test' not for test purposes. My form: ``` <div> <form method='POST' action='/add_comment/'> {% csrf_token %} <input type="hidden" name='id' value='test'> <input type="submit" value="Make a Comment"> </form> </div> ``` Comment View: ``` @login_required def make_comment(request): if request.method == 'POST': form = CommentForm(request.POST) if form.is_valid(): comment = form.save(commit=False) comment.user = request.user comment.save() # render? return HttpResponseRedirect('/results/', { 'restaurant': get_object_or_404( Restaurant, name=request.POST['name'], address=request.POST['address'] ) }) else: form = CommentForm() return render(request, 'stamped/comment.html', {'form': form}) ``` Comment Model: ``` class Comment(models.Model): content = models.TextField() review = models.ForeignKey(Review) user = models.ForeignKey(User) date_added = models.DateTimeField(auto_now_add=True) ``` Comment ModelForm Code: ``` class CommentForm(ModelForm): class Meta: model = Comment exclude = ('user', 'review',) ``` I've been trying to follow the tactics in this question, but using the request.session dict is undesirable because Id have to store an id for every review regardless if they're are ever commented on. What is a more efficient way to pass variables from Template to View in Django? Any ideas on how to include the hidden value in the POST? Thanks!

Original source

Related problems