bootstrapman
bootstrapman

Reputation: 109

Error invalid literal for int() with base 10: 'a' in Django admin?

I am having this Error invalid literal for int() with base 10: 'a' in Django admin? The code causing it is below. Does anybody know what is the issue?

def formfield_for_manytomany(self, db_field, request, **kwargs):
    if db_field.name == "filenames":
        kwargs["queryset"] = MyFile.objects.filter(file='a')
    return super().formfield_for_manytomany(db_field, request, **kwargs)

Upvotes: 0

Views: 831

Answers (2)

Cory Madden
Cory Madden

Reputation: 5203

The error you're seeing normally arises when you try to query a primary key field with something that's not an integer. Django tries to cast it as an int and it fails and raises the same error that you would see when normally calling int('a').

In [1]: int('a')
---------------------------------------------------------------------------
ValueError                                Traceback (most recent call last)
<ipython-input-1-b3c3f4515dd4> in <module>()
----> 1 int('a')

ValueError: invalid literal for int() with base 10: 'a'

If file is actually a file field you should be able to query it by name. If it's another related object as it appears to be, you can perform a "nested query" by using double underscores to access fields on whatever file is. So if file has a name field you could do:

MyFile.objects.filter(file__name='a')

Upvotes: 0

csling
csling

Reputation: 328

The file field is not a text or char field, so you can't query it with text like you're doing. You need to filter based on the file name, and then your query filter will work.

Upvotes: 1

Related Questions