Changing data in a django modelform
- by Matt Hampel
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?