4

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

问题是,当我创建我的食谱时,我需要一个指向创建这个食谱的食谱的外键,但我不希望创建食谱的用户看到 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))
4

2 回答 2

8

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

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

....
recipe = form.save(commit=False)
recipe.original_cookbook = whatever_that_is
recipe.save()
...
于 2012-04-11T20:48:27.230 回答
0

这在文档中得到了回答。

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

    class Meta:
        model = Recipe
        widgets = {'cookbook': forms.HiddenInput
于 2012-04-11T20:47:07.907 回答