-1

我正在使用 Django-userena 来扩展用户配置文件行为。

我想要做的是要么覆盖 userena/forms.py 中的 edit_profile 函数,要么从我的 myapp/forms.py 处理这个。

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

模型.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 的 forms 或 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)
4

1 回答 1

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']

就这样。

于 2017-01-04T03:58:10.043 回答