【问题标题】:Django model method not making changes to objectDjango模型方法不对对象进行更改
【发布时间】: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


【解决方案1】:

有三个小错误:

  1. 您使用单个等号 (=) 设置变量,而不是双等号 (==);
  2. 你应该调用.unpublish()方法;和
  3. 您应该只允许在 POST 或 DELETE 请求中访问此视图。

在您的模型中,我们将逻辑重写为:

class Post(models.Model):
    # …

    def unpublish(self):
        self.published = False
        self.save()

在视图中,我们调用该方法并限制对 POST 和/或 DELETE 请求的访问:

from django.views.decorators.http import require_http_methods

@require_http_methods(['POST', 'DELETE'])
def unpublish_post(request, slug):
    post = get_object_or_404(Post, slug=slug)
    post.unpublish()
    return redirect('dashboard')

因此,客户端将需要发出 POST/DELETE 请求,而不是 GET 请求。因此,模板应如下所示:

<form method="POST" action="{% 'unpublish-post' post.slug %}">
    <input type="submit" value="unpublish">
</form>

【讨论】:

  • 真棒@Willem 我还没有实现你的代码。但是,我已经更新了视图。如果帖子未发布并且我尝试再次重新发布它,它会引发错误“视图 blog.views.unpublish_post 没有返回 HttpResponse 对象。它返回 None 而不是”
  • @samhassan:你需要 return 一个 HTTP 响应,例如你自己写的 return redirect('dashboard')
  • @samhassan:在您更新后的视图中,只有在尚未删除 post 时才执行此操作。您还应该在 else 案例中返回一些内容。
  • 我在 else 语句中添加了“return None”。这是抛出的错误“不允许的方法(GET):/unpublish-post/django-tutorials/[18/Aug/2021 19:07:36]“GET /unpublish-post/django-tutorials/HTTP/1.1”405 0" Th page is not working 也会在网页上抛出
  • 请您看看所做的更改好吗
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2011-05-15
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2018-01-12
  • 2020-05-08
相关资源
最近更新 更多