【问题标题】:Pass primary key in success_url in Delete Class view in django在django的Delete Class视图中传递success_url中的主键
【发布时间】:2020-07-31 06:17:49
【问题描述】:

我的 models.py 中有一个 Post 模型

在模板中,postdescripition.html,我有以下删除按钮的代码,在 postdescription.html 中,我提到了 post 对象

<a class=type="submit" href="{% url 'delete' pk=post.id %}" >Delete </a> 

在 urls.py 中

path('posts/<int:pk>/delete',views.Delete_Post.as_view(), name = 'delete') ,

在views.py中

class Delete_Post(DeleteView):
     model = Post
     template_name = 'dlt.html'
     # dlt.html have an confirmation button
     # success_url= '/profile/1' -> working 
     #i want 1 to should be replaced by user id
     # reverse_lazy('posts') -> working
     #success_url = reverse_lazy('profile/pk=id')-> not working
      success_url= "/posts/"

删除后我想重定向到那个用户个人资料页面,所以我需要那个 user.id..,在删除后传递到视图中,我在 success_url 中使用“/posts/”将我重定向到所有帖子,没问题

urls.py

  path('profile/<pk>/', views.Profile, name='profile'),

但是为了得到身份证,我试过了

  1. “Delete_Post”类视图中的request.user.id

request is not defined error

  1. object.author.id

object has no attribute author

注意:我实现了登录和身份验证。所以 request.user.id 给出当前用户 id

【问题讨论】:

标签: django request primary-key reverse attributeerror


【解决方案1】:

这里没有定义id,所以你不能在这里使用它,你应该做的是在你的个人资料视图中处理用户识别。我假设您会创建一个登录视图等,因此在您的个人资料视图中根据请求获取用户,而不是在此处使用 id 反转

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2018-12-09
    • 2011-11-15
    • 2013-12-05
    • 2018-03-05
    • 2023-03-20
    • 2012-06-17
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多