为什么我的Django模板将user设置为与object相同?

2024-10-02 20:37:20 发布

您现在位置:Python中文网/ 问答频道 /正文

我对django绝对是个新手,在设计我的应用程序时经常使用教程和堆栈溢出。你知道吗

我的应用程序跟踪用户的案例工作。我需要它能够做的一件事是作为一个用户登录,并查看另一个用户的案例量。你知道吗

当这个页面出现时,通常会说“Logout Joe Bloggs”,其中Joe Bloggs是登录的用户,会说“Logout Fitzwilliam Darcy”,其中Fitzwilliam Darcy是我应该查看案例的用户。你知道吗

我真的不想继续开发应用程序,直到我修复了它,以防这是一个潜在问题的症状,将导致更多的问题在未来。你知道吗

我会添加我认为所有相关的位在这里,但如果有任何其他需要,让我知道,我很乐意编辑。你知道吗

#urls.py

url(r'cases/(?P<slug>\w+)',views.UserCasesView.as_view(),name='cases'),

#views.py

@method_decorator(login_required,name='dispatch')
class UserCasesView(generic.DetailView):

    model = models.User
    template_name = 'caseworkclub/caseworker_detail.html'
    slug_field = 'username'

#models.py

class User(AbstractUser):                                           

    association = models.ForeignKey('Association',null=True)

    def full_name(self):
        return("{} {}".format(self.first_name,self.last_name)

    def open_cases(self):
        return(Case.objects.filter(closed__isnull=True,caseworker=self))

slug位是这样的:根据this answer to another question,用户名可以在URL中

如果models.py位没有给出它,那么可能还值得解释的是,我已经扩展了基本用户类,并且正在使用它,而不是用户配置文件技术。不过,问题似乎是在改变了上面的slug位之后出现的。你知道吗

任何帮助都非常感谢,正如我所说的-任何更多的信息,很高兴提供!你知道吗

詹姆斯


Tags: 用户namepyself应用程序modelsviews案例
1条回答
网友
1楼 · 发布于 2024-10-02 20:37:20

这是因为您没有用合理的默认值重写UserCasesView类的get_context_data()方法。它当前使用的模型名(恰好也是user)与django.contrib.auth.context_processors.auth上下文处理器设置的内置user变量冲突。你知道吗

the documentation

Context variables override values from template context processors

Any variables from get_context_data() take precedence over context variables from context processors. For example, if your view sets the model attribute to User, the default context object name of user would override the user variable from the django.contrib.auth.context_processors.auth() context processor. Use get_context_object_name() to avoid a clash.

尝试将对象名称从user更改为其他名称(例如case_user):

class UserCasesView(generic.DetailView):
    ...
    context_object_name = 'case_user'

相关问题 更多 >