的ModelForm。为什么我的表单没有填充模型中的数据?

时间:2012-10-15 15:56:07

标签: django

为什么我的表单没有填充模型中的数据?

这是我的model.py

class People(models.Model):
    user = models.OneToOneField(User)
    name = models.CharField(max_length=100)
    address = models.CharField(max_length=255)

这是我的forms.py

from django.forms import ModelForm 

class EditForm(ModelForm):
    class Meta:
        model = People
        exclude=('user',)

views.py

def edit_data(request):
    user = request.user
    people = People.objects.get(user=user)
    form = EditForm(request.POST, instance = people)
    if request.method == 'POST':
        if form.is_valid():
            form.save()
        else:
            print 'Error'
    else:
        form = EditForm()

    return render_to_response('profile.html',{'form':form}, context_instance=RequestContext(request))

profile.html

<form action="/profile/" method="post">{% csrf_token %}
{{ form.as_p }}
</form>

1 个答案:

答案 0 :(得分:2)

问题是您在form子句中重新定义elseEditForm的新实例,其中instance变量集没有设置else )。删除{{1}}(及其下面的行),你应该好好去。