AbstractUser Django完整示例 [英] AbstractUser Django full example

查看:118
本文介绍了AbstractUser Django完整示例的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述



我想要存储额外的信息,如用户手机号码,银行名称,银行帐号。并且想要在用户注册时存储手机号码,并希望用户使用(手机号码和密码)或(电子邮件和密码)登录。



这是我的UserProfile模型从django.db导入模型

 $ code从django.contrib.auth.models导入
来自django的用户
.contrib.auth.models import AbstractUser
#在这里创建你的模型。

class UserProfile(AbstractUser):

user_mobile = models.IntegerField(max_length = 10,null = True)
user_bank_name = models.CharField(max_length = null = True)
user_bank_account_number = models.CharField(max_length = 50,null = True)
user_bank_ifsc_code = models.CharField(max_length = 30,null = True)
user_byt_balance = models.IntegerField max_length = 20,null = True)

这是我的forms.py

从$ d code从django导入表单
从django.contrib.auth.models导入用户#填写自定义用户信息,然后保存
从django.contrib.auth.forms导入UserCreationForm
从模型import UserProfile
from django.contrib.auth import get_user_model

class MyRegistrationForm(UserCreationForm):
email =表单.EmailField(required = True)
mobile = forms.IntegerField(required = True)



class Meta:
model = UserProfile
fields =('username','email','password1','password2','mobile')

def save(self,commit = False):
user = super(MyRegistrationForm,self).save(commit = False)
user.email = self.cleaned_data ['email']
user.user_mobile = self.cleaned_data ['mobile']
user.set_password(self.cleaned_data [password1])

user_default = User.objects.create_user(self.cleaned_data ['username'],
self.cleaned_data ['email' ],
self.cleaned_data ['password1'])
user_default.save()

如果提交:
user.save()

返回用户

在我的settings.py中,我已经包括

  AUTH_USER_MODEL =registration.UserProfile

管理。我的应用程序的py是

  from django.contrib import admin 
from django.contrib.auth.admin import UserAdmin
from django.contrib.auth.models import来自模型的用户
import UserProfile

class UserProfileInline(admin.StackedInline):
model = UserProfile
can_delete = False
verbose_name_plural ='userprofile'

class UserProfileAdmin(UserAdmin):
inlines =(UserProfileInline,)

admin.site.register(UserProfile, UserProfileAdmin)

从管理员添加用户我收到此错误

  / admin / registration / userprofile / 1 / 
< class'registration.models.UserProfile'>没有ForeignKey到< class'registration.models.UserProfile'>有人可以帮助我这个或指出全面的工作exapmle,我已经看到了Django的文档,但是,b
$ / code $没有找到任何运气。或者如果还有另一种办法。



提前感谢



编辑1:



从注册表单注册时,我也收到此错误

  DatabaseError at / register 
(1146,table'django_auth_db.auth_user'不存在)


解决方案

你有点困惑了。将AbstractUser子类化并将 AUTH_USER_MODEL 定义为子类的想法是,新模型完全替代auth.models.User。你不应该导入原来的用户,你一定应该调用 User.objects.create_user():你的新模型的经理现在有自己的create_user方法。



正因为如此,没有理由与内联管理员沟通。您的UserProfile应该使用现有的django.contrib.auth.admin.UserAdmin类在管理员中注册。


I am new to Django and I have been trying this for weeks, but could not find a way to solve this problem.

I want to store additional information like user mobile number, bank name, bank account. And want to store the mobile number while user registers and wants user to login with either (mobile number and password) or (email and password).

This is my UserProfile model

from django.db import models
from django.contrib.auth.models import User
from django.contrib.auth.models import AbstractUser
# Create your models here.

class UserProfile(AbstractUser):

     user_mobile = models.IntegerField(max_length=10, null=True)
     user_bank_name=models.CharField(max_length=100,null=True)
     user_bank_account_number=models.CharField(max_length=50, null=True)
     user_bank_ifsc_code = models.CharField(max_length=30,null=True)
     user_byt_balance = models.IntegerField(max_length=20, null=True)

And this is my forms.py

from django import forms            
from django.contrib.auth.models import User   # fill in custom user info then save it 
from django.contrib.auth.forms import UserCreationForm      
from models import UserProfile
from django.contrib.auth import get_user_model

class MyRegistrationForm(UserCreationForm):
    email = forms.EmailField(required = True)
    mobile = forms.IntegerField(required=True)



    class Meta:
        model = UserProfile
        fields = ('username', 'email', 'password1', 'password2','mobile' )        

    def save(self,commit = False):   
        user = super(MyRegistrationForm, self).save(commit = False)
        user.email = self.cleaned_data['email']
        user.user_mobile = self.cleaned_data['mobile']
        user.set_password(self.cleaned_data["password1"])

        user_default = User.objects.create_user(self.cleaned_data['username'],
                                                self.cleaned_data['email'],
                                                self.cleaned_data['password1'])
        user_default.save()

        if commit:
             user.save()

         return user

In my settings.py I have included

AUTH_USER_MODEL = "registration.UserProfile"

admin.py of my app is

from django.contrib import admin
from django.contrib.auth.admin import UserAdmin
from django.contrib.auth.models import User
from models import UserProfile

class UserProfileInline(admin.StackedInline):
    model = UserProfile
    can_delete = False
    verbose_name_plural = 'userprofile'

 class UserProfileAdmin(UserAdmin):
    inlines = (UserProfileInline, )

 admin.site.register(UserProfile, UserProfileAdmin)

While adding the user from admin I get this error

Exception at /admin/registration/userprofile/1/
<class 'registration.models.UserProfile'> has no ForeignKey to <class 'registration.models.UserProfile'>

Can someone help me with this or point out to the full working exapmle, I have seen Django documentation but didn't find any luck. Or if there is another way to do this.

Thanks in advance

Edit 1:

While registering from the registration form I'm also getting this error

DatabaseError at /register
(1146, "Table 'django_auth_db.auth_user' doesn't exist")

解决方案

You have confused yourself a bit here. The idea of subclassing AbstractUser - and defining AUTH_USER_MODEL as your subclass - is that the new model completely replaces auth.models.User. You shouldn't be importing the original User at all, and you certainly should be calling User.objects.create_user(): your new model's manager now has its own create_user method.

Because of this, there's no reason to muck about with inline admins. Your UserProfile should be registered in the admin using the existing django.contrib.auth.admin.UserAdmin class.

这篇关于AbstractUser Django完整示例的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆