Ben
Ben

Reputation: 5198

Django how to get record id from ModelForm

I've been banging my head on this for weeks but I am determined to get ModelForm to work! When you process a POST with data received from a ModelForm, I understand that you need to get the original record from the database and then create a new form using that original record as the 'instance'. This is documented in the Django docs as follows:

>>> from myapp.models import Article
>>> from myapp.forms import ArticleForm

# Create a form instance from POST data.
>>> f = ArticleForm(request.POST)

# Save a new Article object from the form's data.
>>> new_article = f.save()

# Create a form to edit an existing Article, but use
# POST data to populate the form.
>>> a = Article.objects.get(pk=1)
>>> f = ArticleForm(request.POST, instance=a)
>>> f.save()

In this example they know that the pk of the record they are looking for is 1. BUT, how do you know the pk if you're reading data from request.POST, assuming that the POST is based on data you previously wrote to the screen? ModelForm doesn't store the pk. So, from where do you pick this up? Without it, how do you know which record to pull out of the DB (as in 'a' above)?

Thanks!

Ben

Upvotes: 0

Views: 855

Answers (1)

user4691348
user4691348

Reputation:

You can use named groups in URLs to pass arguments to your view.

So if you have an url like :

url(r'^articles/update/(?P<article_id>[0-9]+)/$', views.update_article)

you could use in your view:

def update_article(request, article_id=None):
    pass

Upvotes: 1

Related Questions