django评论功能实现
时间: 2023-08-20 11:04:15 浏览: 68
要在Django中实现评论功能,一般需要以下步骤:
1. 创建Comment模型并与其他模型进行关联,例如某篇文章的评论。
2. 编写CommentForm表单,用于接收用户提交的评论内容。
3. 在视图函数中处理表单数据,验证并保存评论到数据库。
4. 在模板中展示评论列表和评论表单。
下面是一个简单的实现过程:
1. 创建Comment模型
```python
from django.db import models
from django.contrib.auth.models import User
class Comment(models.Model):
user = models.ForeignKey(User, on_delete=models.CASCADE)
content = models.TextField()
created_time = models.DateTimeField(auto_now_add=True)
article = models.ForeignKey('Article', on_delete=models.CASCADE)
def __str__(self):
return self.content
```
2. 编写CommentForm表单
```python
from django import forms
class CommentForm(forms.Form):
content = forms.CharField(widget=forms.Textarea)
```
3. 编写视图函数
```python
from django.shortcuts import render, get_object_or_404, redirect
from .models import Article, Comment
from .forms import CommentForm
def article_detail(request, pk):
article = get_object_or_404(Article, pk=pk)
comments = Comment.objects.filter(article=article)
if request.method == 'POST':
form = CommentForm(request.POST)
if form.is_valid():
comment = form.save(commit=False)
comment.user = request.user
comment.article = article
comment.save()
return redirect('article_detail', pk=article.pk)
else:
form = CommentForm()
return render(request, 'article_detail.html', {'article': article, 'comments': comments, 'form': form})
```
4. 在模板中展示评论列表和评论表单
```html
{% extends 'base.html' %}
{% block content %}
<h1>{{ article.title }}</h1>
<p>{{ article.content }}</p>
<h2>Comments</h2>
<ul>
{% for comment in comments %}
<li>{{ comment.content }}</li>
{% empty %}
<li>No comments yet.</li>
{% endfor %}
</ul>
<form method="post">
{% csrf_token %}
{{ form.as_p }}
<button type="submit">Submit</button>
</form>
{% endblock %}
```
以上是一个简单的评论功能实现过程,需要根据具体情况进行调整和完善。
相关推荐
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)