Boun
Boun

Reputation: 123

Django - how to pass object to ModelForm via UpdateView?

I have this situation:

To edit the klient, UpdateView is used:

url(r'^klient_change/(?P<pk>\d+)/$', KlientUpdateView.as_view(), name='url_klient_change'),

Update View takes care of updating the object, it uses KlientUpdateForm

class KlientUpdateView(UpdateView):
    form_class = KlientUpdateForm
    model = Klient
    template_name = 'forms/klient_zmenit.html'

The problem is, that I need to update existing object using my own save method, which gets klient object and does something more (my save method is not complete in this example, it does a lot more).

class KlientUpdateForm(ModelForm):
    class Meta:
        model = Klient

    # This method creates and saves a database object from the data bound to the form.
    def save(self):
        #self.cleaned_data obsahuje data z formulare
        data = self.cleaned_data
        klient = get_object_or_404(Klient, klient_id =self.request.pk)
        Klient.objects.filter(klient_id = self.request.pk).update(nazev=data['nazev'], telefon=data['telefon'],)

        return klient

How can I obtain particualr object having pk from URL in modelForm? Is it possible to do this? ModelForm doesn't know anything about request. My idea was to get the object in updateview which is possible but i dont know, how to pass it to save method of that modelform.

Upvotes: 1

Views: 1933

Answers (1)

Pavel Anossov
Pavel Anossov

Reputation: 62898

In KlientUpdateForm.save, your object should be available as self.instance.

Upvotes: 3

Related Questions