Django使用Meta模型隐藏外键

时间:2012-04-11 20:41:39

标签: django forms widget foreign-keys hidden

我正在使用django在cookbook网站上工作,并在我的表单中遇到了外键字段的问题

问题是,当我创建我的食谱时,我需要一个外键指向创建此食谱的食谱但我不希望用户创建食谱来查看original_cookbook字段(他们不应该)

我相信我需要使用一个小部件(HiddenInput),但我对其他网站上给出的示例感到困惑。我的朋友也提到了在original_cookbook视图中设置初始值的一些内容

tl; dr:我想将fk指向用户的食谱,同时保持original_cookbook字段隐藏。

相关代码:

形式:

class RecipeForm(forms.ModelForm):

    class Meta:
        model = Recipe

模型:

class Recipe(models.Model):
    def __unicode__(self):
        return self.name
    original_cookbook = models.ForeignKey(Cookbook)
    #cookbooks = models.ManyToManyField('Cookbook', related_name = 'recipes')
    name = models.CharField(max_length=200)
    author = models.CharField(max_length= 100)
    picture = models.ImageField(upload_to = 'Downloads', blank=True)
    pub_date = models.DateTimeField('date published', auto_now_add=True, blank=True)
    ingredients = models.TextField()
    steps = models.TextField()
    prep_time = models.IntegerField()
    TYPE_CHOICES= (
    ('SW', 'Sandwich'),
    ('AP', 'Appetizers'),
    ('SD', 'Sauces and Dressings'),
    ('SS', 'Soups and Salads'),
    ('VG', 'Vegetables'),
    ('RG', 'Rice, Grains and Beans'),
    ('PA', 'Pasta'),
    ('BR', 'Breakfast'),
    ('MT', 'Meat'),
    ('SF', 'Seafood'),
    ('BP', 'Bread and Pizza'),
    ('DT', 'Desserts'),
    )
    type = models.CharField(max_length = 2, choices=TYPE_CHOICES)

    def index_queryset(self):
        return self.objects.all()

视图:

def createrecipe(request):
    if not request.user.is_authenticated():
        return HttpResponseRedirect('/index/')
    else:
        if request.method == 'POST':
            form = RecipeForm(request.POST)
            if form.is_valid():
                recipe = form.save()
                user = request.user
                cookbooks = user.cookbooks
                cookbook = cookbooks.all()[0]
                cookbook.recipes.add(recipe)
                return HttpResponseRedirect('/account')
        else:
            form = RecipeForm()

        return render_to_response('cookbook/createrecipe.html',
                                    {'form':form},
                              context_instance=RequestContext(request))

2 个答案:

答案 0 :(得分:8)

exclude = ('original_cookbook',)添加到表单的Meta类。

然后,在您的if form.is_valid()代码中,执行以下操作:

....
recipe = form.save(commit=False)
recipe.original_cookbook = whatever_that_is
recipe.save()
...

答案 1 :(得分:0)

这在the documentation中得到解答。

from django import forms
class RecipeForm(forms.ModelForm):

    class Meta:
        model = Recipe
        widgets = {'cookbook': forms.HiddenInput