【问题标题】:'NoneType' object has no attribute 'username'“NoneType”对象没有属性“用户名”
【发布时间】:2020-02-28 21:46:54
【问题描述】:

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

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

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

models.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

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

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)

【问题讨论】:

  • 用于获取 .username 的变量为 None。调试问题并修复它。打印变量进行调试。
  • 如果request.method 不是'POST',你确定要form = PIIForm(request.POST)

标签: python django django-models django-admin


【解决方案1】:

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

  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}'

【讨论】:

    猜你喜欢
    • 2021-03-30
    • 2013-05-13
    • 1970-01-01
    • 2015-02-01
    • 1970-01-01
    • 1970-01-01
    • 2021-11-02
    • 2014-07-05
    相关资源
    最近更新 更多