【问题标题】:My bootstrap drop-down items are not clickable (showing)我的引导下拉项目不可点击(显示)
【发布时间】:2020-05-18 19:02:52
【问题描述】:

只要我在我的 Django 项目中包含一个指向本地的 bootstrap.min.css 的链接,我的下拉菜单就会变得不可点击。我是一个学习 Django,对引导程序知之甚少。以下教程使用cdn包含引导程序,但由于互联网连接,我手动下载了它。虽然下载的引导程序正在运行,但下拉菜单不起作用。有人可以帮帮我吗.. 在这个阶段我无法继续学习。提前致谢。 代码如下。

{% load static %}
<!doctype html> 
<html lang="en"> 
    <head> 
    <!-- Required meta tags --> 
    <meta charset="utf-"> 
    <meta name="viewport" content="width=device-width, initial-scale=, shrink-to-fit=no">
    <!-- Bootstrap CSS --> 
    <link rel="stylesheet" href="{% static 'css/bootstrap.min.css' %}" 
    integrity="sha-MCw/SFnGEfJTGXwEOngsVZtNXFoaoApmYmi\ uXoPkFOJwJERdknLPMO" 
    crossorigin="anonymous">


    <title>{% block title %}Newspaper App{% endblock title %}</title> 
</head> 
<body> 
        <nav class="navbar navbar-expand-md navbar-dark bg-dark mb-"> 
            <a class="navbar-brand" href="{% url 'home' %}">Newspaper</a>
            <button class="navbar-toggler" type="button" data-toggle="collapse" 
                data-target="#navbarCollapse" aria-controls="navbarCollapse" 
                aria-expanded="false" aria-label="Toggle navigation"> 
                <span class="navbar-toggler-icon"></span>
            </button> 
            <div class="collapse navbar-collapse" id="navbarCollapse"> 
                {% if user.is_authenticated %} 
                    <ul class="navbar-nav ml-auto"> 
                        <li class="nav-item"> 
                            <a class="nav-link dropdown-toggle" data-toggle="dropdown "href="#" id="userMenu"
                                aria-expanded="false"> 
                                {{ user.username }} 
                            </a> 
                            <div class="dropdown-menu dropdown-menu-right" 
                                aria-labelledby="userMenu"> 
                                <a class="dropdown-item" 
                                href="{% url 'password_change'%}">Change password</a> 
                                <div class="dropdown-divider"></div> 
                                <a class="dropdown-item" href="{% url 'logout' %}"> 
                                    Log Out</a>
                            </div>
                        </li>
                    </ul>
                {% else %}
                    <form class="form-inline ml-auto"> 
                        <a href="{% url 'login' %}" class="btn btn-outline-secondary"> 
                        Log In</a> 
                        <a href="{% url 'signup' %}" class="btn btn-primary ml-">
                        Sign up</a> 
                    </form>
                {% endif %}
            </div>
        </nav>
        <div class="container"> 
            {% block content %} 
            {% endblock content %}
        </div>

    <!-- Optional JavaScript --> 
   <!-- <jQuery first, then Popper.js, then Bootstrap JS -->
   <script src="https://code.jquery.com/jquery-...slim.min.js" integrity="sha-qi/X+DzOrTabKJStQIAqVgRVzpbzosmXKp\ YfRvH+abtTEPijizo" crossorigin="anonymous"></script>
    <script src="https://cdnjs.cloudflare.com/ajax/libs/popper.js/\ ../ umd/popper.min.js" integrity="sha-ZMPrVomIykV++JUJjBkWLaUAdnaCwoqbB\ JiSnjAK/ lWvCWPIPm" crossorigin="anonymous"></script>
    <script src="{% static 'js/bootstrap.min.js' %}" 
    integrity="sha-ChfqqxuZUCnJSK+MXmPNIyEZbWhIMqErYiqJxyMiZ\ OW/JmZQstwEULTy" 
    crossorigin="anonymous"></script>

</body> 
</html>
#settings.py
"""
Django settings for helloworld_project project.

Generated by 'django-admin startproject' using Django 3.0.5.

For more information on this file, see
https://docs.djangoproject.com/en/3.0/topics/settings/

For the full list of settings and their values, see
https://docs.djangoproject.com/en/3.0/ref/settings/
"""

import os

# Build paths inside the project like this: os.path.join(BASE_DIR, ...)
BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))


# Quick-start development settings - unsuitable for production
# See https://docs.djangoproject.com/en/3.0/howto/deployment/checklist/

# SECURITY WARNING: keep the secret key used in production secret!
SECRET_KEY = 'z0qdn^sf&ill&gg%3myb#q)bzp$!^xnn-3(1po+blyjt1(bxyv'

# SECURITY WARNING: don't run with debug turned on in production!
DEBUG = True

ALLOWED_HOSTS = []


# Application definition

INSTALLED_APPS = [

    #local
    'users.apps.UsersConfig',
    'pages.apps.PagesConfig',
    'articles.apps.ArticlesConfig',
    #'blog.apps.BlogConfig',
    #'accounts.apps.AccountsConfig',
    #'posts.apps.PostsConfig',
    #'page.apps.PageConfig',

    # 3rd Party
    'crispy_forms',

    'django.contrib.admin',
    'django.contrib.auth',
    'django.contrib.contenttypes',
    'django.contrib.sessions',
    'django.contrib.messages',
    'django.contrib.staticfiles',
]

TIME_ZONE = 'Africa/Lagos'

MIDDLEWARE = [
    'django.middleware.security.SecurityMiddleware',
    'django.contrib.sessions.middleware.SessionMiddleware',
    'django.middleware.common.CommonMiddleware',
    'django.middleware.csrf.CsrfViewMiddleware',
    'django.contrib.auth.middleware.AuthenticationMiddleware',
    'django.contrib.messages.middleware.MessageMiddleware',
    'django.middleware.clickjacking.XFrameOptionsMiddleware',
]

ROOT_URLCONF = 'helloworld_project.urls'

TEMPLATES = [
    {
        'BACKEND': 'django.template.backends.django.DjangoTemplates',
        'DIRS': [os.path.join(BASE_DIR, 'templates')],
        'APP_DIRS': True,
        'OPTIONS': {
            'context_processors': [
                'django.template.context_processors.debug',
                'django.template.context_processors.request',
                'django.contrib.auth.context_processors.auth',
                'django.contrib.messages.context_processors.messages',
            ],
        },
    },
]

WSGI_APPLICATION = 'helloworld_project.wsgi.application'


# Database
# https://docs.djangoproject.com/en/3.0/ref/settings/#databases

DATABASES = {
    'default': {
        'ENGINE': 'django.db.backends.sqlite3',
        'NAME': os.path.join(BASE_DIR, 'db.sqlite3'),
    }
}


# Password validation
# https://docs.djangoproject.com/en/3.0/ref/settings/#auth-password-validators

AUTH_PASSWORD_VALIDATORS = [
    {
        'NAME': 'django.contrib.auth.password_validation.UserAttributeSimilarityValidator',
    },
    {
        'NAME': 'django.contrib.auth.password_validation.MinimumLengthValidator',
    },
    {
        'NAME': 'django.contrib.auth.password_validation.CommonPasswordValidator',
    },
    {
        'NAME': 'django.contrib.auth.password_validation.NumericPasswordValidator',
    },
]


# Internationalization
# https://docs.djangoproject.com/en/3.0/topics/i18n/

LANGUAGE_CODE = 'en-us'

TIME_ZONE = 'UTC'

USE_I18N = True

USE_L10N = True

USE_TZ = True


# Static files (CSS, JavaScript, Images)
# https://docs.djangoproject.com/en/3.0/howto/static-files/

STATIC_URL = '/static/'
AUTH_USER_MODEL = 'users.CustomUser'
STATICFILES_DIRS = [os.path.join(BASE_DIR, 'static')]

STATIC_ROOT = os.path.join(BASE_DIR, 'staticfiles')
LOGIN_REDIRECT_URL = 'home'
LOGOUT_REDIRECT_URL = 'home'

CRISPY_TEMPLATE_PACK = 'bootstrap4'

EMAIL_BACKEND = 'django.core.mail.backends.console.EmailBackend'
'''EMAIL_HOST = 'smtp.sendgrid.net' 
EMAIL_HOST_USER = 'apikey' 
EMAIL_HOST_PASSWORD = 'my_sendgrid_password'
EMAIL_PORT = 587
EMAIL_USE_TLS = True
#ACCOUNT_EMAIL_VERIFICATION = 'none'
'''
#views.py
from django.urls import reverse_lazy
from django.views.generic import CreateView
from .forms import CustomUserCreationForm

# Create your views here.


class SignUpView(CreateView):
    form_class = CustomUserCreationForm
    success_url = reverse_lazy('login')
    template_name = 'signup.html

登录、注销等在模板/注册/

#project_urls.py
"""helloworld_project URL Configuration

The `urlpatterns` list routes URLs to views. For more information please see:
    https://docs.djangoproject.com/en/3.0/topics/http/urls/
Examples:
Function views
    1. Add an import:  from my_app import views
    2. Add a URL to urlpatterns:  path('', views.home, name='home')
Class-based views
    1. Add an import:  from other_app.views import Home
    2. Add a URL to urlpatterns:  path('', Home.as_view(), name='home')
Including another URLconf
    1. Import the include() function: from django.urls import include, path
    2. Add a URL to urlpatterns:  path('blog/', include('blog.urls'))
"""
from django.contrib import admin
from django.urls import path, include

urlpatterns = [
    path('admin/', admin.site.urls),
    path('users/', include('users.urls')),
    path('users/', include('django.contrib.auth.urls')),
    path('', include('pages.urls')),

    #path('accounts/', include('django.contrib.auth.urls')),
    #path('accounts/', include('accounts.urls')),
    #path('', include('blog.urls')),
    #path('', include('posts.urls')),
    #path('', include('page.urls')),
    #path('', include('pages.urls')),

]

最后下面是app_level url

#app_urls.py
from django.urls import path


from .views import SignUpView


urlpatterns = [
    path('signup', SignUpView.as_view(), name='signup'),
]

【问题讨论】:

    标签: django bootstrap-4


    【解决方案1】:

    下载 Jquery 和 Popper JS 并放在静态文件夹中

    【讨论】:

    • 我已经这样做了,但它仍然无法正常工作。我将 jQuery.min.js 和 popper.min.js 和 bootstrap.min.js 存储在 my_project/static/J 中并将其加载到我的模板中,但它仍然无法正常工作。
    • 移除脚本标签上的完整性属性
    • 你能告诉我们你的观点吗,py,urls.py和settings.py?
    • 由于调试模式=True,首先尝试删除STATIC_ROOT(只需将其注释掉)或者您可以使用命令python manage.py collectstatic并将文件放在staticfiles/文件夹中
    • 我取消了 STATIC_URL 的注释,但它不起作用。我删除了评论并运行了 python manage.py colecstatic ,但它仍然无法正常工作。请您认为接下来我使用哪个评论将静态收集回静态文件夹
    【解决方案2】:

    我曾经遇到过这样的问题: 我希望我的解决方案对你有用。

    您在 html 文件中使用的 jquery 库 (jquery-.slim.min.js) 可能不包含创建下拉效果所需的函数,请改用 jquery.min.js。

    从您的 html 文件中删除它:

    <script src="https://code.jquery.com/jquery-...slim.min.js" integrity="sha-qi/X+DzOrTabKJStQIAqVgRVzpbzosmXKp\ YfRvH+abtTEPijizo" crossorigin="anonymous"></script>
    

    并使用下面的 jquery.min:

    <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.5.1/jquery.min.js"></script>
    

    连接到互联网并刷新。

    P:S 你也可以通过jquery 下载 jquery.min.js,它只有大约 87kb。然后复制代码并将其保存为静态文件夹中的 jquery.min.js 并将其连接到您的模板中,如下所示:

    <script src="{% static 'jquery.min.js' %}"></script>
    

    您将不再需要互联网来使用它。我认为您使用的 jquery 库是问题所在。

    【讨论】:

      【解决方案3】:

      这件事以前发生在我身上。 我如何解决它只是按顺序放置 Jquery,然后是 Popper js,然后是 Boostrap js。 我发现下拉功能依赖于 Popper 和 Jquery。

      查看您的代码,我看到您遵循了该顺序,但我不确定您使用 django 加载 boostrap 的方式。

      请获取 boostrap cdn,(与 Popper 和 Jquery 相同的地方),重新启动服务器,使用 SHIFT + F5 清除浏览器缓存,然后重试。

      确保您有互联网连接。

      【讨论】:

        【解决方案4】:

        这是第 23 行的错误。分号被我放错了。

        【讨论】:

          猜你喜欢
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 2019-01-10
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          相关资源
          最近更新 更多