2011-08-01 45 views
1

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

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

那么我应该创建1周的ModelForm为与我相关的2款车型?或每个模型的模型?如果我做了一个,我将如何从另一个模型中排除字段?我有点困惑。

回答

1

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

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

3.如果我做了一个,我将如何从另一个模型中排除字段? 如果您为每个模型创建模型表单,则可以在其各个模型表单中使用exclude

说的如:

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

谢谢,这个回答我的问题。但是现在,我会有一个或多个视图功能吗?如果2,每个人都会直接进入同一页面? – Morano88

+1

如果你只是添加,更新,删除条目而烦恼,那么我建议你看看[通用视图](https://docs.djangoproject.com/en/dev/ref/generic-views/?from=olddocs #创建更新,删除泛型视角)。如果您希望灵活性更好,请为每个模型创建视图和模板。 – Pannu