[英]Django add comment section on posts feed
我想分享一個項目,目前可以創建用戶,每個用戶可以創建N個帖子
源碼可以在github上找到
和模板層
目前,每個帖子的提要都有一個按鈕,可以發送評論帖子我想更改它以放置帖子的評論而不是發送和發送電子郵件每個用戶應該能夠評論帖子並且評論應該保留
{% block container %}
<body id="bg" img style="zoom: 85%; background-position: center center; background-attachment: fixed;background-repeat:no-repeat;padding:5px; background-image: url('{% static "/back.png"%}') ";>
<div style="background-image: url({% static 'static/img/back.png' %});">
<div class="row" style="align:center">
{% for post in posts %}
<div class="col-sm-12 col-md-8 offset-md-4 mt-5 p-0 post-container,width:50%;">
<div class="card" style="width: 32rem;width:50%;">
<div class="card-body">
<div class="media pt-3 pl-3 pb-1">
<a href="{% url " users:detail" post.user.username%}">
<img alt="{{ post.user.username }}" class="mr-3 rounded-circle" height="35"
src="{{ post.profile.picture.url }}">
</a>
<h3 class="card-title">{{ post.title }}</h3>
</div>
<p class="card-text">{{ post.desc }}</p>
</div>
</div>
<img alt="{{ post.title }}" src="{{ post.photo.url }}" style="width: 50%; heigth:60%">
<div class="media-body">
<b><p style="margin-top: 5px;">@{{ post.user.username }} - <small>{{ post.created }}</small>
<a href="" style="color: #000; font-size: 20px;">
<i class="far fa-heart"></i>
</a>
<br>
</p></b>
</div>
<!-- COMENT SECTION THAT I WANT TO IMPLEMENT MY FEATURE-->
<form action="{% url 'posts:comment_new' %}" enctype="multipart/form-data" method="POST">
{% csrf_token %}
<input
class="form-control {% if form.title.errors %}is-invalid{% endif %}"
name="title"
size="16"
type="hidden"
value="{{post.title}}"
>
<input
class="form-control {% if form.title.errors %}is-invalid{% endif %}"
name="first_name "
size="16"
type="hidden"
value="{{user.first_name}}"
>
<input
class="form-control {% if form.title.errors %}is-invalid{% endif %}"
name="last_name "
size="16"
type="hidden"
value="{{user.last_name}}"
>
<textarea class="form-control" cols="50" name="comment" rows="5"
style="width:50%;" value="{{ comments.comment }}"></textarea>
<button class="btn btn-outline-info btn-lg" style="width:35%; display:block;margin:auto;" type="submit">
Publish
</button>
</form>
</div>
<br>
{% endfor %}
</div>
</div>
{% endblock %}
正如我所說,我想替換此表單函數調用以創建評論部分,而不是發送帶有評論的電子郵件
< form action = "{% url 'posts:comment_new' %}">
def comment_new(request):
if request.method == 'POST':
message = request.POST['comment']
subject = request.POST['title']
user = request.POST['first_name']
last_name = request.POST['last_name']
# lastname = request.POST['lastname']
send_mail("[MAIL] " + subject, user + " " + last_name + " said " + message + " on http://url.com:8000",
'guillermo.varelli@gmail.com',
['guillermo.varelli@gmail.com'], fail_silently=False)
posts = Post.objects.all().order_by('-created')
return render(request, os.path.join(BASE_DIR, 'templates', 'posts', 'feed.html'), {'posts': posts})
我認為這可能會與用戶一起創建評論並發布帶有評論詳細信息的 ID
def comment_new(request):
if request.method == 'POST':
message = request.POST['comment']
subject = request.POST['title']
user = request.POST['first_name']
last_name = request.POST['last_name']
#lastname = request.POST['lastname']
form = PostForm(request.POST, request.FILES)
form.save()
一個選項它創建一個評論
class Comment(models.Model):
"""
#id= models.AutoField(max_length=1000, blank=True)
# post = models.ForeignKey(Post, related_name='',on_delete=models.CASCADE,default=0)
"""
#comment = models.ForeignKey('posts.Post', related_name='posts_rel', to_field="comments", db_column="comments",
# on_delete=models.CASCADE, null=True, default=1, blank=True)
post = models.IntegerField(blank=True,null=True,unique=True)
user = models.ForeignKey(User, on_delete=models.CASCADE,null=True)
username = models.CharField(blank=True, null=True, unique=True ,max_length=200)
comment = models.CharField(max_length=254, blank=True, null=True)
然后是表格
class CommentForm(forms.ModelForm):
class Meta:
"""form settings"""
model = Comment
fields = ('user','username','post','comment',)
終於有了我能夠堅持但無法呈現的功能
form = CommentForm(request.POST, request.FILES)
# 打印 formset.errors
if form.is_valid():
form.save()
但我找不到在 html 文件上呈現對象的方法
please feel free to suggest any solution or better create a pull request on the public git hub repo
在Django 2 by Example一書中,我們可以找到創建評論系統的分步指南,用戶可以在其中對帖子發表評論。
為了做到這一點,就如以下四步一樣簡單
- 創建模型以保存評論
在應用程序的 models.py 文件中,添加以下代碼
class Comment(models.Model):
post = models.ForeignKey(Post,
on_delete=models.CASCADE,
related_name='comments')
name = models.CharField(max_length=80)
email = models.EmailField()
body = models.TextField()
created = models.DateTimeField(auto_now_add=True)
updated = models.DateTimeField(auto_now=True)
active = models.BooleanField(default=True)
class Meta:
ordering = ('created',)
def __str__(self):
return 'Comment by {} on {}'.format(self.name, self.post)
您剛剛創建的新 Comment 模型尚未同步到數據庫中。 運行以下命令以生成反映新模型創建的新遷移:
python manage.py makemigrations APPNAME
和
python manage.py migrate
在此之后,新表存在於數據庫中。 現在,打開博客應用程序的 admin.py 文件,導入 Comment 模型,並添加以下 ModelAdmin 類:
from .models import Post, Comment
@admin.register(Comment)
class CommentAdmin(admin.ModelAdmin):
list_display = ('name', 'email', 'post', 'created', 'active')
list_filter = ('active', 'created', 'updated')
search_fields = ('name', 'email', 'body')
- 創建表單以提交評論並驗證輸入數據
編輯博客應用程序的 forms.py 文件並添加以下行:
from .models import Comment
class CommentForm(forms.ModelForm):
class Meta:
model = Comment
fields = ('name', 'email', 'body')
- 添加處理表單並將新評論保存到數據庫的視圖
編輯 views.py 文件,為 Comment 模型和 CommentForm 表單添加導入,並修改帖子詳細信息視圖,使其如下所示:
from .models import Post, Comment
from .forms import EmailPostForm, CommentForm
def post_detail(request, year, month, day, post):
post = get_object_or_404(Post, slug=post,
status='published',
publish__year=year,
publish__month=month,
publish__day=day)
# List of active comments for this post
comments = post.comments.filter(active=True)
new_comment = None
if request.method == 'POST':
# A comment was posted
comment_form = CommentForm(data=request.POST)
if comment_form.is_valid():
# Create Comment object but don't save to database yet
new_comment = comment_form.save(commit=False)
# Assign the current post to the comment
new_comment.post = post
# Save the comment to the database
new_comment.save()
else:
comment_form = CommentForm()
return render(request,
'blog/post/detail.html',
{'post': post,
'comments': comments,
'new_comment': new_comment,
'comment_form': comment_form})
- 編輯帖子詳細信息模板以顯示評論列表和添加新評論的表單
至此,我們已經創建了管理帖子評論的功能。 現在,我們需要調整我們的 post/detail.html 模板來做以下事情: - 顯示評論列表 - 顯示一個表單供用戶添加新評論
將以下行附加到 post/detail.html 模板以獲取評論列表:
{% for comment in comments %}
<div class="comment">
<p class="info">
Comment {{ forloop.counter }} by {{ comment.name }}
{{ comment.created }}
</p>
{{ comment.body|linebreaks }}
</div>
{% empty %}
<p>There are no comments yet.</p>
{% endfor %}
然后,對於另一點,添加以下幾行:
{% if new_comment %}
<h2>Your comment has been added.</h2>
{% else %}
<h2>Add a new comment</h2>
<form action="." method="post">
{{ comment_form.as_p }}
{% csrf_token %}
<p><input type="submit" value="Add comment"></p>
</form>
{% endif %}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.