【问题标题】:How to use ModelForm to save data from user input forms如何使用 ModelForm 保存用户输入表单中的数据
【发布时间】:2012-01-11 05:54:56
【问题描述】:

我认为我错过了如何使用 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

这个视图看起来像:

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'

我在这里缺少什么?我意识到我可能遗漏了一个重要概念,因此我们将不胜感激。

【问题讨论】:

    标签: python django forms post


    【解决方案1】:

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

    在表单实例化后只需调用save() - 如果它有cleaned_data(即表单是有效的),那么POSTed 字段已经通过ModelForm 魔术映射到实例。

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

    【讨论】:

    • 就是这样,哇我没想到这么简单。非常感谢
    猜你喜欢
    • 2021-01-01
    • 2022-10-02
    • 2020-02-21
    • 1970-01-01
    • 2021-01-13
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多