Я новичок в Django и создаю одно приложение для блога и ниже на своей странице подробного сообщения и пытаюсь отобразить форму комментариев, но я не получаю форму, даже если я также использовал csrf и не получаю никаких ошибок во время работы сервера.
Однако другие вещи, такие как кнопки и комментарии, отображаются в веб-браузере.
1.models.py
######Model related to comment
# We required to create a Model to save comments
# We required to create a model based form to submit comments
# We required to create a view function to process comments and save to the database
# We have to edit post_detail.html to display list of comments and add a form to submit
# comments
class Comment(models.Model):
post=models.ForeignKey(Post,related_name='comments',on_delete=models.DO_NOTHING)
name=models.CharField(max_length=32)
email=models.EmailField()
body=models.TextField()
created = models.DateTimeField(auto_now_add=True)
updated = models.DateTimeField(auto_now=True)
active = models.BooleanField(default=True)
#now order we can define.
class Meta:
ordering=('-created',)
#now let me take str if any person want to display comment object.
def __str__(self):
return 'Commented by {} on {}'.format(self.name,self.post)
#Means if any person want to display my comment object sir simply return o/p in above form :)
#Now after creating comment model we need to run migration and migrate and need to register inside admin.py
from blog.forms import CommentForm
def post_detail_view(request,year,month,day,post):
post = get_object_or_404(Post,slug=post,status='Published',publish__year=year,
publish__month=month,
publish__day=day)
#now to implement comment we will use related name means post.comments (comment related to this post)
comments=post.comments.filter(active=True)#i got all comment related to post.
csubmit=False
if request.method=='POST':
form=CommentForm(request.POST)
if form.is_valid():
new_comment=form.save(commit=False)
new_comment.post=post
new_comment.save()
csubmit=True
else:
#if not POST then we need to display form.:)
form=CommentForm()
###lets visualize above 3 lines user will submit only 3 field data (name email and body but for which post that we are associating here.)
return render(request,'blog/post_detail.html',{'post': post,form:'form',csubmit:'csubmit','comments':comments})
3.post detail template
Здесь я пытаюсь отобразить форму комментария.
<div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false">
<div class="snippet-code">
<pre class="snippet-code-html lang-html prettyprint-override"><code> <!DOCTYPE html>
{% extends 'blog/base.html'%}
{%block title_block %}
{{post.title}}
{%endblock%}
{%block content%}
<h1>{{post.title}}</h1>
<p id='date'>Published on {{post.publish}} by {{post.author|title}}</p>
{{post.body|linebreaks}}<br>
<div class="container1" align="center">
<!--####Now here below to detail post i'll enter email button href which will open post and email form.-->
<a href="/{{post.id}}/share" class="btn btn-lg btn-success">Share Post By Email</a>
<!--Note: target_blank will open page in new tab.-->
</div>
<!--#######adding comment section below to post######-->
{% with comments.count as comment_count %}
<h2>{{comments_count}} Comment{{comments_count|pluralize}}</h2>
{%endwith%}
<!--#now lets display comments:)-->
{%if comments%}
{%for comment in comments%}
<p id='ch'> comment {{forloop.counter}} by {{comment.name}} on {{comment.created}}</p>
<div class="commentbody">{{comment.body|linebreaks}}</div><hr>
{%endfor%}
{%else%}
<p>There is no Comment Yet!!You are the first to comment on this..</p>
{%endif%}
<!--###Now if comment is Submitted then we need to display form to end user.-->
{%if csubmit%}
<h2>Hey!,Your commented has submitted successfully. </h2>
{%else%}
<!-- <p id="submit1">Please submit your comment.</p>-->
<form method="post">
{{form.as_p}}
{%csrf_token%}
<input type="submit" name="" class='btn btn-lg btn-success' value="Submit Your Comment">
</form>
{%endif%}
{%endblock%}
4. forms.py из django импортировать формы класса EmailSendForm (forms.Form): name = forms.CharField () email = forms.EmailField () to = forms.EmailField () comments = forms.CharField (required = True, widget = forms.Textarea) #here комментарий не является обязательным, поэтому мы берем required = False, а комментарий может быть любого размера, поэтому мы берем текст ared. from blog.models import Комментарий class CommentForm (forms.ModelForm): class Meta: model = Comment fields = ('name', 'email', 'body')