What I would like to do is to display a single form that lets the user:
- Enter a document title (from
Documentmodel) - Select one of their
user_defined_codechoices from a drop down list (populated by theUserDefinedCodemodel) - Type in a
unique_code(stored in theCodemodel)
I’m not sure how to go about displaying the fields for the foreign key relationships in a form. I know in a view you can use document.code_set (for example) to access the related objects for the current document object, but I’m not sure how to apply this to a ModelForm.
My model:
class UserDefinedCode(models.Model):
name = models.CharField(max_length=8)
owner = models.ForeignKey(User)
class Code(models.Model):
user_defined_code = models.ForeignKey(UserDefinedCode)
unique_code = models.CharField(max_length=15)
class Document(models.Model):
title = models.CharField(blank=True, null=True, max_length=200)
code = models.ForeignKey(Code)
active = models.BooleanField(default=True)
My ModelForm
class DocumentForm(ModelForm):
class Meta:
model = Document
In regards to displaying a foreign key field in a form you can use the
forms.ModelChoiceFieldand pass it a queryset.so, forms.py:
views.py:
from your question:
Actually, your
Documentobjects wouldn’t have a.code_setsince the FK relationship is defined in your documents model. It is defining a many to one relationship toCode, which means there can be manyDocumentobjects perCodeobject, not the other way around. YourCodeobjects would have a.document_set. What you can do from the document object is access whichCodeit is related to usingdocument.code.edit: I think this will do what you are looking for. (untested)
forms.py:
views.py:
actually you probably want to use get_or_create when creating your Code object instead of this.