2011-08-01 17 views
1

DjangoのModelFormsに関する質問があります。 ModelFormsを使用してモデルからフォームを作成する場合、フォームフィールドはどのようにこれらのM2M関係にリンクされますか?私が意味することは、私が持っている場合は次のとおりです。ManyToMany関係を持つModelForms Djangoのモデル

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.私は、2つのモデルが互いに関連して1つのモデルフォームを作成する必要がありますか? いいえ、できません。 Djangoはthisのリストを使用して、モデルフィールドを作成してフィールドマッピングを作成します。関連フィールドは、選択/ドロップダウンボックスとして表示されます。これらの選択/ドロップダウンボックスには、関連するフィールドの既存のインスタンスが入力されます。

2.各モデルのモデル形式? モデルごとにモデルフォームを作成する方が良いです。

3.私が1つの場合、他のモデルのフィールドをどのように除外しますか? モデルごとにモデル・フォームを作成する場合は、個々のモデル・フォームにexcludeを使用できます。

は、例えばのために言う:

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

が、これは私の質問に答え、ありがとうございます。しかし、今、私は1つ以上のビュー機能を持っていますか? 2の場合は、それぞれが同じページに移動しますか? – Morano88

+1

エントリの追加、更新、削除を気にするだけなら、[generic views](https://docs.djangoproject.com/en/dev/ref/generic-views/?from=olddocs)をご覧ください。 #create-update-delete-generic-views)を実行します。柔軟性を向上させたい場合は、各モデルのビューとテンプレートを作成してください。 – Pannu

関連する問題