将变量从url传递给CreateView

时间:2015-10-26 11:12:47

标签: django

我正在寻找一种基于url自动填写ForeignField ID的方法。用户将单击一个链接,指向CreateView,其中包含添加到其末尾的ForeignField的ID。我不确定这样做的最佳方式。

urls.py

url(r'^comment/(?P<pk>[0-9]+)/$', CommentCreate.as_view()),

views.py

class CommentCreate(CreateView):
    form_class = CommentCreateForm
    model = Comment
    queryset = Comment.objects.all()

HTML-link.html

<a href="/comment/{{ artical.id }}">Comment</a>

3 个答案:

答案 0 :(得分:0)

据我所知querysetCreateView无效。当然你可以设置它,但它没有意义,因为当你使用CreateView时,你应该想要创建一个对象。

我猜你可以试试像:

class CommentCreate(CreateView):
    form_class = CommentCreateForm
    model = Comment
    form_class = FollowupForm

    def get_form(self):
        form = super(CommentCreate, self).get_form(self.form_class)
        # artical_id - is a name of foreign key defined the Comment model.
        form.instance.artical_id = Artical.objects.get(pk=self.kwargs.get('pk', None))
        return form

答案 1 :(得分:0)

这样,您还可以在上下文中花费文章

def get_context_data(self, **kwargs):
    context = super(CommentCreate, self).get_context_data(**kwargs)
    context['artical'] = Artical.objects.get(pk=self.kwargs[artical_id])
    return context

可以通过执行以下过滤器进行纠正:

context['artical'] = Artical.objects.filter(pk=self.kwargs[artical_id])

答案 2 :(得分:-2)

如果你的网址是这样的,那就更具启发性了:

#urls.py
url(r'^comment/(?P<artical_id>[0-9]+)/$', CommentCreate.as_view()),

#views.py
class CommentCreate(CreateView):
    form_class = CommentCreateForm
    model = Comment
    queryset = Comment.objects.all()

    #That way you can spend the article in the context also
    def get_context_data(self, **kwargs):
        context = super(CommentCreate, self).get_context_data(**kwargs)
        context['artical'] = Artical.objects.get(pk=self.kwargs[artical_id])
        return context