为什么在Django中做这么简单的事情看起来如此复杂?它首先设置了一个用户模型,其中使用电子邮件登录,痛苦......现在我尝试将用户保存为user.is_active = False
,但它保存为活动状态。任何提示非常受欢迎或任何其他指导,因为与Flask相比,Django迄今为止经历了相当痛苦的经历。
注意,我在下面尝试了@receiver(pre_save, sender=get_user_model())
。
views.py
...
from .models import Story, MyUser
from .forms import SignupForm, LoginForm
from django.dispatch import receiver
from django.db.models.signals import pre_save
@receiver(pre_save, sender=MyUser)
def set_new_user_inactive(sender, instance, **kwargs):
if instance._state.adding is True:
print("Creating Inactive User")
instance.is_active = False
else:
print("Updating User Record")
...
def signup(request):
if request.method == 'POST':
form = SignupForm(request.POST)
if form.is_valid():
user = get_user_model()
user.objects.create_user(
form.cleaned_data['username'],
form.cleaned_data['email'],
form.cleaned_data['password'],
)
return HttpResponseRedirect(reverse('index'))
else:
form = SignupForm()
return render(request, 'drillapp/signup.html', {'form': form})
...
models.py
from django.db import models
from django.contrib.auth.models import AbstractBaseUser, BaseUserManager
...
class MyUserManager(BaseUserManager):
def create_user(self, username, email, password=None):
if not email:
raise ValueError('Users must have an email address')
user = self.model(
email=self.normalize_email(email),
)
self.username = username
user.set_password(password)
user.save(using=self._db)
return user
def create_superuser(self, email, date_of_birth, password):
user = self.create_user(
email,
password=password,
)
user.is_admin = True
user.save(using=self._db)
return user
class MyUser(AbstractBaseUser):
email = models.EmailField(
verbose_name='email address',
max_length=255,
unique=True,
)
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
答案 0 :(得分:1)
你为什么不这样做:
class MyUser(AbstractBaseUser):
email = models.EmailField(
verbose_name='email address',
max_length=255,
unique=True,
)
is_active = models.BooleanField(
default=False
)