Updating Custom User Model in Django with Class Based UpdateView

落爺英雄遲暮 提交于 2019-12-13 05:25:11

问题


I am using Django 1.7.1 with Python 3.4. I created a custom user model and now I have a need for users to be able to update their details. What I need is that, when users go to the form to update their details, the form is pre-populated with their data i.e. username, email and so on. So far, the form is showing but not with the current user data.

I have the following code:

models.py

from django.contrib.auth.models import AbstractBaseUser, BaseUserManager, PermissionsMixin

... # Some code left out for brevity

class AuthUser(AbstractBaseUser, PermissionsMixin):
    """
    A fully featured User model with admin-compliant permissions that uses
    a full-length email field as the username.

    Email and password are required. Other fields are optional.
    """
    username = models.CharField(_('username'), max_length=30, unique=True, 
        help_text=_('Required. 30 characters or fewer. Letters, numbers and @/./+/-/_ characters'), 
        validators=[validators.RegexValidator(re.compile('^[\w.@+-]+$'), _('Enter a valid username.'), _('invalid'))])

    email = models.EmailField(_('email address'), max_length=254, unique=True)

    is_staff = models.BooleanField(_('staff status'), default=False,
        help_text=_('Designates whether the user can log into this admin site.'))

    is_active = models.BooleanField(_('active'), default=True,
        help_text=_('Designates whether this user should be treated as '
                    'active. Unselect this instead of deleting accounts.'))

    date_joined = models.DateTimeField(_('date joined'), default=timezone.now)

    objects = AuthUserManager()

    USERNAME_FIELD = 'email'
    REQUIRED_FIELDS = ['username'] # Not needed since it has been mentioned in USERNAME_FIELD and is required by default and cannot be listed in REQUIRED_FIELDS

    class Meta:
        verbose_name = _('user')
        verbose_name_plural = _('users')

    def get_absolute_url(self):
        return "/users/%s/" % urlquote(self.username)

    def __str__(self):
        return self.username

    def get_full_name(self):
        # The user is identified by their email address
        return self.email

    def get_short_name(self):
        # The user is identified by their username
        return self.username 

    def email_user(self, subject, message, from_email=None):
        """
        Sends an email to this User.
        """
        send_mail(subject, message, from_email, [self.email])

forms.py

from django.contrib.auth.forms import UserChangeForm
from .models import AuthUser

class AuthUserChangeForm(UserChangeForm):
    """
    A form for updating users. Includes all the fields on the user, but 
    replaces the password field with admin's password hash display field.
    """
    password = ReadOnlyPasswordHashField(label="password",
                                         help_text="""Raw passwords are not stored, so there is no way to see this
                                         user's password, but you can change the password using <a href=\"password/\">
                                         this form</a>""")

    class Meta:
        model = AuthUser
        fields = ('username', 'email', 'password', 'is_active', 'is_staff', 'is_superuser', 'user_permissions')
        widgets = {
            'email': TextInput(),
        }

    def clean_password(self):
        # Regardless of what the user provides, return the initial value.
        # This is done here, rather than on the field, because the field does 
        # not have access to the initial value
        return self.initial["password"]

views.py

class UpdateUserView(LoginRequiredMixin, FormView):

    template_name = 'users/update_user.html'
    form_class = AuthUserChangeForm

    # get current user object
    def get_object(self, queryset=None): 
        return self.request.user

urls.py

url(r'^profile/update/', UpdateUserView.as_view(), name='update_profile'),

What I'm I missing?


回答1:


FormView is not the appropriate base class here: it doesn't know about model forms and doesn't define a get_object method. Use UpdateView instead.



来源:https://stackoverflow.com/questions/26954694/updating-custom-user-model-in-django-with-class-based-updateview

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!