【发布时间】:2020-06-15 08:04:48
【问题描述】:
我正在尝试将抽象模型传递给包含标记,例如通过 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'
【问题讨论】:
-
你到底给 kwargs['model'] 分配了什么?
标签: python django django-views django-templates