【问题标题】:ModelForms with ManyToMany relationship Models in DjangoDjango中具有ManyToMany关系模型的ModelForms
【发布时间】:2011-08-01 21:03:25
【问题描述】:

我有一个关于 Django 中的 ModelForms 的问题。如果我使用 ModelForms 从模型创建表单,那么表单字段将如何链接到这些 M2M 关系?我的意思是如果我有:

模型.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})

那么我应该像我一样为彼此相关的 2 个模型创建 1 个模型表单吗?还是每个模型的模型形式?如果我这样做,我将如何从另一个模型中排除字段?我有点困惑。

【问题讨论】:

    标签: python django django-models django-forms


    【解决方案1】:

    1.我应该像我一样为相互关联的2个模型创建1个模型表单吗? 不,你不能。 Django 使用this 列表做一个模型字段来形成字段映射。相关字段显示为选择/下拉框。这些选择/下拉框填充了相关字段的现有实例。

    2.每个模型的模型形式? 最好为每个模型创建一个模型表单。

    3.如果我做一个,我将如何从另一个模型中排除字段? 如果您为每个模型创建一个模型表单,那么您可以在它们各自的模型表单中使用exclude

    比如说:

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

    【讨论】:

    • 谢谢,这回答了我的问题。但是现在,我会拥有 1 个或多个视图功能吗?如果是 2,每个都将指向同一页面?
    • 如果您只是为添加、更新、删除条目而烦恼,那么我建议您看看generic views。如果您想要更好的灵活性,请为每个模型创建一个视图和模板。
    猜你喜欢
    • 2012-02-27
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-01-16
    • 2020-02-09
    • 2012-08-27
    • 1970-01-01
    • 2014-05-20
    相关资源
    最近更新 更多