Buttons840
Buttons840

Reputation: 9637

With Django ModelForms, how do I including the "id" column or primary key in the HTML?

I have a Django ModelForm which I render to a page. It renders the way I expect. My problem is when I receive a POST "containing" the ModelForm, the ModelForm will not update the existing model as I would expect. This is because the ModelForm does not include a primary key in the HTML form.

Here's is the code I have an the generated HTML:

### models.py
from django.db import models

class MyModel(models.Model):
    dummy_field = models.CharField(max_length=10)


### forms.py
from django import forms
from models import MyModel

class MyForm(forms.ModelForm):
    class Meta:
        model = MyModel
        fields = ['dummy_field']


### views.py
from django.shortcuts import render_to_response
from forms import MyForm
from models import MyModel

def my_view(request):
    my_model = MyModel()
    my_model.save()
    my_form = MyForm(instance=my_model)
    return render_to_response('my_template.html', {'my_form': my_form})


### my_template.html
This is my template: {{ my_form.pk }}{{ my_form.id }}{{ my_form }}

When I visit the URL connected to the my_view view, I receive the following HTML as a response:

This is my template: <tr><th><label for="id_dummy_field">Dummy field:</label></th><td><input id="id_dummy_field" type="text" name="dummy_field" maxlength="10" /></td></tr>

As you can see from the generated HTML, there is nothing indicating the primary key of my_model which I created in my_view. Thus, when I receive the form back in a POST, I have no way of connecting the POST values with the correct Django model. What is the best way to include my_models primary key in the HTML?

I am using Django 1.4 and would prefer a compatible answer.

Upvotes: 1

Views: 710

Answers (1)

David Dahan
David Dahan

Reputation: 11162

Is this what you're looking for?

https://docs.djangoproject.com/en/1.4/topics/forms/modelforms/#the-save-method

A subclass of ModelForm can accept an existing model instance as the keyword argument instance; if this is supplied, save() will update that instance. If it’s not supplied, save() will create a new instance of the specified model

Upvotes: 2

Related Questions