【问题标题】:How to pass a complex url to a generic class Update view in django如何将复杂的 url 传递给 django 中的通用类更新视图
【发布时间】:2020-07-25 22:47:12
【问题描述】:

我正在尝试为我的 django 博客项目创建更新视图,但我无法弄清楚。我有一个模型,它根据发布日期和标题创建一个 url,该标题也通过一个随机 slug 生成器给出,我无法将该 url 传递给更新视图我不断收到错误“AttributeError at /posts2020 /7/24/hello-93ej/更新/ 必须使用对象 pk 或 URLconf 中的 slug 调用通用详细视图 PostUpdateView"

这是我的代码

models.py

class Post(models.Model):
    STATUS_CHOICES = (
        ('cleared','Cleared'),('UnderReview','Being Reviewed'),('banned','Banned'),)
    title = models.CharField(max_length = 300)
    slug = models.SlugField(max_length = 300, unique_for_date='publish')
    author = models.ForeignKey(User, on_delete=models.SET_NULL, related_name='forum_posts',null=True)
    body = models.TextField()
    publish = models.DateTimeField(default=timezone.now)
    created = models.DateTimeField(auto_now_add=True)
    updated = models.DateTimeField(auto_now=True)
    status = models.CharField(max_length=12,choices=STATUS_CHOICES,default='cleared')
    objects = models.Manager()
    cleared = PublishedManager()
    class Meta:
        ordering =('-publish',)
    def __str__(self):
        return self.title
    def get_absolute_url(self):
        return reverse('posts:post_detail', args=[self.publish.year, self.publish.month, self.publish.day, self.slug])

urls.py

from . import views
from django.urls import path, include
from django.contrib.auth import views as auth_views
from .views import PostListView, PostCreateView,PostUpdateView
app_name = 'posts'
urlpatterns = [
    path('', views.PostListView.as_view(), name='post_list'),
    path('<int:year>/<int:month>/<int:day>/<slug:post>/',views.post_detail,name='post_detail'),
    path('post/new/',PostCreateView.as_view(), name='post-create'),
    path('<int:year>/<int:month>/<int:day>/<slug:post>/update/',PostUpdateView.as_view(), name='post-update'),

views.py

class PostUpdateView(LoginRequiredMixin, UpdateView):
    model = Post
    fields = ['title','body']

    def get_success_url(self):
        return reverse('posts:post-update', args=[self.publish.year, self.publish.month, self.publish.day, self.slug])
    
    def form_valid(self, form):
        form.instance.author = self.request.user
        return super().form_valid(form)

post-update.html

{% extends "Main/Base.html" %}
{% block title %} Update a post {% endblock %}
{% block content %}
    {% if request.user.is_authenticated %}
    <h1> Update a post <h1>
    <p>You can Update your post using the following form:</p>
    <form method="post">
        {{ form.as_p }}
        {% csrf_token %}
        <p><input type="submit" value="Update"></p>
    </form>
    {% endif %}
{% endblock %}

【问题讨论】:

    标签: python django


    【解决方案1】:

    您可以通过覆盖get_object来过滤对象:

    from django.shortcuts import get_object_or_404
    
    class PostUpdateView(LoginRequiredMixin, UpdateView):
        model = Post
        fields = ['title','body']
    
        def get_object(self, *args, **kwargs):
            return get_obect_or_404(
                Post,
                publish__year=self.kwargs['year'],
                publish__month=self.kwargs['month'],
                publish__day=self.kwargs['day'],
                slug=self.kwargs['post'],
                author=self.request.user
            )
    
        def get_success_url(self):
            return reverse(
                'posts:post-update',
                args=[
                    self.object.publish.year,
                    self.object.publish.month,
                    self.object.publish.day,
                    self.object.slug
                ]
            )
        
        def form_valid(self, form):
            form.instance.author = self.request.user
            return super().form_valid(form)

    author=self.request.user 过滤器部分将确保如果登录用户不是作者,它将引发 HTTP 404 响应,而不是让该用户编辑帖子。

    【讨论】:

    • 除此之外,我认为 self.publish 不存在...
    • 是的,self.object 确实如此,因为我们在此处的视图中。
    • @Melvyn:是的,我在评论几秒钟后就意识到了;)
    • 感谢您按预期工作的帮助,我只需要检查作者是否是现在尝试编辑它的人
    • @JoeG:您也可以过滤author=request.user。见编辑。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2021-11-18
    • 2011-03-28
    • 1970-01-01
    • 2012-01-17
    • 2017-11-11
    • 2019-03-23
    • 1970-01-01
    相关资源
    最近更新 更多