繁体   English   中英

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

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

我目前正在从事一个项目,该项目将接收用户信息并存储它。 据我所知,存储数据没有问题,但是当我尝试访问管理页面上的用户部分时,它给了我这个错误:

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

还有一些其他人发布了同样的错误,但我似乎无法理解他们的解决方案。 任何可以为我指明正确方向的帮助或建议将不胜感激!

模型.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)

视图.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})

表格.py

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

管理文件

from django.contrib import admin
from .models import Profile


admin.site.register(Profile)

由于您与用户模型的 oneToOne 关系可能为 null,您有时可能会收到此错误。 你有两个选择:

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

此外,您可能需要删除数据库,因为您将此字段设为不可为空,并且 db 中有一些行为空值。

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

暂无
暂无

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

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM