为每个Django Web应用程序推荐六个Python软件包

图片



那里有无数个易于添加到任何项目的Python软件包。但是也有一些软件包是您不禁不得不在任何Django Web应用程序中使用的,因为它们已被证明非常有用且节省时间。



我们决定将重点放在您最终将要定期安装的软件包上,并讨论安装和使它们准备就绪所需的配置。



虽然某些Python软件包提供了很棒的特定于项目的功能,但下面讨论的软件包是最常见的Django软件包。



Django Web框架



但是我们不能不谈论Django Web框架就跳入Django软件包。

Web框架由模块或程序包组成,使开发人员可以快速编写Web应用程序,而不必处理协议的特定细节和组织Web应用程序的其他方面。



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. .



它最初是为Django构建的,但现在被视为用于分隔配置设置的“通用工具”。



env> mysite>(新文件).env



SECRET_KEY =sdjioerb43buobnodhioh4i34hgip
DEBUG =True


env> mysite> mysite> settings.py



from decouple import config

SECRET_KEY = config('SECRET_KEY')
DEBUG = config('DEBUG', cast=bool)


在您的项目文件夹中创建一个名为.env的新文件,然后将config导入settings.py文件中。然后将所有要隐藏的配置设置和变量移到.env文件中,并使用python-decouple config(“变量”)格式调用每个变量。



如果您需要更多信息,请访问使用Python解耦保护Django敏感变量页面




All Articles