Python Forum

Full Version: Saving a manytomany form
You're currently viewing a stripped down version of our content. View the full version with proper formatting.
I have in my models two tables Article and Client, the relation is ManyToMany in client :
 articles = models.ManyToManyField(Article, through='ClientArticle')
In one page I have to a form :
class ClientDetailsForm(forms.ModelForm):
    class Meta:
        model = Client
        fields = ['email', 'nom', 'adresse', 'codepostal', 'ville', 'pays', 'articles']

    articles = forms.ModelChoiceField(
        queryset=Article.objects.all(),
        widget=forms.RadioSelect,
        required=False
    )

    def __init__(self, *args, **kwargs):
        instance = kwargs.get('instance')
        # Utilisez l'article associé à l'instance ou utilisez tous les articles par défaut
        article_from_url = kwargs.get('initial', {}).get('article_from_url', None)
        articles_queryset = Article.objects.filter(pk=article_from_url) if article_from_url else Article.objects.all()

        # Ajustez le queryset pour le champ 'articles'
        self.fields['articles'].queryset = articles_queryset

        super(ClientDetailsForm, self).__init__(*args, **kwargs)

        self.helper = FormHelper()
        self.helper.form_method = 'post'
        self.helper.add_input(Submit('submit', 'Enregistrer'))
When I show the page I have an Url like this /articles/24/client/details/45, 24 is the article ID and 45 is the client ID.
The page shows the client fields where some already filled.

How can I save the form, I have an error :
Error:
TypeError at /articles/24/client/details/45 'Article' object is not iterable Request Method: POST Request URL: http://127.0.0.1:8000/articles/24/client/details/45 Django Version: 5.0.1 Exception Type: TypeError Exception Value: 'Article' object is not iterable
Thanks in advance,
Jean-Marie
Line 7 'Article' never defined
The error is for 'Article' not 'articles' not case and plural, not singular.
Obviously, there is some related code that isn't posted. Article would raise a NameError if it was not defined. My guess is Article is a class, something like this from the django documentation:
class Article(models.Model):
    pub_date = models.DateField()
    headline = models.CharField(max_length=200)
    content = models.TextField()
    reporter = models.ForeignKey(Reporter, on_delete=models.CASCADE)
I wonder if the problem is here:
    articles = forms.ModelChoiceField(
        queryset=Article.objects.all(),
        widget=forms.RadioSelect,
        required=False
    )
I would set queryset=None since you update the quereset in the __init__ method.