首页 > 解决方案 > 如何修复“CustomUser”对象没有“get”属性

问题描述

我正在尝试从数据库中获取一些数据以显示在视图上,但我向我显示了一个错误,即我的代码甚至不存在。

我有模型CustomCliente:

class CustomCliente(AbstractUser):
        email     = models.EmailField(unique=True, null=False, blank=False)
        full_name = models.CharField(max_length=120, null=False, blank=False)
        password  = models.CharField(max_length=40, null=False, blank=False)
        username  = models.CharField(max_length=110, unique=True, null=False, blank=False)

我对以下方法有看法:

def mostrar_relatorio(request, id):
    aluguel = Aluguel.objects.get(cliente=CustomCliente.objects.get(id=id))
    if aluguel is not None :
        context = {'aluguel': aluguel}
        template_name = 'relatorio.html'
    else:
        raise Http404

    return render(request, template_name, context)

我的那个模型的网址模式是:

urlpatterns = [
    path('cliente/<int:id>', CustomCliente, name='relatorio'),
]

发生的情况是,当我尝试访问以下 url 127.0.0.1:8000/cliente/2 时,我收到错误:'CustomCliente' object has no attribute 'get. 即使我的代码中没有任何地方调用 CustomCliente.get。我已经尝试关闭服务器并再次尝试,重写代码,但它似乎不起作用。

标签: djangodjango-modelsdjango-viewsdjango-users

解决方案


您在 urls.py 中使用了您的模型,而不是您的视图。

它应该是:

path('cliente/<int:id>', mostrar_relatorio, name='relatorio'),

推荐阅读