AttributeError: module 'student.models' has no attribute 'ManyToManyField'

Viewed 97

I'm using the below models:

models.py

class Student(models.Model):
    name    =   models.CharField(max_length = 200)
    country =   models.ManyToManyField(Country, null = True,blank=True)

class Country(models.Model):
    title   =   models.CharField(max_length = 100, null = True)
    
    def __str__(self):
        return self.title

admin.py

@admin.register(models.Student)
class StudentAdmin(admin.ModelAdmin):
    formfield_overrides = {
        models.ManyToManyField: {'widget': CheckboxSelectMultiple},
    } 

I get this error:

AttributeError: module 'student.models' has no attribute 'ManyToManyField'
2 Answers

It looks like you are trying to use models.ManyToManyField from student.models, when it should be using django.db.models.

Try adding this import to the top of your file:

from django.db import models

And if the name is conflicting with your student.models, you can rename it to something like this:

from django.db import models as django_models

# then to use you would need to change your code to this:
django_models.ManyToManyField()

You imported the wrong models module, instead of the from student import models, you should import from django.db import models.

Another problem is that you refer to a Country before it is defined. You should thus use a string literal to refer to a model that is later defined:

# no student.models
from django.db import models

class Student(models.Model):
    name = models.CharField(max_length=200)
    #               use a string literal ↓
    country = models.ManyToManyField('Country', null=True, blank=True)

class Country(models.Model):
    title = models.CharField(max_length=100, null=True)
    
    def __str__(self):
        return self.title
Related