【问题标题】:How to construct url path with two detailview如何用两个detailview构造url路径
【发布时间】:2019-09-08 08:15:25
【问题描述】:

我有以下网址格式

urlpatterns = [
    path('', CategoryListView.as_view(), name='forum'),
    path('category/<int:pk>/', CategoryDetailView.as_view(), name='forum-detail'),
]

在 CategoryDe​​tailView 中,我将列出与该类别相关的帖子。因此,当我单击任何帖子时,我想要类别中的帖子详细信息视图,因为当我将使用 CreateView 类创建帖子时,我希望类别已经预定义。我还可以执行以下操作

path('post/<int:pk>/', ForumPostDetailView.as_view(), name='forum-post-detail'),
    path('post/new/', ForumPostCreateView.as_view(), name='forum-post-create'),
]

在这种情况下,用户在尝试创建帖子时应自行选择类别。但我希望已经选择这样的类别(我知道这是错误的)

path('category/<int:pk>/post/<int:pk>/', ForumPostDetailView.as_view(), name='forum-post-detail'),
    path('category/<int:pk>/post/new/', ForumPostCreateView.as_view(), name='forum-post-create'),
] 

我的视图文件和模型是这样的:

class ForumPostCreateView(CreateView):
    model = PostForum
    fields = ['title', 'content']
    template_name = 'forum/forum_post_form.html'

    def form_valid(self, form):
        form.instance.author = self.request.user
        return super().form_valid(form)

class Category(models.Model):
    image = models.ImageField(default='category.png', upload_to='category_pics')
    title = models.CharField(max_length=100)
    content = models.CharField(max_length=1200)
    date_posted = models.DateTimeField(auto_now=True)

class PostForum(models.Model):
    category = models.ForeignKey(Category, on_delete=models.CASCADE)
    title = models.CharField(max_length=100)
    content = models.TextField()
    date_posted = models.DateTimeField(default=timezone.now)
    author = models.ForeignKey(User, on_delete=models.CASCADE)

那该怎么做呢?现在它显示了

IntegrityError
null value in column "category_id" violates not-null constraint

【问题讨论】:

    标签: django django-models django-views


    【解决方案1】:

    在urls.py中设置category.id

    path('category/<int:cat_id>/post/new/', ForumPostCreateView.as_view(), name='forum-post-create')
    

    检查它是否存在于您的视图中

    class ForumPostCreateView(CreateView):
        category = None
    
        def despatch(self, *args, **kwargs):
            super().despatch(*args, **kwargs)
            if 'cat_id' in self.kwargs:
                self.category = Category.objects.get(id=cat_id)
    

    现在您可以在初始化表单时在表单中使用它

    【讨论】:

    • 仍然显示 IntegrityError at /forum/category/1/post/new/ "category_id" 列中的空值违反非空约束
    • 那是因为你传递了一个空的 category_id。你需要2个网址。一种用于有category_id,一种用于无category_id
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2012-11-23
    • 1970-01-01
    • 2021-04-22
    • 2013-06-30
    • 2018-05-14
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多