Search code examples
pythondjangodjango-modelsdjango-admindjango-admin-actions

Error while adding data using Django Administration's panel


I'm currently experimenting with the Django framework and i've made an application that includes 2 models. The first one is the user model which contains the user and some basic information about them. The second model is the Image model which has an author(links the user model with a foreign key) and a filename.

App name: Sc

Models: User, Image

The code for my models:

from django.db import models

class User(models.Model):
    username = models.CharField(max_length=128, default='')
    password = models.CharField(max_length=512, default='')
    ip_address = models.CharField(max_length=32, default='')

    def __str__(self):
        return f"{self.id} - {self.username}"

class Image(models.Model):
    author = models.ForeignKey(User, on_delete=models.DO_NOTHING)
    filename = models.CharField(max_length=512)

    def __str__(self):
        return f"{User.objects.filter(id=self.author)} - {self.filename}"

I can add users using Django's administration panel(localhost/admin) however I can't add any images.

I select the user I want as the author of the image and I add a random file name but I get the following error when I try to add the new image:

TypeError at /adminsc/image/add/
int() argument must be a string, a bytes-like object or a number, not 'User'
Request Method: POST
Request URL: http://localhost/adminsc/image/add/
Django Version: 2.0.7
Exception Type: TypeError
Exception Value:
int() argument must be a string, a bytes-like object or a number, not 'User'
Exception Location: C:\Python37\lib\site-packages\django\db\models\fields__init__.py in get_prep_value, line 947
Python Executable: C:\Python37\python.exe
Python Version: 3.7.0
Python Path:
['G:\smiley\Websites\local',
'C:\Python37\python37.zip',
'C:\Python37\DLLs',
'C:\Python37\lib',
'C:\Python37',
'C:\Python37\lib\site-packages']
Server time: Tue, 21 Aug 2018 00:05:30 +0000

I already tried deleting the database including the migrations folder and restarting from scratch but I always get the same error. It seems it tries to pass the user object when it actually expects its primary key. Am I doing something wrong by using ForeignKey(User) as an attribute/column of Image?


Solution

  • The error message says it all:

    int() argument must be a string, a bytes-like object or a number, not 'User'
    

    You are passing a User object to be used as an id in the .filter() call, which is not valid.

    You have multiple issues here:

    1. You should have used {User.objects.filter(id=self.author.id)}.
    2. That will not return a User object (because of the filter() call) but a list of Users of size 1. You should probably change it to {User.objects.get(id=self.author.id)}
    3. The above will work, but won't make sense as it is an expensive way of getting {self.author}:

      return f"{self.author) - {self.filename}"