I
I
Ivan Privedenets2019-01-26 00:28:06
Django
Ivan Privedenets, 2019-01-26 00:28:06

How to display a comment form on a page using an html template in the {{ form }} block?

Hello, I created a form model, the form itself and data processing in views.py, I want to display it on the page using the html template in the {{ form }} block, but nothing happens.
Model:

class Comment(models.Model):
    product = models.ForeignKey('Product', on_delete=models.CASCADE, related_name='comments', db_column=None)
    name = models.CharField(max_length=50)
    email = models.EmailField(max_length=50)
    text = models.TextField()
    date_pub = models.DateTimeField(auto_now_add=True)
    approved_comment = models.BooleanField(default=False)

views:
def comment(request, pk):
    post = get_object_or_404(Product, pk=pk)    
    if request.method == 'POST':                
        form = CommentForm(request.POST)       
        if form.is_valid():                   
            comm = form.save(commit=False)   
            comm.post = post               
            comm.save()                      
    else:
        form = CommentForm()                  
    return render(request, 'App/Product_information.html', {'post': post, 'form': form})

forms:
from django.forms import ModelForm
from .models import Comment


class CommentForm(ModelForm):
    class Meta:
        model = Comment
        fields = ('name', 'text', 'email')

Sample:
{% extends 'base.html' %}
{% block content %}
<form action=""  method="post" class="post-form">
                {% csrf_token %}
                {{ form }}
</form>
{% endblock %}

Answer the question

In order to leave comments, you need to log in

1 answer(s)
O
Oksana ..., 2019-01-26
@deniz1983

In the view block with else and return must be on the same level as if request.method == POST. Now your form is not rendered, because you wrote the condition “render the form if the data was sent using the post method”

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question