I searched the same thing on net and got many answers but some how dint get working with any of them.
Table:
- Report: reportType(foreign key from ReportCategory), name, description
- Report Category: name, description
forms.py
class ReportForm_insert(forms.ModelForm):
class Meta:
model=Report
invent = ReportCategory.objects.all()
print invent
reportType_id = forms.ModelMultipleChoiceField(queryset = invent)
fields =('name','description',)
model.py
class ReportCategory(models.Model):
name = models.CharField(max_length=20)
description = models.CharField(max_length=20)
def __unicode__(self):
return self.name
class Report(models.Model):
reportType = models.ForeignKey(ReportCategory)
name = models.CharField(max_length=200)
description = models.CharField(max_length=300)
def __unicode__(self):
return self.name
Now, inside the meta class I am trying to do two things:
Firstly, populating the Report Type dropdown box with the value from
the ‘name’ column of ReportCategory table.
Secondly, when all the other fields in the form are filled by the user
and the button is pressed, the data in the fields should be saved in
the Report table keeping in mind the foreign key constraint it has
from the ReportCategory table.
In forms.py
That is it. Django automatically understands that a drop down has to be created when we declare it as a Foreign key in the model.