简体   繁体   中英

Problems with jquery/select2 framework - it doesn't work in my django project

i'm newbie in python, still learning this language and django framework. So i making simple project now, and now i meet this problem: i can't modify my design cause select2 and jquery not working in html document. Here is my files:

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.6.1.min.js" integrity="sha256-o88AwQnZB+VDvE9tvIXrMQaPlFFSUTR+nldQm1LuPXQ=" crossorigin="anonymous"></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

BASE_DIR = Path(__file__).resolve().parent.parent
DEBUG = True
ALLOWED_HOSTS = []

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'

DATABASES = {
    'default': {
        'ENGINE': 'django.db.backends.sqlite3',
        'NAME': BASE_DIR / 'db.sqlite3',
    }
}

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',
    },
]

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

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")),
]

So i'll so grateful if somebody helps me!

If you want to be able to use JQuery / select2 in HTML, you can do something like this.

page.html

<!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">

    <link href="https://cdn.jsdelivr.net/npm/select2@4.1.0-rc.0/dist/css/select2.min.css" rel="stylesheet"/>
</head>
<body>

<!-- Optional JavaScript; choose one of the two! -->
<select class="js-example-basic-single" name="state">
    <option value="AL">Alabama</option>
      ...
    <option value="WY">Wyoming</option>
</select>
<!-- 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.6.1.min.js"
  integrity="sha256-o88AwQnZB+VDvE9tvIXrMQaPlFFSUTR+nldQm1LuPXQ="
  crossorigin="anonymous"></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();
});
</script>
</body>
</html>

It may be that your forms.py doesn't set the class js-example-basic-single properly. If this is the case, This link may be able to further assist you.

I hope this answers your question.

it works for me in the following way

layout.html

<head>    
<link href="{% static 'select2/css/select2.css' %}" rel="stylesheet">
      <link href="{% static 'select2/css/select2-bootstrap4.min.css' %}" rel="stylesheet">
</head>
<body>
...
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.6.1/jquery.min.js"></script>
     <script src="{% static 'select2/js/select2.js' %}"></script>
      <script src="{% static 'select2/js/i18n/es.js' %}"></script>
      <script>

        $('.select2').select2({
            theme: "bootstrap4",
            language: 'es'
        });
        
        $(document).ready(function() {
            $('select[name="selector"]').select2();
        });
        </script>
</body>

in form.py

class ExampleForm(forms.ModelForm):
    class Meta:
        model = Example
        fields = '__all__'        
        widgets = {
            'name': forms.TextInput(attrs={'class':'form-control' }),
            'exampleselect': forms.Select(attrs={'class':'form-control select2'}),
        }

in templates/example/example_form.html

<form action="" method="post">{% csrf_token %} 
            <div class="mb-3">               
                {{form}}
            </div>            
            <button type="submit" class="btn btn-primary text-center">Save</button>
          </form>

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM