'我开始使用基于类的视图,但是当我使用基于类的视图时,我最初编写的代码不能在模板中呈现。main_c.main_categories.url,main_c.name中的数据,(参见模板)在我使用基于类的视图时根本不会显示。当我改回基于函数的视图并刷新页面时,模板中的HTML代码显示没有任何问题。有人能解释一下是什么原因导致这个错误吗?我读过一些关于模板找不到上下文的文章,但我真的不明白这意味着什么,以及上下文如何解决这个问题。
先谢谢你!
views.py
class MainCategoryDeleteView(DeleteView):
model = MainCategory
success_url = reverse_lazy("main_category")
template_name = 'admin_dashboard/categories/maincategory_confirm_delete.html'
class MainCategoryUpdateView(UpdateView):
model = MainCategory
fields = '__all__'
success_url = reverse_lazy("main_category")
template_name = 'admin_dashboard/categories/main_category_edit.html'
class MainCategoryCreateView(CreateView):
model = MainCategory
fields = '__all__'
success_url = reverse_lazy("main_category")
template_name = 'admin_dashboard/categories/main_category.html'
def get_context_data(self, **kwargs):
context = super(MainCategoryCreateView, self).get_context_data(**kwargs)
context['main_categories'] = MainCategory.objects.all()
print(MainCategory.objects.all())
return context
urls.py
path('BaitSouq/MainCategory/', views.MainCategoryCreateView.as_view(), name="main_category"),
path('BaitSouq/MainCategory/<int:pk>/Delete/', views.MainCategoryDeleteView.as_view(), name="main_category_delete"),
path('BaitSouq/MainCategory/<int:pk>/Change/', views.MainCategoryUpdateView.as_view(), name="main_category_update"),
模板
<div class="col-lg-2 d-none d-lg-flex">
<div class="categories-dropdown-wrap style-2 mt-30">
<div class="d-flex categori-dropdown-inner" style="font-size: x-small">
<ul>
{% for main_c in main_categories %}
<li>
<a href="#"> <img
src="{{ main_c.main_categories.url }}"
alt=""/>{{ main_c.name }}</a>
</li>
{% endfor %}
</ul>
</div>
</div>
</div>
1条答案
按热度按时间dwbf0jvd1#
在您的模板中,您有:
既然你还没有给出那个模型,我想它应该更短一些:
{{ main_c.url }}
.