using a foreign key with multiple choices

106 views
Skip to first unread message

Christian

unread,
Nov 13, 2018, 7:45:11 AM11/13/18
to django-users

Hello

I need to use a model form to create a new instance of Recette,  using multiple choices list instead of the foreign_key

class Recette(models.Model):
  ......
    categoriederecette = models.ForeignKey(Categorie, on_delete=models.CASCADE)

class Categorie(models.Model):
    SOUPE = 'SP'
    DESSERTS ='DS'
    PLATUNIQUE ='PU'
    LISTE_CHOIX =  ((SOUPE,'Soupe'), (DESSERTS,'Desserts'), (PLATUNIQUE,'Plat unique'),)
   .....
    categorierecette = models.CharField(db_column='Categorierecette', max_length=15, choices=LISTE_CHOIX, blank=True, null=True)  # Field name made lowercase....

I use a Modelform :

class RecettesForm(forms.ModelForm):
    categoriederecette = forms.ChoiceField(choices = Categorie.LISTE_CHOIX)
  
    class Meta:
        model = Recette
        fields = (...... ,'categoriederecette')


The form is displayed correctly,  but cannot be saved. In the test if form.is_valid():  I get a value error -

ValueError: Cannot assign "'SP'": "Recette.categoriederecette" must be a "Categorie" instance.

Any help would be greatly appreciated.

amit pant

unread,
Nov 13, 2018, 11:58:37 PM11/13/18
to django...@googlegroups.com
use dict in   LISTE_CHOIX.

--
You received this message because you are subscribed to the Google Groups "Django users" group.
To unsubscribe from this group and stop receiving emails from it, send an email to django-users...@googlegroups.com.
To post to this group, send email to django...@googlegroups.com.
Visit this group at https://groups.google.com/group/django-users.
To view this discussion on the web visit https://groups.google.com/d/msgid/django-users/524c62ab-2454-7746-ec6a-9c7daeed775d%40yahoo.fr.
For more options, visit https://groups.google.com/d/optout.

Jani Tiainen

unread,
Nov 14, 2018, 12:09:25 AM11/14/18
to django...@googlegroups.com
Well categoriederecette is a foereign key to your Categorie model. 

Your models don't make any real sense.

If your categories are fixed you can remove foreign key and add charfield and definitions directly to Recette model.

If you expect that categories are added, changed, created or deleted frequently having your current structure is okayish. Just make a name field in Categorie model as free text.

--
Reply all
Reply to author
Forward
0 new messages