如何使用ModelForm保存用户输入表单中的数据

时间:2012-01-11 05:54:57

标签: python django forms post

我想我错过了如何使用ModelForm和Forms来保存数据库中数据的关键基础。我有一个UserProfile模型,它存储未包含在User类

中的特定数据

Models.py:

class UserProfile(models.Model):
    GRADE_YEAR_CHOICES = (
        ('FR', 'Freshman'),
        ('SO', 'Sophomore'),
        ('JR', 'Junior'),
        ('SR', 'Senior'),
        ('GR', 'Graduate')
    )

    school = models.CharField(max_length=64)
    grade_year = models.CharField(max_length=2, choices=GRADE_YEAR_CHOICES)
    gpa = models.DecimalField(decimal_places=2, max_digits=6, blank=True, null=True)
    user = models.ForeignKey(User, unique=True)

我的 Forms.py 如下所示:

class UserProfileForm(ModelForm):
    class Meta:
        model = UserProfile

View for this看起来像:

def more(request):
    if request.method == 'POST':
        form = UserProfileForm(request.POST)
        if form.is_valid():
            form = UserProfileForm(request.POST,
                school = form.cleaned_data['school'],
                grade_year = form.cleaned_data['grade_year'],
                gpa = form.cleaned_data['gpa'],
                user = form.cleaned_data['user']
            )
            form.save()
            return HttpResponseRedirect('/success')
    else:
        form = UserProfileForm()

        variables = RequestContext(request, {
            'form': form
        })
        return render_to_response('more.html', variables)

表单正确呈现了我指定的模型中的所有字段,但是当我尝试保存数据时,我得到了:

__init__() got an unexpected keyword argument 'grade_year'

我在这里缺少什么?我意识到我可能会错过一个大概念,所以任何帮助都会受到高度赞赏。

1 个答案:

答案 0 :(得分:1)

您正在传递UserProfileForm一个关键字参数,该参数引用您不期望的模型字段。

在表单实例化后简单地调用save() - 如果它有cleaned_data(即表单有效),则POSTed字段已经通过ModelForm magic映射到实例。

   if form.is_valid():
            form.save()