Django:将用户与模型实例相关联

时间:2012-04-08 04:52:21

标签: django many-to-many

假设我有一个处理食谱的模型,我希望允许用户通过表单输入自己的食谱。然后,我想将该配方条目与输入它的用户的用户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)) 

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

2 个答案:

答案 0 :(得分:2)

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

答案 1 :(得分: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})