开发者

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

开发者 https://www.devze.com 2023-01-06 23:10 出处:网络
I\'m using modelform in django to insert and update objects in my database, but when I try to update I cannot see the primary key/id of the object being updated:

I'm using modelform in django to insert and update objects in my database, but when I try to update I cannot see the primary key/id of the object being updated:

My model:

class Category(models.Model):
    name = models.CharField(max_length=20, db_index = True)

and my form:

class CategoryForm(ModelForm):
    class Meta:
        model = Category
        fields = ['name']

and in my template I got:

{% csrf_token %}
{{ category_form.as_p  }}

In my view I do

cat = Category.objects.get(pk = cat_id)
data['category_form'] = CategoryForm(instance = cat)

and pass the data to my template, which renders the form ok, but the id of the object I ab开发者_运维知识库out to update is nowhere in the html source. How can the code then now what object to update?

I feel stupid asking this since it should be pretty basic, but I've followed all the tutorials and looked thru the django docs, googled and search this site without luck.

Thanks in advance.


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.


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)


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


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().

0

精彩评论

暂无评论...
验证码 换一张
取 消