Bootstrap导航栏下拉列表填充了Django 2中的数据库条目 [英] Bootstrap navbar dropdown populated with database entries in Django 2

查看:71
本文介绍了Bootstrap导航栏下拉列表填充了Django 2中的数据库条目的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试使用从sqlite3 DB中的数据填充的单个下拉菜单项"填充导航栏下拉菜单".

I am trying to populate a navbar "dropdown-menu" with individual "dropdown-item"'s populated from data in the sqlite3 DB.

我在其他页面上也有类似的工作,但是我无法在导航栏中使用它.

I have something similar working on other pages but I cant get it to work in my navbar.

我正在创建一个唱片公司标签,并希望从数据库中的条目中填充艺术家列表.我已经找到了一个有关在php中执行类似操作的教程,但没有进行翻译,而且在youtube或此处似乎除了填充表单数据外没有任何其他内容.

I am creating a record label, and want the list of artists populated from entries in the DB. I have found one tutorial on doing something similar in php, but doesn't translate, and there doesn't seem to be anything either on youtube or here other than populating form data.

任何帮助都将不胜感激,因为我一直在努力使其工作大约一个星期.我知道这应该很简单,但是我错过了一些东西.

Any help is greatly appreciated, as I have been trying to get it working for about a week now. I know it should be simple, but im missing something.

该应用称为音乐"

models.py

models.py

class Artist(models.Model):
    artist_name = models.CharField(max_length=250, default='')
    artist_logo = models.FileField()
    artist_url = models.URLField(blank=True)

    def __str__(self):
        return self.artist_name

class Release(models.Model):
    artist = models.ForeignKey(Artist, on_delete=models.CASCADE)
    release_title = models.CharField(max_length=500)
    release_cover = models.FileField()
    release_duration = models.IntegerField()

    def __str__(self):
        return self.release_title

class Track(models.Model):
    release = models.ForeignKey(Release, default='', on_delete=models.CASCADE)
    artist = models.ForeignKey(Artist, default='', on_delete=models.CASCADE)
    track_title = models.CharField(max_length=200)
    track_version = models.CharField(max_length=200)
    track_genre = models.CharField(max_length=100)
    track_duration = models.IntegerField()
    track_number = models.SmallIntegerField()

    class Meta:
        ordering = ["track_number"]

    def __str__(self):
        return self.track_title

views.py

from django.contrib.auth import authenticate, login
from django.views import generic
from django.views.generic import ListView, View
from .models import Artist, Track, Release
from .forms import UserForm

# class IndexView(ListView):
#     template_name = 'music/index.html'

class ReleaseView(generic.ListView):
    template_name = 'music/releaselist.html'
    context_object_name = 'all_releases'

    def get_queryset(self):
        return Release.objects.all()

class ArtistView(generic.ListView):
    model = Artist
    template_name = 'music/artistlist.html'
    context_object_name = 'all_artists'

    def get_queryset(self):
        return Artist.objects.all()

class DetailView(generic.DetailView):
    model = Release
    template_name = 'music/detail.html'

urls.py(主要)

urls.py (Main)

from django.contrib import admin
from django.urls import path, include, re_path
from django.conf import settings
from django.conf.urls.static import static

urlpatterns = [
    path('admin/', admin.site.urls),
# include urls from the music app
    path('music/', include('music.urls'))

urls.py(音乐"又称应用网址)

urls.py ("music" aka the app urls)

from django.contrib import admin
from django.urls import path, include, re_path
from . import views

# defined the app name in case the same fields are used in other apps
app_name = 'music'

urlpatterns = [
    # no info past music return index EG /music/
    # path('', views.IndexView.as_view(), name='index'),
    # albums/releases
    re_path(r'^release/$', views.ReleaseView.as_view(), name='release'),
    # looking for music page with album id afterwards /music/1
    re_path(r'^(?P<pk>[0-9]+)/$', views.DetailView.as_view(), name="detail"),
    re_path(r'^(?P<pk>[0-9]+)/$', views.ArtistView.as_view(), name="artist"),

base.html

base.html

      <li class="nav-item dropdown">
        <a class="nav-link dropdown-toggle" href="#" id="navbarDropdownMenuLink" data-toggle="dropdown" aria-haspopup="true" aria-expanded="false">
          Artists
        </a>
        <div class="dropdown-menu" aria-labelledby="navbarDropdownMenuLink">
            {% for artist in all_artists %}
                <li><a class="dropdown-item" href="#">{{ artist.artist_id }}</a></li>
            {% endfor %}
        </div>

      </li>

更新: 这是我的releases.html,它使用类似的代码工作,并且在底部进行了一个测试,看起来好像for循环不正确

Update: Here is my releases.html which works using similar code, and at the bottom has a test which looks like the for loop is incorrect

{% extends 'music/base.html' %}
{% block title %}KOLD FUZEON: Releases{% endblock %}

{% block body %}

        {% if all_releases %}
            <ul>
                {% for release in all_releases %}
                    <div class="releaseitem">
                        <li><a href="{% url 'music:detail' release.id %}">{{ release.artist }} - {{ release.release_title }}</a></li>
                        <li><a href="{% url 'music:detail' release.id %}"</a><img src="{{ release.release_cover.url }}" style="width: 300px"></li>
                    </div>
                {% endfor %}
            </ul>
        {% else %}
            <h3>We currently dont have any releases yet.</h3>
        {% endif %}


{#basic test for the artist list to be printed to screen#}
            <ul>
                <li>test1</li>
                {% for artist in all_artists %}
                    <li>test2</li>
                {% endfor %}
            </ul>



{% endblock %}

推荐答案

在您的View.py中,您具有ArtistView,其中 template artistlist.html,上下文是all_artist&您可以从db获取所有对象.

In your View.py you have ArtistView where template is artistlist.html and your context is all_artist & you get all objects from db.

代码:

class ArtistView(generic.ListView):
model = Artist
template_name = 'music/artistlist.html'
context_object_name = 'all_artists'

def get_queryset(self):
    return Artist.objects.all()

现在,我相信您有一个名为artistlist.html的模板.如果未在templates中创建它,则将在其中使用 for循环 渲染艺术家列表,因此artistlist.html的代码应为以下代码:

Now i believe you have a template named artistlist.html. If not create it in templates in which you will use for Loop to render artist list so the code should be this for artistlist.html:

{% extends 'music/base.html' %}
{% block body %}

   <h1>Artists!</h1>

<ul>
{% for artist in all_artists %}
  <li class="artist">
     <h1>
         <a href='/music/{{ artist.id }}'>{{artist.artist_name }}</a>  
     </h1>
  </li>
{% endfor %}
</ul>

</div>

{% endblock %}

您可以在Base.html 中渲染艺术家列表. 使用: Context Processor

You can Render Artist list in Base.html. Using: Context Processor

首先在App中创建一个名为context_processors.py的文件,然后将此代码添加到该文件中.

First Create a file named context_processors.py in your App.Then add this code in that file.

from .models import Artist

def basetest(request):

    hello = Artist.objects.values_list("artist_name", flat=True)
    return {
        'testname': hello
    }

然后,打开Settings.py并找到 context_processors 并添加以下设置'yourapp.context_processors.add_variable_to_context'.

Settings.py

TEMPLATES = [
{
    'BACKEND': 'django.template.backends.django.DjangoTemplates',
    'DIRS': [],
    'APP_DIRS': True,
    'OPTIONS': {
        'context_processors': [
            'django.template.context_processors.debug',
            'django.template.context_processors.request',
            'django.contrib.auth.context_processors.auth',

            #This one is from my code so set it according to you
            #appname.context_processors.function_name_context_processor.py',

            'blog.context_processors.basetest',

        ],
    },
},
]

此后,根据需要将 {{ testname }} 放入您的base.html中.它会工作.无需循环,仅插值即可显示列表.遵循此 doc a>

After this just place {{ testname }} in your base.html according to your need. it will work. No need for looping just the interpolation will render you a list. Format it according to your need by following this doc

这篇关于Bootstrap导航栏下拉列表填充了Django 2中的数据库条目的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆