Ich kann einen Benutzer aus der Shell erstellen, indem ich das benutzerdefinierte Benutzermodell importiere, aber wenn ich dieselbe Methode nach dem Absenden des Formulars anwende, wird der Benutzer nicht erstellt. Unten sind die Codes meines benutzerdefinierten Benutzermodells UserCreationForm
und Ansicht.Warum kann ich in Django keinen benutzerdefinierten Benutzer mithilfe von UserCreationForm erstellen?
//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
Ich habe die AbstractBaseUser
erweitert, wie in dem Django docs vorgeschlagen, um ein benutzerdefiniertes Benutzermodell zu erstellen.
//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
Ich mache falsche Formularverarbeitung. Die form.save()
Methode hat für mich nicht geklappt. Auch die Dokumentation diskutiert die Benutzerregistrierung nicht gründlich. Ich weiß nicht warum.
//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})
Ich bin neu in Django, aber nicht besonders auf Web-Entwicklung. Ich habe etwas mit MEAN zu tun, aber ich finde Django schwierig. Ich bin jetzt seit 5 Tagen mit diesem Authentifizierungs- und Autorisierungskram festgefahren.
Versuch 'form.save()' statt 'my_user.save()' – ravigadila
@RaviKumar Wie ich in der Beschreibung gesagt, ich habe bereits versucht, dass . Das Ergebnis ist das gleiche. – nktsg