Python Forum
Thread Rating:
  • 0 Vote(s) - 0 Average
  • 1
  • 2
  • 3
  • 4
  • 5
Saving a manytomany form
#1
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
deanhystad write Mar-02-2024, 06:14 PM:
Please post all code, output and errors (it it's entirety) between their respective tags. Refer to BBCode help topic on how to post. Use the "Preview Post" button to make sure the code is presented as you expect before hitting the "Post Reply/Thread" button.
Reply


Messages In This Thread
Saving a manytomany form - by polaije - Mar-02-2024, 06:10 PM
RE: Saving a manytomany form - by Larz60+ - Mar-04-2024, 12:02 PM
RE: Saving a manytomany form - by deanhystad - Mar-04-2024, 06:32 PM

Forum Jump:

User Panel Messages

Announcements
Announcement #1 8/1/2020
Announcement #2 8/2/2020
Announcement #3 8/6/2020