如何使用两个DetailView构造URL路径

时间:2019-09-08 08:15:25

标签: django django-models django-views

我有以下网址格式

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

1 个答案:

答案 0 :(得分:0)

在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)

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