Уведомления

Группа в Telegram: @pythonsu

#1 Сен. 8, 2022 13:27:19

rita_des
Зарегистрирован: 2022-09-08
Сообщения: 1
Репутация: +  0  -
Профиль   Отправить e-mail  

проблемы с подключением jquery/select2 фреймворка на django

Ребята, я новичок , учу фреймворк джанго всего пару месяцев, сейчас делаю небольшой проект - маленькое веб-приложение с поиском маршрутов, и я столкнулась с проблемой - в моем html-файле не подключается библиотека jquery и посему я не могу улучшить дизайн своего проекта, очень рассчитываю на вашу помощь. Не бейте сильно тапками, если я там где-то чушь написала в коде.

base.html

 {% url 'cities:home' as cities_home_url%}
{% url 'cities:create' as cities_create_url%}
{% url 'trains:home' as trains_home_url%}
{% url 'trains:create' as trains_create_url%}
<!doctype html>
<html lang="ar" dir="rtl">
<head>
    <!-- Required meta tags -->
    <meta charset="utf-8">
    <meta name="viewport" content="width=device-width, initial-scale=1">
    <!-- Bootstrap CSS -->
    <link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/bootstrap@5.2.0/dist/css/bootstrap.rtl.min.css"
          integrity="sha384-+4j30LffJ4tgIMrq9CwHvn0NjEvmuDCOfk6Rpg2xg7zgOxWWtLtozDEEVvBPgHqE" crossorigin="anonymous">
    <link href="https://cdn.jsdelivr.net/npm/select2@4.1.0-rc.0/dist/css/select2.min.css" rel="stylesheet"/>
    <title>{% block title %}{% endblock %}</title>
     {{ form.media.css }}
</head>
<body>
<nav class="navbar navbar-expand-lg container" style="background-color: #e3f2fd;">
    <div class="container-fluid">
        <a class="navbar-brand" href="{% url 'home'%}">FindRoute</a>
        <button class="navbar-toggler" type="button" data-bs-toggle="collapse" data-bs-target="#navbarNavDropdown"
                aria-controls="navbarNavDropdown" aria-expanded="false" aria-label="Toggle navigation">
            <span class="navbar-toggler-icon"></span>
        </button>
        <div class="collapse navbar-collapse" id="navbarNavDropdown">
            <ul class="navbar-nav">
                <li class="nav-item {% if request.path == cities_home_url%}active {% endif %}">
                    <a class="nav-link" aria-current="page" href="{% url 'cities:home'%}">Города</a>
                </li>
                <li class="nav-item" {% if request.path== trains_home_url%}active {% endif %}>
                    <a class="nav-link" href="{% url 'trains:home'%}">Поезда</a>
                </li>
                <li class="nav-item">
                    <a class="nav-link" href="#">Pricing</a>
                </li>
                <li class="nav-item dropdown"
                    {% if request.path== cities_create_url or request.path== trains_create_url %} active {% endif %}
                >
                    <a class="nav-link dropdown-toggle" href="#" role="button" data-bs-toggle="dropdown"
                       aria-expanded="false">
                        Добавить
                    </a>
                    <ul class="dropdown-menu">
                        <li><a class="dropdown-item" href="{% url 'cities:create'%}">Новый город</a></li>
                        <li><a class="dropdown-item" href="{% url 'trains:create'%}">Новый поезд</a></li>
                        <li><a class="dropdown-item" href="#">Something else here</a></li>
                    </ul>
                </li>
            </ul>
        </div>
    </div>
</nav>
<div class="container">
    <div class="row">
        <div class="col-md-8 mx-auto my-4">
            {% if messages %}
            {% for message in messages %}
            {% if message.level == DEFAULT_MESSAGE_LEVELS.ERROR %}
            <div class="alert alert-danger alert-dismissible fade show" role="alert">
                {{ message }}
                <button type="button" class="btn-close" data-bs-dismiss="alert" aria-label="Close">
                    <span aria-hidden="true">&times;</span>
                </button>
            </div>
            {% else %}
            <div class="alert alert-success alert-dismissible fade show" role="alert">
                {{ message }}
                <button type="button" class="btn-close" data-bs-dismiss="alert" aria-label="Close">
                    <span aria-hidden="true">&times;</span>
                </button>
            </div>
            {% endif %}
            {% endfor %}
            {% endif %}
        </div>
    </div>
</div>
<div class="container">
    {% block content %}{% endblock %}
</div>
<!-- Optional JavaScript; choose one of the two! -->
<!-- Option 1: Bootstrap Bundle with Popper -->
<script src="https://cdn.jsdelivr.net/npm/bootstrap@5.2.0/dist/js/bootstrap.bundle.min.js"
        integrity="sha384-A3rJD856KowSb7dwlZdYEkO39Gagi7vIsF0jrRAoQmDKKtQBHUuLZ9AsSv4jD4Xa"
        crossorigin="anonymous"></script>
<script src="https://code.jquery.com/jquery-3.4.1.min.js"></script>
    <script src="https://cdn.jsdelivr.net/npm/select2@4.1.0-rc.0/dist/js/select2.min.js"></script>
<script>
    $(document).ready(function() {
    $('.js-example-basic-single').select2();
    $('.js-example-basic-multiple').select2();
});
</script>
{{ form.media.js }}
</body>
</html>

forms.py

 from django import forms
from cities.models import City
class RouteForm(forms.Form):
    from_city = forms.ModelChoiceField(
        label='Откуда', queryset=City.objects.all(), widget=forms.Select(
            attrs={ 'class': 'form-control js-example-basic-single' }))
    to_city = forms.ModelChoiceField(
        label='Куда', queryset=City.objects.all(), widget=forms.Select(
            attrs={'class': 'form-control js-example-basic-single'}))
    cities = forms.ModelMultipleChoiceField(
        label='Через города', queryset=City.objects.all(), required=False,
        widget=forms.SelectMultiple(
            attrs={'class': 'form-control js-example-basic-multiple'}
        )
    )
    travelling_time = forms.IntegerField(label='Время в пути', widget=forms.NumberInput(attrs={
            'class': 'form-control',
            'placeholder': 'Время в пути'
        }))

settings.py

 from pathlib import Path
# Build paths inside the project like this: BASE_DIR / 'subdir'.
BASE_DIR = Path(__file__).resolve().parent.parent
# Quick-start development settings - unsuitable for production
# See https://docs.djangoproject.com/en/4.0/howto/deployment/checklist/
# SECURITY WARNING: keep the secret key used in production secret!
SECRET_KEY = 'django-insecure-e4hk7u__%iz7x4#w+i^5entpbqdq7mk^fzmp!)4&yw38^6odip'
# SECURITY WARNING: don't run with debug turned on in production!
DEBUG = True
ALLOWED_HOSTS = []
# Application definition
INSTALLED_APPS = [
    'django.contrib.admin',
    'django.contrib.auth',
    'django.contrib.contenttypes',
    'django.contrib.sessions',
    'django.contrib.messages',
    'django.contrib.staticfiles',
    'django_select2',
    'routes',
    'cities',
    'trains',
]
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 = 'travel.urls'
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',
                'django.contrib.messages.context_processors.messages',
            ],
        },
    },
]
WSGI_APPLICATION = 'travel.wsgi.application'
# Database
# https://docs.djangoproject.com/en/4.0/ref/settings/#databases
DATABASES = {
    'default': {
        'ENGINE': 'django.db.backends.sqlite3',
        'NAME': BASE_DIR / 'db.sqlite3',
    }
}
# Password validation
# https://docs.djangoproject.com/en/4.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/4.0/topics/i18n/
LANGUAGE_CODE = 'en-us'
TIME_ZONE = 'UTC'
USE_I18N = True
USE_TZ = True
# Static files (CSS, JavaScript, Images)
# https://docs.djangoproject.com/en/4.0/howto/static-files/
STATIC_URL = 'static/'
# Default primary key field type
# https://docs.djangoproject.com/en/4.0/ref/settings/#default-auto-field
DEFAULT_AUTO_FIELD = 'django.db.models.BigAutoField'

urls.py

 import patterns as patterns
from django.contrib import admin
from django.urls import path, include
import routes
from routes.views import home
urlpatterns = [
    path('admin/', admin.site.urls),
    path('cities/', include(('cities.urls', 'cities'))),
    path('trains/', include(('trains.urls', 'trains'))),
    path('', home, name='home'),
    path("select2/", include("django_select2.urls")),
]

буду очень благодарна вам за помощь! Еще я не могу отзеркалить отображение моего проекта влево, может кто-то подскажет как это реализовать? Спасибо вам большое)

Отредактировано rita_des (Сен. 8, 2022 13:27:41)

Прикреплённый файлы:
attachment doc_2022-09-08_13-26-12.png (97,4 KБ)

Офлайн

Board footer

Модераторировать

Powered by DjangoBB

Lo-Fi Version