Sebastian
Sebastian

Reputation: 23

Passing and accessing value in Django form

I'm trying to pass info to my form and I have a bit of a struggle with that. My code looks as follows:

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}}

As you can see I'd like to access Container_id value in my form_page.html. Unfortunately, nothing is there. What I also noticed, that with __init__ I had to add, now values are empty in my form. Before I added __init__ all values were properly passed (well, except Container_id).

Could you recommend how I can pass such value to be accessed in the form template?

Upvotes: 1

Views: 36

Answers (1)

willeM_ Van Onsem
willeM_ Van Onsem

Reputation: 476547

You can render this with:

{{ form.Container_id }}

In your form you should first pop the container_id from the kwargs, like:

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)

Use the context over the form

That being said, it is a bit strange that you pass this to the form, and not add this to the context data. You can simplify your view a lot to:

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 automatically fetches a single element based on the pk_url_kwarg [Django-doc]. You only need to set it correctly, so here that is the object_id.

In that case, we can simply render this with:

{{ container_id }}

and you do not need to store this in the form.

Upvotes: 1

Related Questions