【发布时间】:2021-08-18 18:46:26
【问题描述】:
我的模型上有一个方法可以将对象从已发布更改为未发布。重定向工作正常,但在我的数据库中,没有任何反应。如果对象已发布,则在单击按钮取消发布对象时保持不变(博客文章)
这是模型和方法
class Post(models.Model):
title = models.CharField(max_length=200)
author = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.SET_NULL, null=True)
published = models.BooleanField(default=False, null=True, blank=True)
def unpublish(self):
self.published == False
self.save()
我的看法
def unpublish_post(request, slug):
post = get_object_or_404(Post, slug=slug)
post.unpublish
return redirect('dashboard')
编辑 2:我的观点
@require_http_methods(['POST', 'DELETE'])
def unpublish_post(request, slug):
post = get_object_or_404(Post, slug=slug)
if post.published == True:
post.unpublish()
return redirect('dashboard')
else:
return messages.warning(request, "Post already not published")
return redirect('dashboard')
我的 urls.py
path('unpublish-post/<slug>/', unpublish_post, name='unpublish-post'),
编辑 1:现在我更新了视图逻辑:
def unpublish_post(request, slug):
post = get_object_or_404(Post, slug=slug)
if post.published == True:
post.unpublish()
return redirect('dashboard')
else:
return messages.warning(request, "Post already not published")
【问题讨论】:
-
self.published = False(有一个=),而不是self.published == False。 -
@WillemVanOnsem 仍然没有任何反应。我改了
-
你需要致电
unpublish,所以post.unpublish()。 -
谢谢@WillemVanOnsem
-
请不要“破坏”您的帖子。只需在问题底部添加 EDIT。
标签: python django django-models django-rest-framework django-views