You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Django未登录用户访问UpdateView时重定向至对应DetailView问题

解决Django PostUpdateView未登录用户重定向到对应帖子详情页的问题

使用LoginRequiredMixin是正确的思路,之前的写法错误在于:

  • 类属性login_url在类定义阶段无法访问self.object,因为此时类还未实例化
  • 重写get_login_url时没有正确获取URL中的pk参数,也没有返回生成的URL

正确实现方式

直接重写get_login_url方法,从URL的kwargs中提取帖子ID,生成对应详情页的URL:

from django.urls import reverse_lazy
from django.contrib.auth.mixins import LoginRequiredMixin
from django.views.generic.edit import UpdateView
from .models import Post
from .forms import PostUpdateForm

class PostUpdateView(LoginRequiredMixin, UpdateView):
    model = Post
    form_class = PostUpdateForm
    template_name = "posts/update_post.html"

    def get_login_url(self):
        # 从URL参数中获取帖子pk
        post_pk = self.kwargs.get('pk')
        # 返回对应帖子详情页的URL
        return reverse_lazy('details', args=[post_pk])

补充:限制仅作者可编辑(可选)

如果需要确保只有帖子作者能访问编辑页,可结合UserPassesTestMixin,并在无权限时也重定向到详情页:

from django.urls import reverse_lazy, redirect
from django.contrib.auth.mixins import LoginRequiredMixin, UserPassesTestMixin
from django.views.generic.edit import UpdateView
from .models import Post
from .forms import PostUpdateForm

class PostUpdateView(LoginRequiredMixin, UserPassesTestMixin, UpdateView):
    model = Post
    form_class = PostUpdateForm
    template_name = "posts/update_post.html"

    def get_login_url(self):
        post_pk = self.kwargs.get('pk')
        return reverse_lazy('details', args=[post_pk])

    def test_func(self):
        # 验证当前用户是否为帖子作者
        post = self.get_object()
        return self.request.user == post.author

    def handle_no_permission(self):
        # 登录用户无权限时,重定向到帖子详情页
        post_pk = self.kwargs.get('pk')
        return redirect(reverse_lazy('details', args=[post_pk]))

内容的提问来源于stack exchange,提问作者X_ShaygaN_D

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.21 23:06:25