我正在使用Django制作商店类型的网站,目前正在制定审核和评级系统。我的评论'应用程序包含一个名为' Review'以及从产品说明模板添加评论的视图。模特:
class Review(models.Model):
product = models.ForeignKey(Product, on_delete=models.CASCADE)
author = models.ForeignKey('auth.User', on_delete=models.CASCADE)
title = models.CharField(max_length=100)
content = models.TextField()
rating = models.IntegerField(blank=True, null=True)
created_date = models.DateTimeField(auto_now_add=True)
我遇到的问题是视图没有通过product_id字段,导致NOT NULL约束失败错误。该观点如下:
@login_required
def add_review(request):
if request.user:
if request.method == "POST":
review_form = ReviewForm(request.POST)
if review_form.is_valid():
review = review_form.save(commit=False)
review.author = request.user
review_form.save()
messages.success(request, "Review posted successfully!")
return redirect(reverse(get_reviews))
else:
review_form = ReviewForm()
else:
messages.error(request, "You must be a member to post reviews.")
return redirect(reverse(get_reviews))
args = {'review_form': review_form}
return render(request, "add_review.html", args)
然而,当我尝试通过使用相同的方法来传递作者(我知道我在其他地方使用过该代码的工作)来纠正它时,我得到一个WSGIRequest错误,声明"对象有没有属性'产品' &#34 ;.添加的行如下所示:
...
if review_form.is_valid():
review = review_form.save(commit=False)
review.product = request.product
review.author = request.user
review_form.save()
...
可能很明显,但我的Django知识有点受限,因为我还在学习它。任何人都可以指出我正确的方向吗?
提前致谢。
编辑: 我被要求分享urls.py,所以这里是:
from django.conf.urls import url
from .views import review_content, add_review, edit_review, delete_review
urlpatterns = [
url(r'^(?P<pk>\d+)/$', review_content, name='review-content'),
url(r'^add-review/$', add_review, name='add-review'),
url(r'^(?P<pk>\d+)/edit/$', edit_review, name='edit-review'),
url(r'^(?P<pk>\d+)/delete-review/$', delete_review, name='delete-
review'),
]