Python 如何使用ModelForm保存用户输入表单中的数据
我想我缺少了一个关键的基础知识,即如何使用ModelForm和Forms在数据库中保存数据。我有一个UserProfile模型,用于存储用户类中未包含的特定数据 型号。py:Python 如何使用ModelForm保存用户输入表单中的数据,python,django,forms,post,Python,Django,Forms,Post,我想我缺少了一个关键的基础知识,即如何使用ModelForm和Forms在数据库中保存数据。我有一个UserProfile模型,用于存储用户类中未包含的特定数据 型号。py: class UserProfile(models.Model): GRADE_YEAR_CHOICES = ( ('FR', 'Freshman'), ('SO', 'Sophomore'), ('JR', 'Junior'), ('SR', 'Sen
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)
我的表单.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)
此项的视图如下所示:
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'
我错过了什么?我意识到我可能遗漏了一个重要的概念,因此非常感谢您提供的任何帮助。您正在传递一个关键字参数,该参数引用了您的模型字段,而这是它所不期望的 在表单实例化后,只需调用
save()
——如果它有已清理的\u数据
(即表单有效),则已通过ModelForm
magic将发布的字段映射到实例
if form.is_valid():
form.save()
就这样,哇,我没想到这么简单。多谢各位