2👍
First you need a relation between the article and author. If you have models like this:
class Author(models.Model):
name = models.CharField(max_length=200)
class Article(models.Model):
title = models.CharField(max_length=200)
author = models.ForeignKey(Author)
Than an Article
belongs to an Author
and a Author
can have many Article
s.
A modelForm based on the Author
model lets you add (or modify) an author. A modelForm based on Article
lets you add (or modify) an article. Thats all very useful but not in this case. We need a normal form with ModelChoiceFields to select author and article:
class ArticleForm(forms.Form):
author = forms.ModelChoiceField(queryset=Author.objects.all())
article = forms.ModelChoiceField(queryset=Article.objects.all())
This form will have a select widget for both author
and article
field. It let’s you select one of each. It will render all authors and all articles to template. That’s okay if you have a few, but will be problematic with many entries.
The next part is to filter the article choices. The answer to this is a bit harder. Because it depends on your project requirements.
- You might want to write some JavaScript to filter the select fields
based on author. - You might want to add a validator for fields that
depend on each other. - You might not want to load all articles in
advance and might want to use Ajax techniques to load the articles
belonging to an author. - You might want to use the FormWizard to split your form in multiple pages/steps.
- …