I think I am missing a key fundamental of how to use a ModelForm and Forms to save data in my database. I have a UserProfile model that is stores specific data that is not included in the User class
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)
My Forms.py looks like:
class UserProfileForm(ModelForm):
class Meta:
model = UserProfile
The View for this looks like:
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)
The form renders correctly with all of the fields from the model that I specified but when I try to save the data I get:
__init__() got an unexpected keyword argument 'grade_year'
What am I missing here? I realize that I might be missing a big concept so any help would be greatly appreciated.
You are passing
UserProfileForma keyword argument that refers to your model fields which it isn’t expecting.Simply call
save()after the form is instantiated – if it hadcleaned_data(i.e. the form is valid), then the POSTed fields are already mapped to the instance viaModelFormmagic.