Django模型排除不起作用

时间:2012-05-05 05:11:36

标签: django django-forms

我在ModelForm中排除了一个字段,但它似乎不会影响表单的显示.as_p。它甚至在我实例化时都显示它!

这是ModelForm:

class WorkoutForm(ModelForm):
    class Meta:
        model = Workout
        exclude = ('user',) 

以及相关的观点:

def addworkout(request, uid):    
    thisuser = get_object_or_404(User, pk=uid)
    if request.method == 'POST':
        form = WorkoutForm(request.POST)
        if form.is_valid():
            form.save() 
            return HttpResponseRedirect('/u/'+str(uid))
    else:
        w = Workout(user=thisuser)

        #creates a form for thisuser
        form = WorkoutForm(instance = w)
    return render_to_response('addworkout.html', {'form':form, 'user':thisuser},   RequestContext(request))

以及模板:

<body>
    <p>"{{request.path}}" </p>
    Add a new workout, {{user.name}}! 
    <form action="/u/1/addworkout" method="POST">{% csrf_token %} 
    {{ form.as_p }} 

    <input type="submit" value= "Submit" />
    </form>
</body>

1 个答案:

答案 0 :(得分:1)

这是什么?

else:
    w = Workout(user=thisuser)

不应该是这样的:

w = Workout.objects.get(user=thisuser)

如果是的话,是否修复了错误?

POST请求区块中,您还需要传递实例form = WorkoutForm(request.POST, instance=w)

重写,您的观点应如下所示:

def addworkout(request, uid):
    thisuser = get_object_or_404(User, pk=uid)
    w = get_object_or_404(Workout, user=thisuser)
    form = WorkoutForm(instance = w)

    if request.method == 'POST':
        form = WorkoutForm(request.POST, instance=w)
        if form.is_valid():
            form.save() 
            return HttpResponseRedirect('/u/'+str(uid))

    return render_to_response('addworkout.html', {'form':form, 'user':thisuser},   RequestContext(request))