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
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.
- [Django]-Got InvalidClientIdError (invalid_request) Mismatching redirect URI. using requests_oauthlib
- [Django]-Class attribute inheritance in Django models
- [Django]-Haystack Faceted: __init__() got an unexpected keyword argument 'facet_fields'
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)
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()
.
- [Django]-How to troubleshoot – ImportError: Could not import settings 'mysite.settings' when deploying django?
- [Django]-Tastypie: JSON header to use UTF-8
- [Django]-ImportError: cannot import name connections
- [Django]-Is data in Django’s request.POST object sanitised, at least enough for direct use in an ORM query?