Home > Blockchain >  How to initialize value of foreign key in Django form
How to initialize value of foreign key in Django form

Time:12-06

Im trying to initialize a model form where both fields are foreign key.

Model:

class Subcohort(models.Model):
cohort_id=models.ForeignKey(Cohort,on_delete=models.PROTECT,default=0,db_constraint=False,related_name='subcohortid')
parent_id=models.ForeignKey(Cohort,on_delete=models.PROTECT,default=0,db_constraint=False,related_name='subparentid')

Form:

class SubcohortForm(forms.ModelForm):

class Meta:
    model = Subcohort

    fields = [
        "cohort_id","parent_id",
    ]

Views:

cohortidnew = Cohort.objects.latest('id').id
initialvalue2={
     'cohort_id':int(cohortidnew),
     'parent_id':id,
}

     form2 = SubcohortForm(initialvalue2)
            
     if form2.is_valid():
          return redirect('/dashboard')

It is saying my form is not valid. Can someone explain what is the reason behind this and how to fix this? Thanks.

CodePudding user response:

Because, you have not saved that form after validation.

let's save it:

 if form2.is_valid():
      form2.save()
      return redirect('/dashboard')

And now your problem will be solved..

CodePudding user response:

If you need the form intialize with these values, then please pass the values using initial parameter when initiaiting form object:

initialvalue2={
     'cohort_id':int(cohortidnew),
     'parent_id':id,
}

form2 = SubcohortForm(initial = initialvalue2)

You can send this form2 instance to the template directly without validating it. But you should check if the form is valid on post request. For example:

if request.method == 'GET':
     form2 = SubcohortForm(initial = initialvalue2)
     return render(request, template_name, context={'form2':form2})
else:
    form = SubcohortForm(request.POST)
    if form.is_valid():
       form.save()
       return redirect('dashboard')
    else:
       return render(request, template_name, context={'form2':form})
  • Related