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

I use modelform in django to insert and update objects in my database, but when I try to update, I do not see the primary key / id of the updated object:

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 opinion, I do

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

and pass the data to my template, which displays the ok form, but the identifier of the object I'm going to update is nowhere in the html source. How is the code now, and then which object to update?

It seems to me stupid to ask about this, as it should be quite simple, but I followed all the tutorials and looked through django docs, googled and searched this site without any luck.

Thanks in advance.

+3
4

- , "id" "cat". , ​​ "cat_id". - , , - "request.POST" CategoryForm, is_valid(), .

.

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
0

cat_id ? , url, :

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

urls.py -. , , :

def your_view( request, cat_id ):

, :

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

... ModelForm, cat, , .

+4

django docs : http://docs.djangoproject.com/en/dev/topics/forms/modelforms/#the-save-method

. django .

foo_form = FooForm(request.POST, instance=foo)
+4

HTML, , . Django , form.save().

0

Source: https://habr.com/ru/post/1754632/


All Articles