我设置了modelform
,以便用户输入他的联系信息。验证和form.is_valid()
方法正在运行,但request.POST
数据没有存储到数据库中,我无法确定问题所在。这是我目前的情况 -
# 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)
class 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>
答案 0 :(得分:1)
我认为错误可能是您在ModelForm中调用的实例。您需要使用UserProfile实例,但您正在使用User实例。以下可能有效(未经测试):
@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(...)