django商场评论功能
时间: 2023-08-20 09:05:18 浏览: 47
要实现一个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)
product = models.ForeignKey('Product', 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 Product, Comment
from .forms import CommentForm
def product_detail(request, pk):
product = get_object_or_404(Product, pk=pk)
comments = Comment.objects.filter(product=product)
if request.method == 'POST':
form = CommentForm(request.POST)
if form.is_valid():
comment = form.save(commit=False)
comment.user = request.user
comment.product = product
comment.save()
return redirect('product_detail', pk=product.pk)
else:
form = CommentForm()
return render(request, 'product_detail.html', {'product': product, 'comments': comments, 'form': form})
```
4. 在模板中展示评论列表和评论表单
```html
{% extends 'base.html' %}
{% block content %}
<h1>{{ product.name }}</h1>
<p>{{ product.description }}</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 %}
```
以上是一个简单的商场评论功能实现过程,需要根据具体情况进行调整和完善。
相关推荐
![rar](https://img-home.csdnimg.cn/images/20210720083606.png)
![-](https://csdnimg.cn/download_wenku/file_type_column_c1.png)
![-](https://csdnimg.cn/download_wenku/file_type_column_c1.png)
![-](https://csdnimg.cn/download_wenku/file_type_column_c1.png)
![-](https://csdnimg.cn/download_wenku/file_type_column_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)