以Django形式传递和访问值

时间:2019-06-09 10:40:11

标签: django

我正在尝试将信息传递给表单,对此我有些挣扎。我的代码如下:

views.py

class ObjectUpdateView(UpdateView):

    template_name = 'manage/object_form.html'
    form_class = ObjectEditForm
    def get_success_url(self):
        #...
    def form_valid(self, form):
        return super(ObjectUpdateView, self).form_valid(form)
    def get_object(self):
        return get_object_or_404(Room, pk=self.kwargs['object_id'])
    def get_form_kwargs(self, **kwargs):
        objectid = self.kwargs['object_id']
        object = Object.objects.get(id = objectid)
        container = object.container
        kwargs['container_id'] = container.id
        return kwargs

forms.py

class ObjectEditForm(forms.ModelForm):
 class Meta:
     model = Object
     fields = ['TestField']

 def __init__(self, *args, **kwargs):
     super(ObjectEditForm, self).__init__(*args, **kwargs)
     self.Container_id = kwargs.pop('container_id')

form_page.html

{{fomr.kwarg.Container_id}}

如您所见,我想在我的form_page.html中访问Container_id值。不幸的是,那里什么也没有。我还注意到,必须添加__init__,现在表单中的值为空。在我添加__init__之前,所有值都已正确传递(好,Container_id除外)。

您能推荐我如何在表单模板中传递该值吗?

1 个答案:

答案 0 :(得分:1)

您可以使用以下方式呈现此内容:

{{ form.Container_id }}

在表单中,您应该首先从kwarg中弹出container_id,例如:

class ObjectEditForm(forms.ModelForm):

    class Meta:
        model = Object
        fields = ['TestField']

    def __init__(self, *args, **kwargs):
        # first pop from the kwargs
        self.Container_id = kwargs.pop('container_id', None)
        super(ObjectEditForm, self).__init__(*args, **kwargs)

在表单上使用上下文

话虽如此,您将其传递给表单,而不是将其添加到上下文数据有点奇怪。您可以将视图简化为:

class ObjectUpdateView(UpdateView):

    template_name = 'manage/object_form.html'
    pk_url_kwarg = 'object_id'
    form_class = ObjectEditForm

    def get_success_url(self):
        #...

    def get_context_data(self, **kwargs):
        objectid = self.kwargs['object_id']
        object = Object.objects.get(id = objectid)
        context = super().get_context_data()
        context.update(container_id=object.container_id)
        return context

Django会基于pk_url_kwarg [Django-doc]自动获取单个元素。您只需要正确设置它,所以这里是object_id

在这种情况下,我们可以简单地使用以下方式呈现该信息:

{{ container_id }}

,您无需将其存储在表单中。