简体   繁体   English

'NoneType' 对象没有属性 'username'

[英]'NoneType' object has no attribute 'username'

I am currently working on a project that would take in a users information and store it.我目前正在从事一个项目,该项目将接收用户信息并存储它。 So far as I can tell there are no issues with storing the data, but when I try and access the user section on my admin page it gives me this error:据我所知,存储数据没有问题,但是当我尝试访问管理页面上的用户部分时,它给了我这个错误:

AttributeError at /admin/users/profile/
'NoneType' object has no attribute 'username'
Request Method: GET
Request URL:    http://127.0.0.1:8000/admin/users/profile/
Django Version: 2.2.10
Exception Type: AttributeError
Exception Value:    
'NoneType' object has no attribute 'username'
Exception Location: /Users/ethanjay/Django Projects/opinions_app/users/models.py in __str__, line 28
Python Executable:  /Users/ethanjay/Enviroments/py3/bin/python
Python Version: 3.7.4
Python Path:    
['/Users/ethanjay/Django Projects/opinions_app',
 '/Users/ethanjay/Enviroments/py3/lib/python37.zip',
 '/Users/ethanjay/Enviroments/py3/lib/python3.7',
 '/Users/ethanjay/Enviroments/py3/lib/python3.7/lib-dynload',
 '/Library/Frameworks/Python.framework/Versions/3.7/lib/python3.7',
 '/Users/ethanjay/Enviroments/py3/lib/python3.7/site-packages']
Server time:    Fri, 28 Feb 2020 21:25:57 +0000

There are a few other people with the same error posted, but I can't seem to make sense of their solutions.还有一些其他人发布了同样的错误,但我似乎无法理解他们的解决方案。 Any help or advice that would point me in the right direction would be greatly appreciated!任何可以为我指明正确方向的帮助或建议将不胜感激!

models.py模型.py

class Profile(models.Model):

    user = models.OneToOneField(User, on_delete=models.CASCADE, null=True, blank=True)
    image = models.ImageField(default='default.jpg', upload_to='profile_pics')
    gender = models.CharField(max_length = 1, choices = GENS, default = '')
    birthday = models.DateField(default = '1900-01-01')
    address = AddressField(on_delete=False, blank=True, null=True)
    race = models.CharField(max_length = 2, choices = RACES, default = 'x')
    ethnicity = models.CharField(max_length = 1, choices = ETHNICITIES, default = 'x')
    income = models.CharField(max_length = 1, choices = INCBRACKET, default = 'x')
    education = models.CharField(max_length = 2, choices = EDUCATION, default = 'x')
    employment = models.CharField(max_length = 1, choices = EMPLOYMENT, default = 'x')

    def __str__(self):
        return f'{self.user.username} Profile'
    def save(self, *args, **kawrgs):
        super().save(*args, **kawrgs)
        img = Image.open(self.image.path)
        if img.height > 300 or img.width > 300:
            output_size = (300, 300)
            img.thumbnail(output_size)
            img.save(self.image.path)

views.py视图.py

def PII(request):
    if request.method == 'POST':
        form = PIIForm(request.POST,)
        if form.is_valid():
            form.save()
            messages.success(request, f'Your account has been created! You are now able to log in')
            return redirect('finalpii')
    else:
        form = PIIForm(request.POST)
    return render(request, 'users/pii.html', {'form':form})

forms.py表格.py

class PIIForm(forms.ModelForm):
    birthday = forms.DateField()
    class Meta:
        model = Profile
        fields = [
        'gender',
        'birthday',
        'address',
        'race',
        'ethnicity'
        ]

admin.py管理文件

from django.contrib import admin
from .models import Profile


admin.site.register(Profile)

Since your oneToOne relation with user model can be null you may get this error sometimes.由于您与用户模型的 oneToOne 关系可能为 null,您有时可能会收到此错误。 You got two options for this:你有两个选择:

  1. Make user field null=False and use self.user使用户字段 null=False 并使用 self.user
user = models.OneToOneField(User, on_delete=models.CASCADE, null=True, blank=True)

Also you may need to drop database because you are making this field non nullable and there are some rows with null value in db.此外,您可能需要删除数据库,因为您将此字段设为不可为空,并且 db 中有一些行为空值。

  1. Before every user access check if user is not null.在每个用户访问之前检查用户是否为空。
if self.user:
    return f'{self.user.username}'

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 'NoneType'对象没有属性'username'? - 'NoneType' object has no attribute 'username'? AttributeError:'NoneType'对象没有属性'userName' - AttributeError: 'NoneType' object has no attribute 'userName' auth_user.username给出“ NoneType”对象没有属性“ username” - auth_user.username gives 'NoneType' object has no attribute 'username' Python:“ NoneType”对象没有属性“ get_username” - Python: 'NoneType' object has no attribute 'get_username' Heroku 内部服务器错误 500:“NoneType”对象没有“用户名”属性 - Heroku Internal Server Error 500: 'NoneType' object has no attribute 'username' NoneType 对象没有属性 - NoneType object has no attribute 'NoneType'对象在项目上没有属性'username',该项目已经运行了一段时间 - 'NoneType' object has no attribute 'username' on a project which has been working fine for some time 'NoneType'对象没有属性'adapter','NoneType'对象没有属性'text' - 'NoneType' object has no attribute 'adapter', 'NoneType' object has no attribute 'text' 'NoneType'对象没有属性'PrimarySmtpAddress' - 'NoneType' object has no attribute 'PrimarySmtpAddress' 'NoneType'对象没有属性'height' - 'NoneType' object has no attribute 'height'
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM