Instanting ModelForm with where modelfields are overwritten - django

I have a ModelForm field that is based on the following Model:
class Phrase(models.Model):
subject = models.ForeignKey(Entity) # Entity is unique on a per Entity.name basis
object = models.ForeignKey(Entity) # Entity is unique on a per Entity.name basis
The modelform (PhraseForm) has a field 'subject' that is a CharField. I want users to be able to enter a string. When the modelform is saved, and the string does not match an existing Entity, a new Entity is created.
This is why I had to overwrite the "subject" field of the Modelform, as I cannot use the automatically generated "subject" field of the Modelform (I hope I'm making myself clear here).
Now, all tests run fine when creating a new Phrase through the modelform. But, when modifying a Phrase:
p = Phrase.objects.latest()
pf = PhraseForm({'subject': 'anewsubject'}, instance=p).
pf.is_valid() returns False. The error I get is that "object" cannot be None. This makes sense, as indeed, the object field was not filled in.
What would be the best way to handle this? I could of course check if an instance is provided in the init() function of the PhraseForm, and then assign the missing field values from the instance passed. This doesn't feel as if it's the right way though, so, is there a less cumbersome way of making sure the instance's data is passed on through the ModelForm?
Now that I'm typing this, I guess there isn't, as the underlying model fields are being overwritten, meaning the form field values need to be filled in again in order for everything to work fine. Which makes me rephrase my question: is the way I've handled allowing users to enter free text and linking this to either a new or existing Entity the correct way of doing this?
Thanks in advance!

Why are you modifying using the form.
p = Phrase.objects.latest()
p.subject = Entity.objects.get_or_create(name='anewsubject')[0]
docs for get_or_create
If you are actually using the form it should work fine:
def mod_phrase(request, phrase_id=None):
phrase = get_object_or_404(Phrase, pk=phrase_id)
if request.method == 'POST':
form = PhraseForm(request.POST, instance=phrase)
if form.is_valid():
form.save()
return HttpResponse("Success")
else:
form = PhraseForm(instance=phrase)
context = { 'form': form }
return render_to_response('modify-phrase.html', context,
context_instance=RequestContext(request))
Setting the instance for the ModelForm sets initial data, and also lets the form know which object the form is working with. The way you are trying to use the form, you are passing an invalid data dictionary (lacks object), which the form is correctly telling you isn't valid. When you set the data to request.POST in the example above, the request.POST includes the initial data which allows the form to validate.

Related

Using django form validation for inlineformset without a POST

In my django app, a user can create a Document model object by either 1) entering data into a form or 2) copying an existing Document. In the second case, I want to use is_valid to confirm that the existing Document is still valid (validity rules may have changed since its creation). I have this working like so:
doc = original_doc.clone()
form = DocumentForm(data=doc.__dict__, instance = doc)
if form.is_valid():
# doc is valid
else:
... do stuff ...
Now I need to do the same for an inlineformset. Each Document can have 1 or more Item, and I use inline formset for cross-field validation that depends on both a Document field and an Item field. I have this:
ItemFormSet = inlineformset_factory(Document,
Item, form=ItemForm, formset=CustomItemFormSet)
item_formset = ItemFormSet(data= XXX, instance = doc,
queryset=doc.item_set, doc_form=form)
if item_formset.is_valid():
# item_formset is valid
else:
... do stuff...
My question is: how do I obtain values for the data parameter (XXX) in the ItemFormSet call? When I display a form to the user, I can use request.POST. Without that, do I need to manually reconstruct the dictionary field by field? It gets complicated due to the data that formsets prepend to the field names, like: 'id_item_set-0-field_name'.
My apologies if my question was not straightforward, but I did find a way forward, and will post here in case others find it helpful.
Basically, as far as I found, YES, I do need to manually reconstruct the dictionary field to pass to the ItemFormSet constructor, to create the management form data. Given the single 'item' variable that I wanted to test for validation, I created a dictionary containing item's fields and then added management form data:
item_dict = item.__dict__
item_dict_itemset = {}
for key, value in item_dict.iteritems():
item_dict_itemset["item_set-0-{}".format(key)] = value
item_dict_itemset["item_set-INITIAL_FORMS"] = 0
item_dict_itemset["item_set-MIN_NUM_FORMS"] = 0
item_dict_itemset["item_set-MAX_NUM_FORMS"] = 1000
item_dict_itemset["item_set-TOTAL_FORMS"] = 1
item_formset = ItemFormSet(data-item_dict_itemset, instance=doc, queryset=doc.item_set)
formset_is_valid = item_formset.is_valid()

Accesing information from a POST form in django 1.6

I have a couple of forms, one is created from as a ModelForm and the other is a simple Form. Both of them are used in a request.POST, and to obtain the information from them I am using to different methods:
For the ModelForm form, I do this:
form = ApplicantForm(request.POST)
if form.is_valid():
applicant = form.save(commit=False)
applicant.confirmation_code = '999999'
applicant.save()
For the simple form, I am using:
form = ConfirmationCode(request.POST)
code = request.POST['confirmation_code']
confirmation_id=request.POST['confirmation_id']
As you can see, to access the information in the first form I am using the "form.save.ANYFIELD", and for the second one I am using "request.POST['ANYFIELD']. Is it possible to access the the information in the first form using the request.POST methods even if it hasnt been saved? Which is better?
You can try like this for modelform:
form = ApplicantForm(request.POST)
if form.is_valid():
app_code= form.cleaned_data['confirmation_code'] #assuming confirmation_code is a field in your modelform
.....
You seem a bit confused about what saving is doing in a modelform. When you call form.save(), you're creating a new instance of the model the form is associated with, and (unless you specify commit=False) saving that data to the database. Because you have an instance, you can use any of the normal model instance methods and access patterns.
If you want to use a form without an associated model, you can't call save - because there's nothing to save, and no model to create an instance of - but you should access the data via the form.cleaned_data dictionary after you call form.is_valid(). This is because the data in cleaned_data has been validated according to the rules in the form, and converted into the relevant types where necessary: for instance, if you had an IntegerField in your form called my_number, request.POST['my_number'] will be a string like "3" but form.cleaned_data['my_number'] will be an actual integer, 3.

Django: Change the DOM id at form field level

I understand that, by default, Django auto-populates id for each form field upon rendering with the format id_for_%s. One can modify the format by providing the auto_id argument with a different format as its value to the Form constructor.
That's not exactly what I am looking for, however. What I want to accomplish is changing the id of just one of the many fields in my form. Also, the solution should not break the use of form = MyForm(request.POST).
PS. MyForm is a model form, so each id is derived from its corresponding Model field.
Thanks for helping out.
The forms framework appears to generate labels here:
def _id_for_label(self):
"""
Wrapper around the field widget's `id_for_label` class method.
Useful, for example, for focusing on this field regardless of whether
it has a single widget or a MutiWidget.
"""
widget = self.field.widget
id_ = widget.attrs.get('id') or self.auto_id
return widget.id_for_label(id_)
id_for_label = property(_id_for_label)
Which means you can just supply your field widget with an "id" key to set it to whatever you'd like.
foo = forms.CharField(widget=forms.TextInput(attrs={'id': 'foobar'}))
Or override init and set the attrs after form initialization.
I don't see how this could break a form as django's forms framework isn't ever aware of HTML ids (that data is not passed to the server...)

How can I access the data in a Django form field form a view?

I have a simple Django Form:
class testForm(forms.Form):
list = forms.CharField()
def getItems(self):
#How do I do this? Access the data stored in list.
return self.list.split(",") #This doesn't work
The list form field stores a csv data value. From an external instance of testForm in a view, I want to be able to look at the .csv value list stored in the form field.
Like others have already mentioned, you need to make use of the form's cleaned_data dictionary attribute and the is_valid method. So you can do something like this:
def getItems(self):
if not self.is_valid():
return [] # assuming you want to return an empty list here
return self.cleaned_data['list'].split(',')
The reason your method does not work is that the form fields are not your typical instance variables. Hope this helps!
What you usually do in django in a view to get the form data would be something like this.
form = testForm(request.POST)
if form.is_valid:
# form will now have the data in form.cleaned_data
...
else:
# Handle validation error
...
If you want to do some data formatting or validation yourself you can put this in the validation method in the form. Either for the entire form or for a form field. This is also a great way to make your code more DRY.
There are a couple of things you need to know here.
First is that generally in a Python class method you access the attributes through the 'self' object. So in theory your function should be:
def get_items(self):
return self.list.split(",")
However, in the case of a Django form, this won't work. This is because a field doesn't have a value of its own - the value is only attached to the field when it's rendered, and is obtained in different ways depending on whether the value was applied through initial data or by passing in a data dictionary.
If you have validated the form (through form.is_valid()), you can get the form via the cleaned_data dictionary:
return self.cleaned_data['list']
However this will fail if list has failed validation for any reason.
Call is_valid on the form, then access the cleaned_data dictionary.

Changing data in a django modelform

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?
I would suggest writing a helper factory function for your form set so that you can customize the display widget according to the data. Something like the following:
def make_entry_formset(initial_obj=None, custom_widget=forms.Textarea):
# these will be passed as keyword arguments to the ModelChoiceField
field_kwargs={'widget': custom_widget,
'queryset': Entity.objects.all()}
if initial_obj is not None:
field_kwargs.update({'initial': initial_obj})
class _EntryForm(forms.ModelForm):
entity = forms.ModelChoiceField(**field_kwargs)
class Meta:
model = Entry
return modelformset_factory(Entry, form=_EntryForm)
Then in your view code you can specify the widget you want and whether to bind to an initial Entity object. For the initial rendering of the formset, where you just want a Textarea widget and no initial choice, you can use this:
formset_class = make_entry_formset(custom_widget=forms.Textarea)
entry_formset = formset_class()
Then if you want to render it again (after the is_valid() block) with the Entity object already defined, you can use this:
formset_class = make_entry_formset(initial_obj=entity,
custom_widget=forms.HiddenInput)
entry_formset = formset_class(request.POST, request.FILES)
You can use any widget you like, of course, but using a HiddenInput would prevent the end user from interacting with this field (which you seem to want to bind to the entity variable you looked up).