如何在此示例中向django用户配置文件添加字段?

时间:2017-01-03 22:19:26

标签: django forms django-userena

我正在使用Django-userena扩展用户个人资料行为。

我要做的是覆盖userena / forms.py中的edit_profile函数,或者从myapp / forms.py处理此函数。

在myapp / models.py中,我添加了我想要包含在表单中的新字段。

models.py

class MyProfile(UserenaBaseProfile):
    user = models.OneToOneField(User,unique=True,verbose_name=_('user'),related_name='my_profile')
    storename=models.CharField(null=True, blank=True, max_length=20)
    streetaddress=models.CharField(null=True, blank=True, max_length=30)
    city = models.CharField(null=True, blank=True, max_length=20)
    state = models.CharField(null=True, blank=True, max_length=20)
    zipcode = models.IntegerField(_('zipcode'),null=True, blank=True)
    nearbyzips1=models.IntegerField(null=True, blank=True)
    nearbyzips2=models.IntegerField(null=True, blank=True)

我的问题是我要在userena中添加哪些表单或views.py来保存这些属性?

userena / forms.py

class EditProfileForm(forms.ModelForm):
    """ Base form used for fields that are always required """
    first_name = forms.CharField(label=_('First name'),max_length=30,required=False)
    last_name = forms.CharField(label=_('Last name'),max_length=30,required=False)

    def __init__(self, *args, **kw):
        super(EditProfileForm, self).__init__(*args, **kw)
        # Put the first and last name at the top
        try:  # in Django < 1.7
            new_order = self.fields.keyOrder[:-2]
            new_order.insert(0, 'first_name')
            new_order.insert(1, 'last_name')
            self.fields.keyOrder = new_order
        except AttributeError:  # in Django > 1.7
            new_order = [('first_name', self.fields['first_name']), ('last_name', self.fields['last_name'])]
            new_order.extend(list(self.fields.items())[:-2])
            self.fields = OrderedDict(new_order)

    class Meta:
        model = get_profile_model()
        exclude = ['user']

    def save(self, force_insert=False, force_update=False, commit=True):
        profile = super(EditProfileForm, self).save(commit=commit)
        # Save first and last name
        user = profile.user
        user.first_name = self.cleaned_data['first_name']
        user.last_name = self.cleaned_data['last_name']
        user.save()
        return profile

我可以简单地添加

user.storename = self.cleaned_data['storename']
user.streetaddress = self.cleaned_data['streetaddress']
等等..或者还有更多吗?

userena / views.py

@permission_required_or_403('change_profile', (get_profile_model(), 'user__username', 'username'))    
def profile_edit(request, username, edit_profile_form=EditProfileForm,template_name='userena/profile_form.html', success_url=None,extra_context=None, **kwargs):

    user = get_object_or_404(get_user_model(), username__iexact=username)        
    profile = get_user_profile(user=user)  
    user_initial = {'first_name': user.first_name,'last_name': user.last_name}   
    form = edit_profile_form(instance=profile, initial=user_initial)

    if request.method == 'POST':    
        form = edit_profile_form(request.POST, request.FILES, instance=profile, initial=user_initial)

        if form.is_valid():    
            profile = form.save()

            if userena_settings.USERENA_USE_MESSAGES:    
                messages.success(request, _('Your profile has been updated.'), fail_silently=True)

            if success_url:    
                # Send a signal that the profile has changed    
                userena_signals.profile_change.send(sender=None, user=user)
                redirect_to = success_url
            else:
                redirect_to = reverse('userena_profile_detail', kwargs={'username': username})

            return redirect(redirect_to)

    if not extra_context: 
        extra_context = dict()

    extra_context['form'] = form
    extra_context['profile'] = profile

    return ExtraContextTemplateView.as_view(template_name=template_name,extra_context=extra_context)(request)

1 个答案:

答案 0 :(得分:0)

如果MyProfile类是get_profile_model()返回的模型(这在您的代码中不明确),那么这将是构建表单的模型。然后,您应该能够在表单中看到您的额外字段,并在保存表单时保存模型。

你应该需要:

user.storename = self.cleaned_data['storename']
user.streetaddress = self.cleaned_data['streetaddress']

事实上,无论如何,这都是不正确的,因为那会将这些属性保存到用户,而不是配置文件。看起来你已经从一个例子构建了这个表单,所以除非你真的想保留名字和姓氏的东西,否则我建议你重写它以使它更简单:

class MyProfileForm(forms.ModelForm):
    class Meta: 
        model = MyProfile
        exclude = ['user']

就是这样。