error in django KeyError at /accounts/register/

  Kiến thức lập trình

I have a problem. When clicking on the link http://127.0.0.1:8000/accounts/register / returns the KeyError error at /accounts/register/
’email’. I program in django in pycharm

this is code:

registration/urls.py:

from django.contrib.auth import views as auth_views
from django.urls import path
from . import views

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

registration/views.py:

from django.shortcuts import render
from django.contrib.auth import login, authenticate
from django.shortcuts import render, redirect
from .forms import RegistrationForm
from django.shortcuts import render, redirect


def sign_up(request):
    if request.method == 'POST':
        form = RegistrationForm(request.POST)
        if form.is_valid():
            user = form.save()
            login(request, user)
            return redirect('home')
        else:
            form = RegistrationForm()
            return render(request, 'registration/register.html', {'form': form})


def register():
    print("hello!")

urls.py(In the project itself):

from django.contrib import admin
from django.urls import path, include
from django.conf import settings
from django.conf.urls.static import static
from django.contrib.auth import views as auth_views
from django.urls import path

urlpatterns = [
    path('admin/', admin.site.urls),
    path('', include('main.urls')),
    path('news/', include('news.urls')),
    path('accounts/', include('django.contrib.auth.urls')),
]

urlpatterns += static(settings.STATIC_URL, document_root=settings.STATIC_ROOT)

register.html:

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Регистрация</title>
</head>
<body>
    <h1>Регистрация</h1>
    <form method="post" action="{% url 'register' %}">
        {% csrf_token %}
        {{ form.email }}
        {{ form.password1 }}
        {{ form.password2 }}
        <button type="submit">Зарегистрироваться</button>
    </form>
</body>
</html>

forms.py:

from django import forms
from django.contrib.auth.models import User
from django.contrib.auth.forms import UserCreationForm


class RegistrationForm(UserCreationForm):
    def __init__(self, *args, **kwargs):
        super().__init__(*args, **kwargs)
        self.fields['email'].label = 'Email address'
        self.fields['password1'].label = 'Password'
        self.fields['password2'].label = 'Confirm Password'


class Meta:
    model = User
    fields = ('email', 'password1', 'password2')

I’ve tried a lot of YouTube videos and documentation, but still

New contributor

user24993423 is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
Check out our Code of Conduct.

LEAVE A COMMENT