0

假设我有一个处理食谱的模型,我想允许用户通过表单输入他们自己的食谱。然后我想将该食谱条目与输入它的用户的用户 ID 相关联。我的猜测是我的模型看起来像这样:

class Recipe(models.Model):
    name = models.CharField(max_length=100)
    body = models.TextField()
    creator = models.ManyToManyField(User)

    def __unicode__(self):
        return self.creator

那是对的吗?如果我创建了一个模型表单,它看起来像这样:

class RecipeForm(ModelForm):
    class Meta:
        model = Recipe

但是,我将如何在提交时自动将用户信息传递给 Recipe 模型?在我看来这会发生吗?

我目前的看法是这样的:

def recipe(request):
    if request.method == 'POST':
        form = RecipeForm(request.POST) #if POST method, bound form to POST data
        if form.is_valid():         
            form.save()
    else:
        form = RecipeForm() #unbound form.
    recipe_list = Recipe.objects.all()
    return render_to_response('forms/recipes.html',
        {'form': form, 'recipe_list': recipe_list},
        context_instance = RequestContext(request)) 

在保存之前如何将用户设置为模型?

4

2 回答 2

2

是的,您的视图需要在保存之前在配方模型上设置用户。

于 2012-04-08T04:54:46.087 回答
2

编辑:

您应该接受 Ignacio 的回答,因为他在评论中添加了它。

以下是添加用户的方法:

from django.shortcuts import render

def recipe(request):
    if request.method == 'POST':
        form = RecipeForm(request.POST) #if POST method, bound form to POST data
        if form.is_valid():         
            obj = form.save(commit=False) # don't save to DB
            obj.creator = request.user # adds the user
            obj.save()
    else:
        form = RecipeForm() #unbound form.
    recipe_list = Recipe.objects.all()
    return render(request,'forms/recipes.html',
        {'form': form, 'recipe_list': recipe_list}) 
于 2012-04-08T05:18:22.477 回答