Changing data in a django modelform

Posted by Matt Hampel on Stack Overflow See other posts from Stack Overflow or by Matt Hampel
Published on 2009-07-09T23:00:57Z Indexed on 2010/06/10 6:02 UTC
Read the original article Hit count: 529

I get data in from POST and validate it via this standard snippet:

entry_formset = EntryFormSet(request.POST, request.FILES, prefix='entries')
if entry_formset.is_valid():
    ....

The EntryFormSet modelform overrides a foreign key field widget to present a text field. That way, the user can enter an existing key (suggested via an Ajax live search), or enter a new key, which will be seamlessly added.

I use this try-except block to test if the object exists already, and if it doesn't, I add it.

entity_name = request.POST['entries-0-entity']
try:
    entity = Entity.objects.get(name=entity_name)
except Entity.DoesNotExist:
    entity = Entity(name=entity_name)
    entity.slug = slugify(entity.name)
    entity.save()

However, I now need to get that entity back into the entry_formset. It thinks that entries-0-entity is a string (that's how it came in); how can I directly access that value of the entry_formset and get it to take the object reference instead?

© Stack Overflow or respective owner

Related posts about django

Related posts about django-modelforms