Problem saving data in a modelform
I have a modelform
set up for a user to enter his contact info. The validation and form.is_valid()
method is working, however the request.POST
data is not being stored to the db, and I'm having trouble figuring out what the problem is. Here is what I currently have --
# model
class UserProfile(models.Model):
user = models.ForeignKey(User, unique=True)
contact_email = models.EmailField(max_length=100, blank=True)
contact_phone = models.IntegerField(max_length=11, blank=True)
website = models.CharField(max_length=256, blank=True)
clas开发者_开发知识库s ContactInfoForm(ModelForm):
class Meta:
model = UserProfile
fields = ('contact_email', 'contact_phone', 'website',)
# view
@login_required
def edit_contact(request):
contact_email = request.user.get_profile().contact_email
form = ContactInfoForm(initial={'contact_email':contact_email,})
if request.method == 'POST':
form = ContactInfoForm(request.POST, instance=request.user)
if form.is_valid():
form.save()
return render_to_response(...)
# template
<form action="." method="post"> {% csrf_token %}
<table>
{{form}}
</table>
<p><input type="submit" name="save_changes" value="Save Changes" ></p>
</form>
I think the error might be the instance you're calling in your ModelForm. You need to use a UserProfile instance, but you're using a User instance. The following might work (untested):
@login_required
def edit_contact(request):
contact_email = request.user.get_profile().contact_email
form = ContactInfoForm(initial={'contact_email':contact_email,})
user_profile = UserProfile.objects.get(contact_email=contact_email)
if request.method == 'POST':
form = ContactInfoForm(request.POST, instance=user_profile)
if form.is_valid():
form.save()
return render_to_response(...)
精彩评论