我使用这样的用户配置文件扩展django用户模型:
class UserProfile(BaseModel):
user = models.ForeignKey(User, unique=True, related_name="profile")
city = models.CharField(_("City"), max_length=200)
tel = models.CharField(_("Phone Number"), max_length=50,
help_text=_("(+ Country Code) (Area Code) (Your phone number)"))
description = models.TextField(null=True, blank=True,
help_text = _("Small description about yourself."))
photo = models.ImageField(max_length=255, upload_to="profiles/")
def __unicode__(self):
return "%s %s" % (self.user.first_name, self.user.last_name)
def profile_image(self):
return settings.DEFAULT_PROFILE_IMAGE
这是我在前端使用的表单,以便从那里编辑配置文件:
class UserProfileForm(forms.ModelForm):
# uniForm Helper
helper = FormHelper()
helper.form_id = "edit_profile_form"
helper.form_class = 'mlForm'
layout = Layout(
Fieldset('',
'country', 'city',
'tel', 'photo', 'description',
)
)
helper.add_layout(layout)
# Submit button(s)
submit = Submit('submit','Submit')
helper.add_input(submit)
cancel = Submit('cancel','Cancel')
helper.add_input(cancel)
class Meta:
model = UserProfile
fields = ['city',
'tel', 'photo', 'description',]
def __init__(self, request, *args, **kw):
super(UserProfileForm, self).__init__(*args, **kw)
self.request = request
def save(self, *args, **kw):
edit_profile_form = super(UserProfileForm, self).save(*args, **kw)
return edit_profile_form, "User successfully modified."
我想要做的是在表单中添加用户电子邮件字段,以便用户也可以从前端编辑此字段。
我该怎么做?
答案 0 :(得分:3)
希望,这会有所帮助
class UserProfileForm(forms.ModelForm):
email = forms.EmailField(label=u'Email address',required=True)
class Meta:
model = UserProfile
exclude = ['user',]
def __init__(self, *args, **kw):
super(UserProfileForm, self).__init__(*args, **kw)
self.fields['email'].initial = self.instance.user.email
self.fields.keyOrder = ['your','fields','you','want','to','display','including','email']
def save(self, *args, **kw):
super(UserProfileForm, self).save(*args, **kw)
self.instance.user.email = self.cleaned_data.get('email')
self.instance.user.save()
这个食谱适合我(django 1.3)。 在views.py中必须是这样的:
def profile(request,id):
if request.method == 'POST':
user = get_object_or_404(User,pk=id)
profile = user.profile
form = UserProfileForm(data = request.POST,instance = profile)
if form.is_valid():
form.save()
答案 1 :(得分:0)
将两个对象表单(UserEditForm和UserProfileForm)发送到模板表单并一起提交。