Note that there are some explanatory texts on larger screens.

plurals
  1. POModelForms with ManyToMany relationship Models in Django
    primarykey
    data
    text
    <p>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 :</p> <h1>Models.py</h1> <pre><code>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'] </code></pre> <h1>Forms.py</h1> <pre><code>class RecipeForm(ModelForm): class Meta: model = Recipe exclude = ('added_at','last_update','added_by') </code></pre> <h1>Views.py</h1> <pre><code>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}) </code></pre> <p>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.</p>
    singulars
    1. This table or related slice is empty.
    plurals
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload