django “str”对象没有属性“get”

rvpgvaaj  于 2022-12-30  发布在  Go
关注(0)|答案(1)|浏览(146)

大家好,当我创建一个带有信号的用户配置文件时,我们遇到了一个问题,当我进入寄存器部分时,'str'对象没有属性'get',如果你能帮忙,我会很高兴的
我的观点:

from django.shortcuts import render,redirect
from .forms import LoginForm,RegisterForm
from django.contrib.auth import authenticate,login,logout
from django .contrib.auth.models import User

# Create your views here.

def Login_view(request):
    form=LoginForm(request.POST or None)
    if form.is_valid():
        username=form.cleaned_data.get('username')
        password=form.cleaned_data.get('password')
        user=authenticate(username=username,password=password)
        login(request,user)
        return redirect('index')
    return render(request,'accounts/login.html',{'form':form})

def Register_view(request):
    form=RegisterForm(request.POST or None)
    if form.is_valid():
        user=form.save(commit=False)
        password=form.cleaned_data.get('password1')
        user.set_password(password)
        user.save()
        new_user=authenticate(username=user.username,password=password)
        login(request,new_user)
        return redirect('index')
    return render(request,'accounts/register.html',{'form':form})

def logout_view(request):
    logout(request)
    return redirect('index')

我的信号

from django.db.models.signals import post_save
from django.contrib.auth.models import User
from django.dispatch import receiver 
from .models import UserProfile

@receiver(post_save,sender=User)
def create_profile(sender,instance,created,**kwargs):
    if created:
        UserProfile.objects.create(user=instance)

@receiver(post_save,sender=User)
def save_profile(sender,instance,**kwargs):
    instance.profile.save()

我的模型:

class UserProfile(models.Model):
    user=models.OneToOneField(User, on_delete=models.CASCADE)
    username=models.CharField(verbose_name='Kullanıcı Adı',max_length=40)
    name=models.CharField(verbose_name='ad',max_length=40)
    surname=models.CharField(verbose_name='Soyad',max_length=40)
    bio=models.TextField()
    avatar=models.ImageField(null=True,blank=True)

登录表单:

class LoginForm(forms.Form):
    username=forms.CharField(max_length=50,label='Kullanıcı Adı')
    
 
 password=forms.CharField(max_length=50,label='Parola',widget=forms.PasswordInput)

    def clean(self):
        username=self.cleaned_data.get('username')
        password=self.cleaned_data.get('password')
        if username and password:
            user=authenticate(username=username,password=password)
            if not user:
                raise forms.ValidationError('Kullanıcı adı veya parola yanlış!')
        return super(LoginForm,self).clean()

登记表:

class RegisterForm(forms.ModelForm):
    username=forms.CharField(max_length=100,label='Kullanıcı Adı')
    password1=forms.CharField(max_length=100,label='Parola',widget=forms.PasswordInput)
    password2=forms.CharField(max_length=100,label='Parola Doğrulama',widget=forms.PasswordInput)

    class Meta:
        model=User
        fields=['username','password1','password2',]

    def clean(self):
        password1=self.cleaned_data.get('password1')
        password2=self.cleaned_data.get('password2')
        if password1 and password2 and password1!=password2:
            raise forms.ValidationError('Parolalar eşleşmiyor!')
        return password2

错误
申请方法:POST请求URL:http://127.0.0.1:8000/accounts/register

Django Version: 4.1.3
Python Version: 3.11.0
Installed Applications:
['django.contrib.admin',
 'django.contrib.auth',
 'django.contrib.contenttypes',
 'django.contrib.sessions',
 'django.contrib.messages',
 'django.contrib.staticfiles',
 'myapp',
 'crispy_forms',
 'accounts']
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 "C:\Users\tr\AppData\Local\Programs\Python\Python311\Lib\site-packages\django\core\handlers\exception.py", line 55, in inner
    response = get_response(request)
  File "C:\Users\tr\AppData\Local\Programs\Python\Python311\Lib\site-packages\django\core\handlers\base.py", line 197, in _get_response
    response = wrapped_callback(request, *callback_args, **callback_kwargs)
  File "C:\Users\tr\Documents\django-project\yeter\accounts\views.py", line 19, in Register_view
    if form.is_valid():
  File "C:\Users\tr\AppData\Local\Programs\Python\Python311\Lib\site-packages\django\forms\forms.py", line 205, in is_valid
    return self.is_bound and not self.errors
  File "C:\Users\tr\AppData\Local\Programs\Python\Python311\Lib\site-packages\django\forms\forms.py", line 200, in errors
    self.full_clean()
  File "C:\Users\tr\AppData\Local\Programs\Python\Python311\Lib\site-packages\django\forms\forms.py", line 439, in full_clean
    self._post_clean()
  File "C:\Users\tr\AppData\Local\Programs\Python\Python311\Lib\site-packages\django\forms\models.py", line 471, in _post_clean
    exclude = self._get_validation_exclusions()
  File "C:\Users\tr\AppData\Local\Programs\Python\Python311\Lib\site-packages\django\forms\models.py", line 422, in _get_validation_exclusions
    field_value = self.cleaned_data.get(field)

Exception Type: AttributeError at /accounts/register
Exception Value: 'str' object has no attribute 'get'
db2dz4w8

db2dz4w81#

RegisterForm不应返回str示例,而应返回super().clean()

class RegisterForm(forms.ModelForm):
    username=forms.CharField(max_length=100,label='Kullanıcı Adı')
    password1=forms.CharField(max_length=100,label='Parola',widget=forms.PasswordInput)
    password2=forms.CharField(max_length=100,label='Parola Doğrulama',widget=forms.PasswordInput)

    class Meta:
        model=User
        fields=['username','password1','password2',]

    def clean(self):
        password1=self.cleaned_data.get('password1')
        password2=self.cleaned_data.get('password2')
        if password1 and password2 and password1!=password2:
            raise forms.ValidationError('Parolalar eşleşmiyor!')
        return super().clean()

相关问题