简体   繁体   English

用户在更新Django时丢失管理统计信息

[英]User loses admin stats when updating Django

I have the following code to edit the user: 我有以下代码来编辑用户:

View.py View.py

@login_required()
def edit_user_profile(request):

if request.method == 'POST':
    profile_form = ProfileForm(request.POST, instance=request.user.profile)
    user_form = UserForm(request.POST, instance=request.user, request=request)
    city_form = CityForm(request.POST)

    if profile_form.is_valid() and user_form.is_valid() and city_form.is_valid():

        # Updates profile
        try:
            user_profile = profile_form.save(commit=False)
            user_profile.user = user_form.save()
            user_profile.city = city_form.get_instance()

            # Save instance
            user_profile.save()
        except Exception:
            raise

        # Checks if user came from another page
        previous_page = request.GET.get('next', None)
        if previous_page:
            return HttpResponseRedirect(previous_page)

        return redirect(profile_update_success)
else:

    profile_form = ProfileForm(instance=request.user.profile)
    user_form = UserForm(instance=request.user)
    city_form = CityForm(initial={'post_nr': request.user.profile.get_city_post_code(), 'city': request.user.profile.get_city_name()})

return render(request, 'user/profile.html',
              {
                  'user': request.user,
                  'profile_form': profile_form,
                  'user_form': user_form,
                  'city_form': city_form,
              })

Forms.py Forms.py

class UserForm(ModelForm):
    first_name = forms.CharField(required=True, max_length=10, widget=forms.TextInput(attrs={'placeholder': 'First name'}))
    last_name = forms.CharField(required=True, max_length=20, widget=forms.TextInput(attrs={'placeholder': 'Last name'}))
    email = forms.EmailField(required=True, widget=forms.TextInput(attrs={'placeholder': 'E-mail'}))

    class Meta:
        model = User
        exclude = ('username', 'password', 'date_joined', )

    def clean_email(self):
        email = self.cleaned_data['email']

        try:
            user = User.objects.get(email=email)
            if self.instance.username != user.username:
                raise forms.ValidationError("This e-mail is already in use.")
        except User.DoesNotExist:
            pass
        return email

    def __init__(self, *args, **kwargs):
        self.request = kwargs.pop('request', None)
        super(UserForm, self).__init__(*args, **kwargs)


class ProfileForm(ModelForm):
    class Meta:
        model = UserProfile
        exclude = ('city', 'user',)
        widgets = {
            'company_name': forms.TextInput(attrs={'placeholder': "*Optional company name"}),
            'telephone': forms.TextInput(attrs={'placeholder': "*Optional telephone number"}),
            'mobile': forms.TextInput(attrs={'placeholder': "Mobile number"}),
        }

The problem happens every time the user updates his/her information. 每当用户更新他/她的信息时,都会发生此问题。 The account is set as "inactive". 该帐户设置为“无效”。 The same thing happens with administrators and they lose their "staff" and "superuser" status. 管理员也会发生同样的事情,他们失去了“工作人员”和“超级用户”状态。

I have also the following signal that does not work when ignoring the admin status. 我还有以下signal ,在忽略管理员状态时不起作用。 It does help preventing the account being set to "inactive". 它确实有助于防止将帐户设置为“无效”。

@receiver(pre_save, sender=User)
def update_username_from_email(sender, instance, **kwargs):
    if not instance.email or instance.is_superuser:
        return
    instance.username = instance.email
    instance.is_active = True

The user does get updated however I have these "collateral effects". 用户确实得到了更新,但是我有这些“附带影响”。

As you can see on the Django User Model those permissions you speak of are fields which you are not excluding from 'UserForm' and thus are setting False since you are seemingly not providing a value in the request.POST data. 正如您在Django用户模型上所看到的那样,您所说的那些权限是您不能从“ UserForm”中排除的字段,因此设置为False,因为您似乎未在request.POST数据中提供值。 To be 100% it would help to see how you are rendering the form, but this is most likely the problem. 达到100%有助于查看表单的呈现方式,但这很可能是问题所在。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM