1、 评论和用户建立关联
1)修改model:
- 软关联还是硬关联
- 默认值是什么
- 关联方被删除怎么办
- 如何根据评论找到用户
- 如何根据用户找到评论
然后执行命令:
pdm run M
pdm run init
这样在表里面就会多一个user_id的字段
2)修改视图,接下来编辑views.py文件
@login_required
def submit(request):
if request.method == 'GET':
html = open("submit.html", encoding="utf-8").read()
return HttpResponse(html)
elif request.method == 'POST':
# 获取提交的表单数据
data = json.loads(request.body)
# my_sql()
print(data)
Feedback.objects.create(user=request.user,
quality=data['quality'],
attitude=data['attitude'],
speed=data['speed'],
text=data['text'],
anonymous=data['anonymous']
)
return JsonResponse({'status': 'success',
"data": data})
如果曾经发表过,则不能再发表
@login_required
def submit(request):
if request.method == 'GET':
html = open("submit.html", encoding="utf-8").read()
return HttpResponse(html)
elif request.method == 'POST':
# 获取提交的表单数据
data = json.loads(request.body)
obj_list = Feedback.objects.filter(user=request.user)
if obj_list:
return JsonResponse({'status': 'failed',
"message": "你曾经发表过,不能再发表了"})
print(data)
Feedback.objects.create(user=request.user,
quality=data['quality'],
attitude=data['attitude'],
speed=data['speed'],
text=data['text'],
anonymous=data['anonymous']
)
return JsonResponse({'status': 'success',
"data": data})
所以说不允许匿名具有很重要的意义
第一对用户进行保护,
第二对评论进行实质的关联