Django中与多对多关系模型的ModelForms

1 投票
1 回答
839 浏览
提问于 2025-04-16 22:41

我有一个关于Django中ModelForms的问题。如果我使用ModelForms从一个模型创建表单,那么这些表单字段是如何与多对多关系(M2M)关联起来的呢?我的意思是,如果我有:

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})

那么我应该为这两个相关的模型创建一个modelform,就像我做的那样吗?还是应该为每个模型各创建一个modelform?如果我做一个,我该如何排除另一个模型的字段呢?我有点困惑。

1 个回答

1

1. 我应该为这两个相关的模型创建一个表单吗?

不可以。Django会使用这个列表来把模型字段和表单字段对应起来。相关的字段会显示为选择框或下拉框。这些选择框会填充已有的相关字段的实例。

2. 每个模型都需要一个表单吗?

是的,最好为每个模型单独创建一个表单。

3. 如果我只做一个表单,怎么排除另一个模型的字段呢?

如果你为每个模型创建一个表单,就可以在各自的表单中使用exclude来排除不需要的字段。

举个例子:

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

撰写回答