Reputation: 20470
I have two models:
ProcessDao
** normal fields **
resource = models.ForeignKey(ResourceData, related_name='processes')
ResourceData
** Normal Fields **
The code below is in my views.py :
pdForm = ProcessDataForm(request.POST)
rd = ResourceData.objects.get(pick_date__exact = request.POST['pick_date'])
pdForm.resource = rd <------ here is the assignment
if pdForm.is_valid():
pdForm.save()
else:
print 'pdForm is not valid ! ', pdForm.errors
# print "resource is not valid."
Is there any way to make the pdForm valid ?
Upvotes: 0
Views: 2317
Reputation: 599956
Why would you think assigning a random attribute to a form object would make it valid? There's no point at which a form uses its instance attributes to check its validity, and nothing in the documentation implies that it does.
There are a few ways to fix this properly. First, and probably ugliest, is to copy request.POST
and insert the id of the matching object into there. (You need to copy it, as the original instance is immutable).
A much better way is to exclude the field from the form altogether (via the form's Meta
class) and in the is_valid
clause do this:
object = pdForm.save(commit=False)
rd = ResourceData.objects.get(pick_date__exact = pdForm.cleaned_data['pick_date'])
object.resource = rd
object.save()
Upvotes: 1
Reputation: 405
Shouldn't you work on cleaned form to assign empty fields? Try something like:
if pdForm.is_valid():
cleanform = pdForm.save(commit = False).
cleanform.resource = rd
cleanform.save()
I'm just not sure if it will work with resource being the only field in model. I'm django noob, but it works for me with assigning ForeignKey fields in many forms.
Upvotes: 1