Il existe d'innombrables packages Python faciles à ajouter à n'importe quel projet. Mais il existe également quelques packages que vous ne pouvez tout simplement pas vous empêcher d'utiliser dans n'importe quelle application Web Django, car ils se sont avérés extrêmement utiles et rapides.
Nous avons décidé de nous concentrer sur les packages que vous finirez par installer régulièrement et de parler de l'installation et des configurations nécessaires pour les préparer.
Python- , , , , — Django-.
- Django
Django-, - Django.
- , , - -.
Django - (. .: full-stack) -, , , , . , , .
Django:
macOS
(env)User-Macbook:env user$ pip install django
Windows
(env)C:\Users\Owner\desktop\env> pip install django
Django — 3.0.8. , — pip install django.
, , pip install django==2.1.15. , , , .
- Django. - Django, : Django . , , , « - Django ».
, Python-, - Django, Django, . .
(1) Django TinyMCE4 Lite
macOS
(env)User-Macbook:mysite user$ pip install django-tinymce4-lite
Windows
(env) C:\Users\Owner\Desktop\Code\env\mysite>pip install django-tinymce4-lite
-, Python- django-tinymce4-lite. , , — Django- django-tinymce4, Django- TinyMCE.
TinyMCE — WSIWYG (« , ») , HTML- « ». Python- , , , HTML .
env > mysite > mysite > settings.py
INSTALLED_APPS = [
...
...
'tinymce',
]
TINYMCE_DEFAULT_CONFIG = {
'height': 400,
'width': 1000,
'cleanup_on_startup': True,
'custom_undo_redo_levels': 20,
'selector': 'textarea',
'browser_spellcheck': 'true',
'theme': 'modern',
'plugins': '''
textcolor save link image media preview codesample contextmenu
table code lists fullscreen insertdatetime nonbreaking
contextmenu directionality searchreplace wordcount visualblocks
visualchars code fullscreen autolink lists charmap print hr
anchor pagebreak
''',
'toolbar1': '''
fullscreen preview bold italic underline | fontselect,
fontsizeselect | forecolor backcolor | alignleft alignright |
aligncenter alignjustify | indent outdent | bullist numlist table |
| link image media | codesample
''',
'toolbar2': '''
visualblocks visualchars |
charmap hr pagebreak nonbreaking anchor | code |
''',
'contextmenu': 'formats | link image',
'menubar': True,
'statusbar': True,
}
tinymce settings.py, . , , .
env > mysite > mysite > urls.py
"""mysite URL Configuration
The `urlpatterns` list routes URLs to views. For more information please see:
https://docs.djangoproject.com/en/2.1/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('', include ('main.urls')),
path('tinymce/', include('tinymce.urls')), #add this
tinymce URL- .
env > mysite > main > models.py
from django.db import models
from tinymce import HTMLField
class MyModel(models.Model):
...
content = HTMLField()
, TinyMCE Django-, HTMLField . , Django-, « Django-» .
(1) Pillow
macOS
(env)User-Macbook:mysite user$ pip install Pillow
Windows
(env) C:\Users\Owner\Desktop\Code\env\mysite>pip install Pillow
, Django, , Django-. Django- , , , Pillow. Python Imaging Library .
env > mysite > mysite > settings.py
MEDIA_URL = '/media/'
MEDIA_ROOT = os.path.join(BASE_DIR, 'media')
URL settings.py.
env > mysite > mysite > urls.py
from django.contrib import admin
from django.urls import path, include
from django.conf import settings # add this
from django.conf.urls.static import static # add this
urlpatterns = [
path('admin/', admin.site.urls),
path('', include('main.urls')),
]
if settings.DEBUG: # add this
urlpatterns += static(settings.MEDIA_URL,
document_root=settings.MEDIA_ROOT)
urls.py URL- . , . , .
env > mysite > main > models.py
from django.db import models
class MyModel(models.Model):
...
image = models.ImageField(upload_to='images/')
, , ImageField 'images/' . media > images, .
, Django « Django».
(3) Django Crispy Forms
macOS
(env)User-Macbook:mysite user$ pip install django-crispy-forms
Windows
(env) C:\Users\Owner\desktop\code\env\mysite>pip install django-crispy-forms
Django. , . django-crispy-forms, .
env > mysite > mysite > settings.py
INSTALLED_APPS = [
...
'crispy_forms',
]
CRISPY_TEMPLATE_PACK = 'uni_form'
settings.py crispy_forms . , crispy forms .
crispy-. , (. .: INSTALLED_APPS), — , CSS- Bootstrap, Bootstrap django-crispy-forms.
env > mysite > main > templates > main > contact.html
{% load crispy_forms_tags %}
<form method="post">
{% csrf_token %}
{{form|crispy}}
<button type="submit">Submit</button>
</form>
django-crispy-forms {{form}} Django. , crispy-, settings.py.
« Django Crispy Forms» , « Django- » Django-.
(4) Django Tables
macOS
(env)User-Macbook:mysite user$ pip install django-tables2
Windows
(env) C:\Users\Owner\desktop\code\env\mysite>pip install django-tables2
, Django- , . django-tables2 — Django .
env > mysite > mysite > settings.py
INSTALLED_APPS = [
...
'django_tables2',
]
«Django tables» .
env > mysite > main > models.py
from django.db import models
class MyModel(models.Model):
name = models.CharField(max_length=100, verbose_name="full name")
email = models.EmailField(max_length=200)
, .
python manage.py makemigrations python manage.py migrate, Django. « Django» .
env > mysite > main > ( ) tables.py
import django_tables2 as tables
from .models import MyModel
class MyTable(tables.Table):
class Meta:
model = MyModel
fields = ("name", "email", )
tables.py — main, django_tables2, tables. , .
env > mysite > main > views.py (-)
...
from django_tables2 import SingleTableView
from .models import MyModel
from .tables import MyTable
class ListView(SingleTableView):
model = MyModel
table_class = MyTable
template_name = 'main/table.html'
-, views.py , , . .
env > mysite > main > urls.py (-)
from django.urls import path
from . import views
app_name = "main"
urlpatterns = [
path("table", views.ListView.as_view()),
]
, urls.py URL . -, «- Django».
env > mysite > main > views.py (-)
...
from django_tables2 import SingleTableView
from .models import MyModel
from .tables import MyTable
def list(request):
model = MyModel.objects.all()
table = MyTable(model)
return render(request=request, template_name="main/table.html", context={"model":model, "table":table})
- views.py. , .
env > mysite > main > urls.py (-)
from django.urls import path
from . import views
app_name = "main"
urlpatterns = [
path("table", views.list, name="list"),
]
URL urls.py .
env > mysite > main > templates > main > ( ) table.html
{ % load render_table from django_tables2 % }
<div >
{ % render_table table % }
</div >
, render_table from django_tables2 , render_table , .
- table, - table.
* CSS Bootstrap :
env > mysite > main > tables.py*
import django_tables2 as tables
from .models import MyModel
class MyTable(tables.Table):
class Meta:
model = MyModel
template_name = "django_tables2/bootstrap4.html"
fields = ("name", "email",)
, Bootstrap, tables.py. Lib > site-packages > django_tables2 > templates > django_tables2 .
env > mysite > main > templates > main > ( ) table.html
{% extends "main/header.html" %}
{% block content %}
{% load render_table from django_tables2 %}
<div class="container">
{% render_table table %}
</div>
{% endblock %}
, , CDN- Bootstrap. Bootstrap .
, extends CDN- Bootstrap, «Django extends tag and block content» (. .: Django- extends ) « - Django ».
(5) Django Filter
macOS
(env)User-Macbook:mysite user$ pip install django-filter
Windows
(env) C:\Users\Owner\desktop\code\env\mysite> pip install django-filter
, , , , . django-filter django-tables2, .
env > mysite > mysite > settings.py
INSTALLED_APPS = [
...
'django_filters',
]
Django- . , django_filters, django_filter.
env > mysite > main > ( ) filters.py
import django_filters
from .models import MyModel
class MyFilter(django_filters.FilterSet):
name = django_filters.CharFilter(lookup_expr='icontains')
class Meta:
model = MyModel
fields = {'name', 'email'}
— main, filters.py, django_filters. , .
django_filters.CharFilter , , name .
django_filters.CharFilter(lookup_expr='iexact'), .
env > mysite > main > views.py (-)
...
from django_tables2 import SingleTableMixin
from django_filters.views import FilterView
from .models import MyModel
from .tables import MyTable
from .filters import MyFilter
class ListView(SingleTableMixin, FilterView):
model = MyModel
table_class = MyTable
template_name = 'main/table.html'
filterset_class = MyFilter
, -, FilterView django_filters.views django_tables2 SingleTableView SingleTableMixin. filter.py.
- ListView SingleTableMixin FilterView filterset_class, .
env > mysite > main > templates > main > table.html
{% load render_table from django_tables2 %}
<div>
<br>
<form action="" method="GET">
{{filter.form}}
<button type="submit">Filter</button>
</form>
<br>
{% render_table table %}
</div>
- URL , HTML- form Django, . submit, . .
env > mysite > main > views.py (-)
...
from django_tables2.views import SingleTableMixin
from django_filter import FilterView
from .models import MyModel
from .tables import MyTable
def list(request):
model = MyModel.objects.all()
filterset_class = MyFilter(request.GET, model)
table = MyTable(filterset_class.qs)
return render(request=request, template_name="main/table.html", context={"model":model, "table":table, "filterset_class":filterset_class})
- , -, MyFilter «GET» . filterset_class , (. .: queryset) , filterset_class render.
env > mysite > main > templates > main > table.html
{% load render_table from django_tables2 %}
<div>
<br>
<form action="" method="GET">
{{filterset_class.form}}
<button type="submit">Filter</button>
</form>
<br>
{% render_table table %}
</div>
- filterset_class, , , . , -.
, Django Crispy Forms, — « Django Crispy Forms».
(6) Python Decouple
macOS
(env)User-Macbook:mysite user$ pip install python-decouple
Windows
(env) C:\Users\Owner\desktop\code\env\mysite> pip install python-decouple
, , Python-, — python-decouple. .
Il a été créé à l'origine pour Django, mais est maintenant considéré comme un "outil générique" pour séparer les paramètres de configuration.
env> mysite> (nouveau fichier) .env
SECRET_KEY =sdjioerb43buobnodhioh4i34hgip
DEBUG =True
env> monsite> monsite> settings.py
from decouple import config
SECRET_KEY = config('SECRET_KEY')
DEBUG = config('DEBUG', cast=bool)
Créez un nouveau fichier appelé .env dans le dossier de votre projet, puis importez la configuration dans le fichier settings.py. Ensuite, déplacez tous les paramètres de configuration et les variables que vous souhaitez masquer dans le fichier .env et appelez chaque variable en utilisant le format de configuration python-decouple ('variable').
Si vous avez besoin de plus d'informations, visitez la page Secure Django Sensitive Variables Using Python Decouple .