1

Django 1.7 を使用しており、提供された Django 認証ユーザーの代わりにメールでユーザーを認証しようとしています。

これは私のmodels.py

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

class MyUserManager(BaseUserManager):
    def create_user(self, email, password=None):
        if not email:
            raise ValueError('Users must have an email address')

        user = self.model(
            email=MyUserManager.normalize_email(email),
        )

        user.set_password(password)
        user.save(using=self._db)
        return user

    def create_superuser(self, email, password):
        user = self.create_user(email,
            password=password,
        )
        user.is_admin = True
        user.save(using=self._db)
        return user


class MyUser(AbstractBaseUser):
    """
    Custom user class.
    """
    email = models.EmailField('email address', unique=True, db_index=True)
    joined = models.DateTimeField(auto_now_add=True)
    is_active = models.BooleanField(default=True)
    is_admin = models.BooleanField(default=False)

    USERNAME_FIELD = 'email'

    def __unicode__(self):
        return self.email

これは私のviews.py

def auth_view(request):
   username = request.POST.get('username', '')
   password = request.POST.get('password', '')
   user = auth.authenticate(username=username, password=password)

   if user is not None:
     auth.login(request, user)
     return HttpResponseRedirect('/')
   else:
     return HttpResponseRedirect('/invalid/')

def register_user(request):
   if request.method == 'POST':
      form = MyRegistrationForm(request.POST)
      if form.is_valid():
         print "Form is valid"
         form.save()
         return HttpResponseRedirect('/register_success/')
   args = {}
   args.update(csrf(request))
   args['form'] = MyRegistrationForm()
   return render_to_response('register.html', args, context_instance=RequestContext(request))

そして最後に、私のforms.py

from django import forms
from django.contrib.auth.models import User


class MyRegistrationForm(forms.ModelForm):
    """
    Form for registering a new account.
    """
    email = forms.EmailField(widget=forms.EmailInput,label="Email")
    password1 = forms.CharField(widget=forms.PasswordInput,
                                label="Password")
    password2 = forms.CharField(widget=forms.PasswordInput,
                                label="Password (again)")

    class Meta:
        model = User
        fields = ['email', 'password1', 'password2']

    def clean(self):
        """
        Verifies that the values entered into the password fields match

        NOTE: Errors here will appear in ``non_field_errors()`` because it applies to more than one field.
        """
        cleaned_data = super(MyRegistrationForm, self).clean()
        if 'password1' in self.cleaned_data and 'password2' in self.cleaned_data:
            if self.cleaned_data['password1'] != self.cleaned_data['password2']:
                raise forms.ValidationError("Passwords don't match. Please enter both fields again.")
        return self.cleaned_data

    def save(self, commit=True):
        user = super(MyRegistrationForm, self).save(commit=False)
        user.set_password(self.cleaned_data['password1'])
        if commit:
            user.save()
        return user

アカウントを登録しようとすると、user.save と form.save の呼び出しでエラー'NoneType' object has no attribute '_insert'が発生します。user.save の書き方はよくわかりませんが、両方のエラーが修正されると思います。forms.pyviews.py

誰でも私を助けることができますか?

4

1 に答える 1

2

forms.py輸入品を見て

from django.contrib.auth.models import User

その代わりに MyUser をインポートする必要があります

で同じ

class Meta:
    model = User
    fields = ['email', 'password1', 'password2']

MyUser クラスに追加します

objects = MyUserManage()

への変更

class Meta:
    model = MyUser
    fields = ['email', 'password1', 'password2']

以下をsettings.py設定する必要があります。

AUTH_USER_MODEL = '<apppath>.MyUser'
于 2015-01-21T16:52:20.817 に答える