2016-06-18 7 views
0

カスタムユーザーモデルをインポートしてシェルからユーザーを作成できますが、フォームの送信後に同じ方法を適用するとユーザーは作成されません。 私のカスタムユーザーモデルのコードはUserCreationFormです。UserCreationFormを使用してDjangoでカスタムユーザを作成できないのはなぜですか?

//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 

示唆したように私は、カスタム・ユーザー・モデルを作成するために、DjangoのドキュメントにAbstractBaseUserを高めています。

//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 

不適切なフォーム処理を行っていますか? form.save()メソッドは私にとってはうまくいかなかった。また、ドキュメントはユーザー登録について完全に議論していません。どうしてか分かりません。

//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}) 

私はDjangoの新機能ですが、特にWeb開発には興味がありません。私はMEANにいくつかの露出を持っていますが、私はDjangoを見つけるのが難しいです。私はこの認証と認可のものに5日間拘束されています。

+1

試し 'form.save()'の代わりに 'my_user.save()' – ravigadila

+0

@RaviKumarを。結果は同じです。 – nktsg

答えて

0
def register(request): 
    # this is the logged-in user 
    user = request.user  

    if request.method == 'POST': 
     # this is the form with the submitted data 
     form = UserCreationForm(data=request.POST) 

     if form.is_valid(): 
      # the submitted data is correct 
      my_user = MyUser(user.email, user.password)  

      # this is a new user with the same email and password 
      # than the currently logged-in user. It's not what you want 
      # and it won't work if you're not logged-in 
      my_user.save() 

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

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

代わりに、あなたはおそらく、この欲しい:私が説明で述べたように、私はすでにことを試してみました

if request.method == 'POST': 
    form = UserCreationForm(data=request.POST) 
    if form.is_valid(): 
     user = form.save(commit=False) 
     user.is_active = True # if you want to skip email validation 
     user.email = User.objects.normalize_email(user.email) 
     user.save() 
+0

まだ動作していません。 UserCreationFormのsave()メソッドが正しいかどうかコードの6行目のUserオブジェクトはどうでしょうか?それはMyUserオブジェクトではありませんか? – nktsg

+0

私には正しいと思われる。 "うまくいかない"あなたはどんなエラーを受けますか?フォームが検証されていない可能性があります。 'form.is_valid()'の下にprintステートメントを追加します。テンプレートにエラーを正しく表示していますか? CSRFトークンを忘れましたか? –

関連する問題