模型无法在Django模板中呈现

时间:2020-03-03 01:20:00

标签: python django django-views django-templates

我正在尝试将抽象模型传递给包含标记,例如通过takes_context=True。抽象模型包含模型字段的选择。我想传递抽象模型,而不是硬编码模板中的选择以保持DRY。调试时,我意识到模板没有收到预期的模型。

# urls.py
...
urlpatterns = [
    path('', IndexView.as_view(), name='index'),
]
# views.py
...
class IndexView(TemplateView):
    """Home Page"""
    template_name = 'index.html'

    def get_context_data(self, **kwargs):
        kwargs['model'] = MyModel
        return super(IndexView, self).get_context_data(**kwargs)

...
# index.html
{{model}}

以上内容在浏览器中不显示任何内容。当我将变量更改为字符串时,上下文将按预期呈现。

# views.py
...
class IndexView(BaseSearchBarMixin, TemplateView):
    """Home Page"""
    template_name = 'index.html'

    def get_context_data(self, **kwargs):
        kwargs['model'] = 'testing 123'
        return super(IndexView, self).get_context_data(**kwargs)

...
# index.html
{{model}}  # fixed typo
# browser
testing 123

我感觉自己在做一些愚蠢的事情,但是不知道什么

编辑: 根据公认的答案,无法将类传递给模板。由于我要传递的类是抽象模型,因此在某些情况下MyModel.objects.first()可能会返回一个空的查询集。我最终制作了一个自定义ContextMixin,将选择添加到基于类的视图中。

# myapp.models.users.py

class MyModel(models.Model):
    """shared fields and functions for MyModel models"""
    class Meta:
        abstract = True

    DOWN_VOTE = 'DOWN'
    UP_VOTE = 'UP'
    VOTE_CHOICES = [
        (DOWN_VOTE, 'Down vote'),
        (UP_VOTE, 'Up vote'),
    ]
    user = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.CASCADE)
    vote = models.CharField(choices=VOTE_CHOICES, default=UP_VOTE, max_length=255)
# views.py
...
class MyModelChoicesContextMixin(ContextMixin):
    """add choices from abstract model to context"""
    def get_context_data(self, **kwargs):
        """add choices from abstract model to context"""
        context = super(MyModelChoicesContextMixin, self).get_context_data(**kwargs)
        context['user_DOWN_vote'] = MyModel.DOWN_VOTE
        context['user_UP_vote'] = MyModel.UP_VOTE
        return context


class IndexView(MyModelChoicesContextMixin, BaseSearchBarMixin, TemplateView):
    """Home Page"""
    template_name = 'index.html'

2 个答案:

答案 0 :(得分:1)

您要传递的是类,而不是类的实例或查询集,请尝试:

kwargs['model'] = MyModel.objects.first()

(例如-获得第一个)。

您不能在模板中使用该类。

答案 1 :(得分:0)

在kwargs中,您传递了关键字'model',但在模板中使用了'Mymodel'关键字,这就是为什么显示空模板的原因。

第二件事显示模型字段,例如model.field_name。