Saving a manytomany form - Printable Version +- Python Forum (https://python-forum.io) +-- Forum: Python Coding (https://python-forum.io/forum-7.html) +--- Forum: General Coding Help (https://python-forum.io/forum-8.html) +--- Thread: Saving a manytomany form (/thread-41693.html) |
Saving a manytomany form - polaije - Mar-02-2024 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 : Thanks in advance,Jean-Marie RE: Saving a manytomany form - Larz60+ - Mar-04-2024 Line 7 'Article' never defined The error is for 'Article' not 'articles' not case and plural, not singular. RE: Saving a manytomany form - deanhystad - Mar-04-2024 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. |