Search code examples
pythondjangodjango-modelsdjango-formsdjango-errors

Why this django ModelForm is not valid?


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 ?


Solution

  • 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.