Dynamic Sidebar - How to add data from database to my sidebar automatically

This is my first project with Django. I am working on a scholarship system whereby the admin has the power to add new countries, which offer scholarships, to the system. Everything works well at the level of the database. I am able to add a new country and save it. However, it is automatically supposed to be added to the sidebar of the admin dashboard (templates). But this does not happen.

Here is my views.py code for adding and saving a new country

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 CODE


<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 %}

You're trying to access name attribute of each country using countrys.name instead of country.name. html file:

<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">{{ country.name }}</span></a
</li>

{% endfor %}

Also, in your CountryListView, change the models = Country to model = Country

Back to Top