У меня возникает следующая ошибка при попытке зарегистрироваться в моем приложении:
AttributeError at /signup/: 'str' object has no attribute 'META'
Полная трассировка:
Environment:
Request Method: POST
Request URL: http://127.0.0.1:8000/signup/
Django Version: 3.0.5
Python Version: 3.8.2
Installed Applications:
['django.contrib.admin',
'django.contrib.auth',
'django.contrib.contenttypes',
'django.contrib.sessions',
'django.contrib.messages',
'django.contrib.staticfiles',
'accounts.apps.AccountsConfig',
'widget_tweaks']
Installed Middleware:
['django.middleware.security.SecurityMiddleware',
'django.contrib.sessions.middleware.SessionMiddleware',
'django.middleware.common.CommonMiddleware',
'django.middleware.csrf.CsrfViewMiddleware',
'django.contrib.auth.middleware.AuthenticationMiddleware',
'django.contrib.messages.middleware.MessageMiddleware',
'django.middleware.clickjacking.XFrameOptionsMiddleware']
Traceback (most recent call last):
File "/Users/atakancavuslu/Documents/DjangoProject/projectx/venv/lib/python3.8/site-packages/django/core/handlers/exception.py", line 34, in inner
response = get_response(request)
File "/Users/atakancavuslu/Documents/DjangoProject/projectx/venv/lib/python3.8/site-packages/django/core/handlers/base.py", line 115, in _get_response
response = self.process_exception_by_middleware(e, request)
File "/Users/atakancavuslu/Documents/DjangoProject/projectx/venv/lib/python3.8/site-packages/django/core/handlers/base.py", line 113, in _get_response
response = wrapped_callback(request, *callback_args, **callback_kwargs)
File "/Users/atakancavuslu/Documents/DjangoProject/projectx/projectx/accounts/views.py", line 15, in signup
return redirect('accounts:redirect')
File "/Users/atakancavuslu/Documents/DjangoProject/projectx/projectx/accounts/views.py", line 7, in redirect
return render(request, 'accounts/redirect.html')
File "/Users/atakancavuslu/Documents/DjangoProject/projectx/venv/lib/python3.8/site-packages/django/shortcuts.py", line 19, in render
content = loader.render_to_string(template_name, context, request, using=using)
File "/Users/atakancavuslu/Documents/DjangoProject/projectx/venv/lib/python3.8/site-packages/django/template/loader.py", line 62, in render_to_string
return template.render(context, request)
File "/Users/atakancavuslu/Documents/DjangoProject/projectx/venv/lib/python3.8/site-packages/django/template/backends/django.py", line 61, in render
return self.template.render(context)
File "/Users/atakancavuslu/Documents/DjangoProject/projectx/venv/lib/python3.8/site-packages/django/template/base.py", line 169, in render
with context.bind_template(self):
File "/Users/atakancavuslu/.pyenv/versions/3.8.2/lib/python3.8/contextlib.py", line 113, in __enter__
return next(self.gen)
File "/Users/atakancavuslu/Documents/DjangoProject/projectx/venv/lib/python3.8/site-packages/django/template/context.py", line 246, in bind_template
updates.update(processor(self.request))
File "/Users/atakancavuslu/Documents/DjangoProject/projectx/venv/lib/python3.8/site-packages/django/template/context_processors.py", line 40, in debug
if settings.DEBUG and request.META.get('REMOTE_ADDR') in settings.INTERNAL_IPS:
Exception Type: AttributeError at /signup/
Exception Value: 'str' object has no attribute 'META'
Что бы я ни делал, я не мог не удается устранить ошибку.
Это представление SignUp (после успешной регистрации я перенаправляю в представление «redirect», это только для того, чтобы быть заполнителем, печатая электронную почту зарегистрированных пользователей в шаблоне)
views.py
def redirect(request):
return render(request, 'accounts/redirect.html')
def signup(request):
if request.method == 'POST':
form = SignUpForm(data=request.POST)
if form.is_valid():
user = form.save()
login(request, user)
return redirect('accounts:redirect')
else:
form = SignUpForm()
return render(request, 'accounts/signup.html', {'form': form})
У меня есть объект CustomUser в качестве модели пользователя для аутентификации в моем приложении Django. Я использую CustomUserCreationForm и SignUpForm, которые наследуют эту форму CustomUserCreation (вы можете увидеть ниже модель CustomUser, CustomManager, а также CustomForms.)
models.py
class CustomUser(AbstractBaseUser, PermissionsMixin):
email = models.EmailField('email adress', unique=True)
is_staff = models.BooleanField(default=False)
is_active = models.BooleanField(default=True)
is_exhibitor = models.BooleanField(default=False)
date_joined = models.DateTimeField(auto_now_add=True)
USERNAME_FIELD = 'email'
REQUIRED_FIELDS = []
objects = CustomUserManager()
def __str__(self):
return self.email
class Meta:
verbose_name = 'user'
Manager.py
class CustomUserManager(BaseUserManager):
"""
Custom user model manager where email is the unique identifiers for authentication instead of usernames.
"""
def create_user(self, email, password, **extra_fields):
"""
Create and save a User with the given email and password.
"""
if not email:
raise ValueError('The email must be set')
email = self.normalize_email(email)
user = self.model(email=email, **extra_fields)
user.set_password(password)
user.save()
return user
def create_superuser(self, email, password, **extra_fields):
"""
Create and save a SuperUser with the given email and password.
"""
extra_fields.setdefault('is_staff', True)
extra_fields.setdefault('is_superuser', True)
extra_fields.setdefault('is_active', True)
if extra_fields.get('is_staff') is not True:
raise ValueError('Superuser must have is_staff=True.')
if extra_fields.get('is_superuser') is not True:
raise ValueError('Superuser must have is_superuser=True.')
return self.create_user(email, password, **extra_fields)
forms.py
class CustomUserCreationForm(UserCreationForm):
class Meta:
model = CustomUser
fields = ('email',)
class CustomUserChangeForm(UserChangeForm):
class Meta:
model = CustomUser
fields = ('email',)
class SignUpForm(CustomUserCreationForm):
class Meta:
model = CustomUser
fields = ('email', 'password1', 'password2')