[Django]-Where's the primary key of the object I want to update in django using modelform?

0đź‘Ť

âś…

The primary key is an attribute called “id” on your instance object “cat”. The form itself, and in your example represented by “cat_id”. The Model form should takes care to track the primary key – all you should need to do is pass the resulting “request.POST” data back into CategoryForm, valid the data with is_valid() and then save it.

i.e.

form_with_post = CategoryForm(request.POST)
if form_with_post.is_valid():
    form_with_post.save()
else:
    ... return the form_with_post through the context to display the errors
👤heckj

4đź‘Ť

Where is cat_id coming from in your view? I guess you receive it in url, like so:

url( r'categories/(\d+)/edit/', your_view, {} ),

in urls.py somewhere. Now in your view you can read it from appropriate view function argument:

def your_view( request, cat_id ):

Now you can obtain object with proper id, which you do here:

cat = Category.objects.get(pk = cat_id)

…and instantiate ModelForm passing it cat object if you want to edit existing object, or don’t pass it, if you want an empty form for object creation.

👤cji

4đź‘Ť

The explanation for this can be found in the django docs here: http://docs.djangoproject.com/en/dev/topics/forms/modelforms/#the-save-method

While trying to update already saved entity you must provide an instance parameter when you recreate the form. Otherwise django will try to insert a new entity.

foo_form = FooForm(request.POST, instance=foo)
👤Piotr Duda

0đź‘Ť

The ID doesn’t need to be in the HTML, because you’ve passed the instance into the form object when you instantiate it. Django simply updates that instance when you do form.save().

Leave a comment