2 回答
TA贡献1863条经验 获得超2个赞
扩展 django 用户模型:
from django.contrib.auth.models import AbstractUser
class User(AbstractUser):
university_name = models.ForeignKey(
University, on_delete=models.CASCADE, blank=True, null=True)
isPhysicalAccount = models.BooleanField(default=False)
class Meta:
db_table = 'auth_user'
ordering = ('id', 'username', 'first_name', 'last_name')
settings.py:
AUTH_USER_MODEL = 'appname.User'
要获取使用此模型的用户:
from django.contrib.auth import get_user_model
user_model = get_user_model()
user_model.objects.get(id=1)
使用您的逻辑注册视图:
from django.contrib.auth.forms import AuthenticationForm
def sign_up(request):
context = {}
form = AuthenticationForm(request.POST or None, request.FILES or None)
if form.is_valid():
form.save()
return redirect('/')
else:
form = AuthenticationForm(request.POST or None, request.FILES or None)
context['form'] = form
return render(request, "sign_up.html", context)
TA贡献1757条经验 获得超8个赞
举例说明如何进行自定义Account
from django.contrib.auth.base_user import AbstractBaseUser
from django.contrib.auth.models import ( PermissionsMixin,
_user_has_module_perms, _user_has_perm )
class Account(AbstractBaseUser, PermissionsMixin):
first_name = models.CharField(max_length=30)
last_name = models.CharField(max_length=30)
email = models.EmailField(max_length=60)
username = models.CharField(max_length=30)
password = models.CharField(max_length=60)
university_name = models.ForeignKey(
University, on_delete=models.CASCADE, blank=True, null=True)
isPhysicalAccount = models.BooleanField(default=False)
is_admin = models.BooleanField(default=False)
is_active = models.BooleanField(default=True)
is_staff = models.BooleanField(default=False)
def __str__(self):
return self.username
def has_perm(self, perm, obj=None):
if self.is_active and self.is_superuser:
return True
return _user_has_perm(self, perm, obj)
def has_perms(self, perm_list, obj=None):
return all(self.has_perm(perm, obj) for perm in perm_list)
def has_module_perms(self, app_label):
if self.is_active and self.is_superuser:
return True
return _user_has_module_perms(self, app_label)
USERNAME_FIELD = 'username'
REQUIRED_FIELDS = ['username']
settings.py
AUTH_USER_MODEL = 'yourapp.Account'
添加回答
举报