i just done comments on my website,and i want to do non-authorized comments,and dont know how to.My models looks like this
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)
and views.py like this
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)
CodePudding user response:
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)
note: remove else block if you get an error