AttributeError: module 'student.models' has no attribute 'ManyToManyField'
AttributeError: module 'student.models' has no attribute 'ManyToManyField'
我正在使用以下型号:
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},
}
我收到这个错误:
AttributeError: module 'student.models' has no attribute 'ManyToManyField'
您似乎在尝试使用 student.models
中的 models.ManyToManyField
,而本应使用 django.db.models
。
尝试将此导入添加到文件顶部:
from django.db import models
如果名称与您的 student.models
冲突,您可以将其重命名为:
from django.db import models as django_models
# then to use you would need to change your code to this:
django_models.ManyToManyField()
您导入了错误的 models
模块,而不是 from student import models
,您应该导入 from django.db import models
.
另一个问题是你在定义Country
之前引用了一个。因此,您应该使用字符串文字来引用稍后定义的模型:
# no student.models
from django.db import <strong>models</strong>
class Student(models.Model):
name = <strong>models</strong>.CharField(max_length=200)
# use a string literal ↓
country = <strong>models</strong>.ManyToManyField(<strong>'Country'</strong>, null=True, blank=True)
class Country(<strong>models</strong>.Model):
title = <strong>models</strong>.CharField(max_length=100, null=True)
def __str__(self):
return self.title
我正在使用以下型号:
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},
}
我收到这个错误:
AttributeError: module 'student.models' has no attribute 'ManyToManyField'
您似乎在尝试使用 student.models
中的 models.ManyToManyField
,而本应使用 django.db.models
。
尝试将此导入添加到文件顶部:
from django.db import models
如果名称与您的 student.models
冲突,您可以将其重命名为:
from django.db import models as django_models
# then to use you would need to change your code to this:
django_models.ManyToManyField()
您导入了错误的 models
模块,而不是 ,您应该导入 from student import models
from django.db import models
.
另一个问题是你在定义Country
之前引用了一个。因此,您应该使用字符串文字来引用稍后定义的模型:
# no student.models
from django.db import <strong>models</strong>
class Student(models.Model):
name = <strong>models</strong>.CharField(max_length=200)
# use a string literal ↓
country = <strong>models</strong>.ManyToManyField(<strong>'Country'</strong>, null=True, blank=True)
class Country(<strong>models</strong>.Model):
title = <strong>models</strong>.CharField(max_length=100, null=True)
def __str__(self):
return self.title