karansag
karansag

Reputation: 71

Django modelforms exclude not working

I've excluded a field in a ModelForm but it doesn't seem to affect the form's display .as_p. It even displays it when I instantiate with nothing!

Here's the ModelForm:

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

and the associated view:

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))

and also the template:

<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>

Upvotes: 0

Views: 769

Answers (1)

super9
super9

Reputation: 30101

What is this?

else:
    w = Workout(user=thisuser)

Shouldn't it be something like:

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

If so, does it fix the bug?

In your POST request block, you also need to pass in the instance such that form = WorkoutForm(request.POST, instance=w)

Re-written, your view should look like this:

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))

Upvotes: 1

Related Questions