为什么基于 class 的视图返回类型对象 'Profile' 没有属性 'model'?

why class-based view returned type object 'Profile' has no attribute 'model'?

我有一个使用 django 的网站。

这是项目 urls.py:

urlpatterns = [
url(r'^admin/', admin.site.urls),
url(r'^', include('accounts.urls')),
url(r'^login/$', LoginView.as_view(), name='login'),
url(r'^register/$', RegisterView.as_view(), name='register'),
url(r'^logout/$', logout_view, name="logout")
]

这是 accounts.urls:

from . import views
urlpatterns = [
url(r'(?P<username>[\w]+)/$', views.Profile.as_view(), name='profile_cbv'),
]

这是个人资料模型:

class Profile(models.Model):
    user = models.OneToOneField(settings.AUTH_USER_MODEL, related_name='profile', verbose_name='user', on_delete=models.CASCADE)
    name = models.CharField(max_length=30, verbose_name='name')
    family = models.CharField(max_length=50, verbose_name='family')

最后,这是基于配置文件 class 的视图:

class Profile(View):
def get(self, request, username=None):
    profile = get_object_or_404(Profile, user__username=username)

    print(profile)
    pass

例如,我转到下面url:

localhost:8000/ivan/

它引发以下错误:

AttributeError at /ivan/
type object 'Profile' has no attribute 'model'

如果我通过 url 传递正确或不正确的用户名来查看,它总是会引发该错误。

有什么问题?

在视图中看起来像是名称问题。您的视图 class 名称与模型 class 相同。导入模型 class 作为其他东西。例如:

from .models import Profile as ProfileModel

然后在视图中以这种方式调用模型。

当您调用 get_object_or_404(Profile, ...) 时,它 Profile 不是您的 模型 ,而是您的 视图 .这就是您收到该错误的原因。

尝试将 class Profile(View) 重命名为 class ProfileView(View):

from . import views
urlpatterns = [
    url(r'(?P<username>[\w]+)/$', views.ProfileView.as_view(), name='profile_cbv'),
]

在你的views.py中:

class ProfileView(View):
    def get(self, request, username=None):
        profile = get_object_or_404(Profile, user__username=username)

        print(profile)
        pass