Morano88
Morano88

Reputation: 2077

ModelForms with ManyToMany relationship Models in Django

I have a question on ModelForms in Django. If I'm creating a form from a model using ModelForms, then how the form fields will be linked to these M2M relationships ? what I mean is if I have :

Models.py

class Recipe(models.Model):
    title = models.CharField(max_length=100)
    category = models.ForeignKey(Category)
    cuisineType = models.ForeignKey(CuisineType)
    description = models.TextField()
    serving = models.CharField(max_length=100)
    cooking_time = models.TimeField()
    ingredients = models.ManyToManyField(RecipeIngredient)
    directions = models.TextField()
    image = models.OneToOneField(Image)
    added_at = models.DateTimeField(auto_now_add=True)
    last_update = models.DateTimeField(auto_now=True)
    added_by = models.ForeignKey(UserProfile, null=False)
    tags = models.ManyToManyField(Tag,blank=True)

class Category(models.Model):

    category = models.CharField(max_length=100)
    category_english = models.CharField(max_length=100)
    #slug = models.SlugField(prepopulate_from=('name_english',))
    slug = models.SlugField()
    parent = models.ForeignKey('self', blank=True, null=True, related_name='child')
    description = models.TextField(blank=True,help_text="Optional")
    class Meta:
        verbose_name_plural = 'Categories'
        #sort = ['category']

Forms.py

class RecipeForm(ModelForm):
    class Meta:
        model = Recipe
        exclude = ('added_at','last_update','added_by')

Views.py

def RecipeEditor(request, id=None):
    form = RecipeForm(request.POST or None,
                       instance=id and Recipe.objects.get(id=id))

    # Save new/edited Recipe
    if request.method == 'POST' and form.is_valid():
        form.save()
        return HttpResponseRedirect('/recipes/')     #TODO: write a url + add it to urls .. this is temp

    return render_to_response('adding_recipe_form.html',{'form':form})

then should I create 1 modelform for the 2 models related to each other as I did ? or a modelform for each model ? If I do one, how I'm going to exclude fields from the other model ? I'm a bit confused.

Upvotes: 1

Views: 848

Answers (1)

Pannu
Pannu

Reputation: 2657

1.Should I create 1 model form for the 2 models related to each other as I did ? No, you cant. Django use's this list to do a model field to form field mapping. Related fields are shown as select/drop down box. These select/drop down box are populated with existing instances of the related field.

2.Model form for each model? Its better to create a model form for each model.

3.If I do one, how I'm going to exclude fields from the other model ? If you create a model form for each model then you can use exclude in their individual model forms.

say for eg:

class CategoryForm(ModelForm):
      class Meta:
            model = Category
            exclude = ('slug ')

Upvotes: 1

Related Questions