Ethan Jay
Ethan Jay

Reputation: 31

'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

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)

Upvotes: 0

Views: 2358

Answers (1)

Glyphack
Glyphack

Reputation: 886

Since your oneToOne relation with user model can be null you may get this error sometimes. You got two options for this:

  1. Make user field null=False and use 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.

  1. Before every user access check if user is not null.
if self.user:
    return f'{self.user.username}'

Upvotes: 1

Related Questions