samedi 18 juin 2016

Why can't I create a custom user in Django using the UserCreationForm?


I am able to create a user from shell by importing the custom user model but when I apply the same method after submitting the form, the user is not created. Below are the codes of my custom user model, UserCreationForm and view.

//model.py
class MyUser(AbstractBaseUser):
    email = models.EmailField(
        verbose_name='email address',
        max_length=255,
        unique = True,
)
is_active = models.BooleanField(default=True)
is_admin = models.BooleanField(default=False)

objects = MyUserManager()

USERNAME_FIELD = 'email'


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 email address
    return self.email


def __str__(self):  # __unicode__ on Python 2
    return self.email


def has_perm(self, perm, obj=None):
    "Does the user have a specific permission?"
    # Simplest possible answer: Yes, always
    return True


def has_module_perms(self, app_label):
    "Does the user have permissions to view the app `app_label`?"
    # Simplest possible answer: Yes, always
    return True


@property
def is_staff(self):
    "Is the user a member of staff?"
    # Simplest possible answer: All admins are staff
    return self.is_admin

I have extended the AbstractBaseUser as suggested in the Django docs to create a custom user model.

//forms.py
class UserCreationForm(forms.ModelForm):
    """A form for creating new users. Includes all the required
    fields, plus a repeated password."""
    email = forms.EmailField(
        label='Email',
        widget=forms.EmailInput,
        required=True,
    )
    password1 = forms.CharField(
        label='Password',
        widget=forms.PasswordInput,
        required=True
    )
    password2 = forms.CharField(
        label='Password confirmation',
        widget=forms.PasswordInput,
        required=True
    )

    class Meta:
        model = MyUser
        fields = ('email', 'password1', 'password2')

    def clean_password2(self):
        # Check that the two password entries match
        password1 = self.cleaned_data.get("password1")
        password2 = self.cleaned_data.get("password2")
        if password1 and password2 and password1 != password2:
            raise forms.ValidationError("Passwords don't match")
        return password2

    def save(self, commit=True):
        # Save the provided password in hashed format
        user = super(UserCreationForm, self).save(commit=False)
        user.set_password(self.cleaned_data["password1"])
        if commit:
            user.save()
        return user

Am I doing incorrect form processing. The form.save() method didn't work out for me. Also the docs don't discuss user registration thoroughly. I don't know why.

//views.py
def login(request):
    if request.method == 'POST':
        form = AuthenticationForm(data=request.POST)
        if form.is_valid():
            user = authenticate(email=request.POST['email'],
                                password=request.POST['password'])
            if user is not None:
                if user.is_active:
                    django_login(request, user)
                    return redirect('/home/', permanent=True)

    else:
        form = AuthenticationForm()
    return render(request, 'buymeauth/login.html', {'form': form})

    def register(request):
        user = request.user

    if request.method == 'POST':
        form = UserCreationForm(data=request.POST)
        if form.is_valid():
            my_user = MyUser(user.email, user.password)
            my_user.save()

            return redirect('/home/', permanent=True)
    else:
        form = UserCreationForm()

    return render(request, 'buymeauth/register.html', {'form': form})

I am new to Django but not particularly to web development. I have some exposure with MEAN but I am finding Django difficult. I have been stuck with this authentication and authorisation stuff for 5 days now.


Aucun commentaire:

Enregistrer un commentaire