使用基于类的UpdateView更新Django中的自定义用户模型

时间:2014-11-16 07:03:35

标签: python django django-forms django-views django-class-based-views

我正在使用Django 1.7.1 Python 3.4。我创建了一个自定义用户模型,现在我需要用户能够更新他们的详细信息。我需要的是,当用户转到表单更新他们的详细信息时,表单会预先填充他们的数据,即用户名,电子邮件等。到目前为止,表单显示但不包含当前用户数据。

我有以下代码:

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'),

我错过了什么?

1 个答案:

答案 0 :(得分:2)

FormView在这里不是合适的基类:它不了解模型表单,也没有定义get_object方法。请改用UpdateView