如何在不需要身份验证的情况下添加评论
How to add comments without authentification required
我刚刚在我的网站上做了评论,我想做非授权评论,不知道to.My模型是这样的
class Comment(models.Model):
article = models.ForeignKey(Product, on_delete = models.CASCADE, verbose_name='Page', blank = True, null = True,related_name='comments' )
author = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete = models.CASCADE, verbose_name='Comment author', blank = True, null = True )
create_date = models.DateTimeField(auto_now=True)
text = models.TextField(verbose_name='Comment text', max_length=500)
status = models.BooleanField(verbose_name='Visible', default=False)
和views.py喜欢这样
def post(self, request, *args, **kwargs):
form = self.get_form()
if form.is_valid():
return self.form_valid(form)
else:
return self.form_invalid(form)
def form_valid(self, form):
self.object = form.save(commit=False)
self.object.article = self.get_object()
self.object.author = self.request.user
self.object.save()
return super().form_valid(form)
def post(self, request, *args, **kwargs):
form = self.get_form()
if form.is_valid():
return self.form_valid(form)
else:
return self.form_invalid(form)
def form_valid(self, form):
self.object = form.save(commit=False)
self.object.article = self.get_object()
if self.request.user.is_authenticated:
self.object.author = self.request.user
else:
self.object.author = None
self.object.save()
return super().form_valid(form)
注意:如果出现错误,请移除 else 块
我刚刚在我的网站上做了评论,我想做非授权评论,不知道to.My模型是这样的
class Comment(models.Model):
article = models.ForeignKey(Product, on_delete = models.CASCADE, verbose_name='Page', blank = True, null = True,related_name='comments' )
author = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete = models.CASCADE, verbose_name='Comment author', blank = True, null = True )
create_date = models.DateTimeField(auto_now=True)
text = models.TextField(verbose_name='Comment text', max_length=500)
status = models.BooleanField(verbose_name='Visible', default=False)
和views.py喜欢这样
def post(self, request, *args, **kwargs):
form = self.get_form()
if form.is_valid():
return self.form_valid(form)
else:
return self.form_invalid(form)
def form_valid(self, form):
self.object = form.save(commit=False)
self.object.article = self.get_object()
self.object.author = self.request.user
self.object.save()
return super().form_valid(form)
def post(self, request, *args, **kwargs):
form = self.get_form()
if form.is_valid():
return self.form_valid(form)
else:
return self.form_invalid(form)
def form_valid(self, form):
self.object = form.save(commit=False)
self.object.article = self.get_object()
if self.request.user.is_authenticated:
self.object.author = self.request.user
else:
self.object.author = None
self.object.save()
return super().form_valid(form)
注意:如果出现错误,请移除 else 块