Django 3.0中自定义用户模型的身份验证

时间:2019-12-08 23:19:29

标签: python django model

我是Django的新手,正在尝试对自定义用户模型进行用户身份验证。我的模型已成功创建,并且'createsuperuser'命令在其中插入了新用户。然后,我可以使用这些帐户登录,一切正常。但我希望能够从“注册”表单中插入新用户。我遵循了Django文档中的步骤,但是,它不会插入新用户。它不会给我任何错误,因此,我将不胜感激。

settings.py

TEMPLATES = [
    {
        'BACKEND': 'django.template.backends.django.DjangoTemplates',
        'DIRS': [os.path.join(BASE_DIR, 'templates')],
}
]

forms.py

from django import forms
from django.contrib.auth.forms import UserCreationForm, UserChangeForm

from .models import User

class CustomUserCreationForm(UserCreationForm):
     class Meta(UserCreationForm.Meta):
        model = User
        fields = ('username', 'full_name', 'country', 'city', 'birthday', 'language', 'email')


class CustomUserChangeForm(UserChangeForm):
    class Meta:
        model = User
        fields = UserChangeForm.Meta.fields

views.py

from django.views.generic.edit import CreateView
from .forms import CustomUserCreationForm

    class Register(CreateView):
        form_class = CustomUserCreationForm
        success_url = reverse_lazy('login')
        template_name = 'movies_app/register.html'

movie_project / urls.py

from django.contrib import admin
from django.urls import path, include

urlpatterns = [
    path('admin/', admin.site.urls),
    path('movies_app/', include('django.contrib.auth.urls')),
    path('', include('movies_app.urls', namespace='movies_app')),
]

movies_app / urls.py

from django.urls import path
from . import views
from .views import Register

app_name = 'movies_app'

urlpatterns = [
    path('', views.index, name='index'),
    path('register/', Register.as_view(), name='Register')
]

1 个答案:

答案 0 :(得分:0)

收到任何发帖请求后,您都不会将用户保存在views.py中。

尝试以下代码:

def signup(request):
    if request.method == 'POST':
        form = UserCreationForm(request.POST)
        if form.is_valid():
            form.save()
            username = form.cleaned_data.get('username')
            raw_password = form.cleaned_data.get('password1')
            user = authenticate(username=username, password=raw_password)
            login(request, user)
            return redirect('home')
    else:
        form = UserCreationForm()
    return render(request, 'signup.html', {'form': form})

或者您也可以按照以下URL进行详细了解。

  

https://simpleisbetterthancomplex.com/tutorial/2017/02/18/how-to-create-user-sign-up-view.html