动态侧边栏问题:如何实现数据库数据自动同步至Django后台侧边栏
问题描述
这是我的第一个Django项目,正在开发一款奖学金系统,管理员可向系统添加提供奖学金的国家。数据库操作正常,能成功添加并保存新国家,但新国家不会自动显示在后台仪表盘的侧边栏模板中。
views.py 代码
def add_country(request): user = request.user if request.method == 'POST': form = CountryForm(request.POST) if form.is_valid(): form.save() print(form.cleaned_data) return redirect('dashboard.html') #redirect to be changed else: form = CountryForm() return render(request, 'add-country.html', { "form":form })
class CountryListView(ListView): template_name = "base.html" models = Country context_object_name = "countrys"
HTML 侧边栏代码
<li><a href="#" class="ttr-material-button"> <span class="ttr-icon"><i class="ti-email"></i></span> <span class="ttr-label">Countries</span> <span class="ttr-arrow-icon"><i class="fa fa-angle-down"></i></span> </a> <ul> {% for country in countrys %} <li><a href="#" class="ttr-material-button"><span class="ttr-label">{{ countrys.name }}</span></a </li> {% endfor %}
修复方案
- 修正ListView属性错误
Django ListView要求使用单数model属性,而非models,修改后的代码:
class CountryListView(ListView): template_name = "base.html" model = Country # 改为单数model context_object_name = "countrys"
- 修复模板变量引用错误
循环中单个国家对象是country,不是列表countrys,同时补全未闭合的<a>标签:
{% for country in countrys %} <li><a href="#" class="ttr-material-button"><span class="ttr-label">{{ country.name }}</span></a></li> {% endfor %}
- 修正重定向目标
redirect()需要传入URL配置的name值,而非模板文件名。假设仪表盘的URL配置为:
path('dashboard/', DashboardView.as_view(), name='dashboard')
则修改add_country视图的重定向代码:
return redirect('dashboard')
- 确保仪表盘视图传递国家列表上下文
如果侧边栏在base.html中,需保证仪表盘视图能传递countrys数据:
- 自定义仪表盘视图时手动查询:
def dashboard(request): countrys = Country.objects.all() return render(request, 'dashboard.html', {'countrys': countrys})
- 或使用Django上下文处理器,将国家列表全局注入所有模板,无需每个视图单独传递。
内容的提问来源于stack exchange,提问作者daniel litumbe
相关产品推荐
相关产品推荐

