user3550366
user3550366

Reputation: 125

Using forms in Django

I am creating a website and have two forms. The database I have has authors and titles. What I want to do is when I click the author in my choice field, I want the titles to be filtered so the user can only select those. How would I do this?

class ArticleForm(forms.ModelForm):
    author = forms.ModelMultipleChoiceField(queryset=Article.objects.all())

    title = forms.ModelMultipleChoiceField(queryset=Article.objects.filter(author=author))

    class Meta:
        model = Article
        fields = ('author','title')

When I click the author name, the title still remains blank. What should I do?

Below is my model

class Article (models.Model):
    title = models.CharField(max_length=200)
    author = models.CharField(max_length=200)

Upvotes: 1

Views: 80

Answers (1)

allcaps
allcaps

Reputation: 11228

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

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

Upvotes: 2

Related Questions