Python 3 django шпаргалка

Шпаргалка по Django

Всякий раз, когда я создаю проект Django, я следую порядку выполнения работ. Имейте в виду, что это всего лишь один из возможных вариантов, и вы можете найти тот, который подходит вам больше!

  • Подготовьте каталог проекта
  • Создайте виртуальное окружение
  • Установите/обновите Django
  • Установите зависимости
  • Создайте проект Django
  • Создайте приложение Django
  • Создайте суперпользователя
  • Добавьте приложение в файл settings.py проекта
  • Запустите начальные миграции
  • Запустите сервер разработки
  • Создайте свои модели
  • Напишите/запустите тесты на ваших моделях
  • Выполните миграции и запустите их
  • Создайте формы, если таковые имеются
  • Создайте представления, функции или классы
  • Обновите пути с вашими представлениями
  • Создайте шаблоны для представлений
  • Напишите/запустите тесты для ваших представлений

⚠️ Не пропускайте документацию! Я писал это руководство в основном для себя, и хотя я с радостью поделюсь им со всеми, кто найдет его полезным, я не могу не порекомендовать ознакомиться с официальной документацией!

📝 Примечание: Структура этой шпаргалки более или менее соответствует порядку выполнения работ, описанному выше. Внизу также есть раздел полезных советов и других общих сведений о синтаксисе. Не стесняйтесь пропустить его!

Настройка

Если вы начинаете с нуля:

# create the project directory ~$ mkdir > # access that directory ~$ cd > # initialize a git repo within that directory ~$ git init 

При запуске из существующего репозитория:

# fork the project (if necessary) # clone your forked copy to your computer ~$ git clone > # access that directory ~$ cd > 

Начало работы над проектом Django:

Создайте виртуальную среду:

# create your virtual environment (make sure you are # still within that directory!) ~$ python -m venv .venv # activate that virtual environment ~$ source .venv/bin/activate # Mac OS C:> ./.venv/Scripts/Activate.ps1 # Windows # to deactivate your virtual environment ~$ deactivate 

Установите пакет Django:

# install Django ~$ python -m pip install Django # upgrade Django (if necessary) ~$ pip install -U Django # upgrade pip (if necessary) ~$ python -m pip install --upgrade pip # Mac OS C:> py -m pip install --upgrade pip # Windows 

Установите ваши зависимости:

# to create a requirements file that contains # your project dependencies ~$ pip freeze > requirements.txt # to install your project requirements # (if a file already exists) ~$ pip install -r requirements.txt 

Создайте проект Django

📝 Примечание: Не забудьте «.» после имени проекта!

# create your django project ~$ django-admin startproject > . # create your django app(s) ~$ python manage.py startapp > # to update your database for the migrations that # come with a default django installation ~$ python manage.py migrate # create a superuser to access the admin ~$ python manage.py createsuperuser # add your app(s) to the django project's settings.py INSTALLED_APPS = [ "app_name.apps.AppNameConfig", . . . ] 

Сервер разработки

# to start your development server ~$ python manage.py runserver => ex. http://127.0.0.1:8000 # to add localhost for use in development in # project's settings.py ALLOWED_HOSTS = [ "localhost", . . . ] 

Модели

Создайте свои модели

Эти модели должны быть созданы как таблицы базы данных с помощью команд миграции. Обратите внимание, что поле «id» автоматически создается Django для моделей по умолчанию.

# app_name/models.py from django.db import models class Customer(models.Model) name = models.Charfield('Customer', max_length=120) age = models.IntegerField() note = models.TextField(blank=True, null = True) email = models.EmailField(max_length=255, blank=True, null=True) credit = models.FloatField(blank=True) is_active = models.BooleanField(default=True) created_at = models.DateTimeField(auto_now_add=True) updated_at = models.DateTimeField(auto_now=True) # Create a Select Field (return value, display value) # If this is given, the default form widget will be a # select box instead of the standard text field and will # limit choices to the choices given. TYPE_CHOICES = ( ('Customer', 'Customer'), ('Supplier', 'Supplier'), ('Student', 'Student'), ) type = models.CharField(choices=TYPE_CHOICES) # model string representation def __str__(self): return self.name 

Взаимосвязи между моделями

# One-to-Many: supplier = models.ForeignKey(Supplier, blank=True, null=True, on_delete=models.CASCADE) # where "Supplier" is the name of the model that the # field is referencing # on_delete can be set to models.CASCADE, models.ST_DEFAULT or models.SET_NULL # Many-to-Many: tags = models.ManyToManyField(Tag, blank=True) # One to One User = models.OneToOneField(User, on_delete=models.CASCADE) 

Здесь приведены примеры нескольких моделей, некоторые из которых отображают отношения «один ко многим», а некоторые — «многие ко многим»:

from django.db import models from django.conf import settings USER_MODEL = settings.AUTH_USER_MODEL # Create your models here. class Recipe(models.Model): name = models.CharField(max_length=125) author = models.ForeignKey( USER_MODEL, related_name="recipes", on_delete=models.CASCADE, null=True, ) description = models.TextField() image = models.URLField(null=True, blank=True) created = models.DateTimeField(auto_now_add=True) updated = models.DateTimeField(auto_now=True) servings = models.PositiveSmallIntegerField(null=True) def __str__(self): return f" by " class Step(models.Model): recipe = models.ForeignKey( "Recipe", related_name="steps", on_delete=models.CASCADE, ) order = models.PositiveSmallIntegerField() directions = models.CharField(max_length=300) food_items = models.ManyToManyField("FoodItem", blank=True) def __str__(self): return f" " 

Модели в панели администратора

Чтобы отобразить объекты модели в панели администратора по адресу localhost:8000/admin, зарегистрируйте модель в файле администратора приложения по адресу app_name/admin.py. Вы также можете указать поля, которые вы хотите использовать в панели администратора.

from django.contrib import admin from app_name.models import ModelName # Register your models here # Custom model Admin (admin.py): class BlogAdmin(admin.ModelAdmin) fields = ("title", "description") # Fields to use for add/edit/show page list_display = ("title", "description") # fields to display in search page list_display_links = ("title") # fields that will be a link in search page ordering("date_created",) # Ordering allowed in the search page search_fields("title", "description") # Search fields allowed in the search page # Register app admin.site.register(Blog, BlogAdmin) 

Пути

Маршрутизация

Вам необходимо соединить пути, хранящиеся в файле urls.py каждого приложения, с urls.py вашего проекта в файле project_name/urls.py.

from django.contrib import admin from django.urls import path, include, reverse_lazy from django.views.generic.base import RedirectView urlpatterns = [ path('admin/', admin.site.urls), # Django adds this automatically path("", include('app_name.urls')) # include your app urls with include() path("recipes/", include('recipes.urls')), path("", RedirectView.as_view(url=reverse_lazy("recipes_list")), name="home"), # write a redirect view for your home page like this ] 

Пути приложений

from django.urls import path from recipes.views import ( RecipeCreateView, RecipeDeleteView, RecipeUpdateView, log_rating, create_shopping_item, delete_all_shopping_items, ShoppingItemListView, RecipeDetailView, RecipeListView, ) urlpatterns = [ path("", RecipeListView.as_view(), name="recipes_list"), path("/", RecipeDetailView.as_view(), name="recipe_detail"), path("/delete/", RecipeDeleteView.as_view(), name="recipe_delete"), path("new/", RecipeCreateView.as_view(), name="recipe_new"), path("/edit/", RecipeUpdateView.as_view(), name="recipe_edit"), path("/ratings/", log_rating, name="recipe_rating"), path("shopping_items/create", create_shopping_item, name="shopping_item_create"), path("shopping_items/delete", delete_all_shopping_items, name="delete_all_shopping_items"), path("shopping_items/", ShoppingItemListView.as_view(), name="shopping_items_list"), ] 

Формы

from django import forms from recipes.models import Rating class RatingForm(forms.ModelForm): class Meta: model = Rating fields = ["value"] # Render form in templates 
>

Представления

Представления на основе классов

from django.shortcuts import redirect from django.urls import reverse_lazy from django.views.generic.detail import DetailView from django.views.generic.edit import CreateView, DeleteView, UpdateView from django.views.generic.list import ListView from django.contrib.auth.mixins import LoginRequiredMixin from recipes.forms import RatingForm from recipes.models import Recipe, Ingredient, ShoppingItem class RecipeListView(ListView): model = Recipe template_name = "recipes/list.html" paginate_by = 2 class RecipeDetailView(DetailView): model = Recipe template_name = "recipes/detail.html" # Optional: change context data dictionary def get_context_data(self, **kwargs): context = super().get_context_data(**kwargs) context["rating_form"] = RatingForm() foods = [] for item in self.request.user.shopping_items.all(): foods.append(item.food_item) context["servings"] = self.request.GET.get("servings") context["food_in_shopping_list"] = foods return context class RecipeCreateView(LoginRequiredMixin, CreateView): model = Recipe template_name = "recipes/new.html" fields = ["name", "servings", "description", "image"] success_url = reverse_lazy("recipes_list") # Optional: overwrite form data (before save) def form_valid(self, form): form.instance.author = self.request.user return super().form_valid(form) class RecipeUpdateView(LoginRequiredMixin, UpdateView): model = Recipe template_name = "recipes/edit.html" fields = ["name", "servings", "description", "image"] success_url = reverse_lazy("recipes_list") class RecipeDeleteView(LoginRequiredMixin, DeleteView): model = Recipe template_name = "recipes/delete.html" success_url = reverse_lazy("recipes_list") 

Представления на основе функций

from django.shortcuts import redirect from django.urls import reverse_lazy from django.db import IntegrityError # Create your views here. def log_rating(request, recipe_id): if request.method == "POST": form = RatingForm(request.POST) if form.is_valid(): rating = form.save(commit=False) try: rating.recipe = Recipe.objects.get(pk=recipe_id) except Recipe.DoesNotExist: return redirect("recipes_list") rating.save() return redirect("recipe_detail", pk=recipe_id) def create_shopping_item(request): ingredient_id = request.POST.get("ingredient_id") ingredient = Ingredient.objects.get(id=ingredient_id) user = request.user try: ShoppingItem.objects.create( food_item=ingredient.food, user=user, ) except IntegrityError: pass return redirect("recipe_detail", pk=ingredient.recipe.id) 

Шаблоны

Ваши HTML-шаблоны должны храниться в папке app_folder/templates/имя_приложения.

Базовый шаблон

‘base.html’ должен храниться в корневом каталоге шаблонов, project_folder/templates

Читайте также:  Java build url with parameters

Шаблон пагинации

   
« first >">previous Page > of >. >">next last »

Шаблон DeleteView

  Delete > |   

Are you sure you want to delete ">"?

>

Шаблон DetailView

> | 
">Edit">Delete

>

by: >

Created on > | Updated on >

Serves >

>

Tags: >

>

Ingredients

AmountFood item
>>>
>">
in your list

Steps

    >

Шаблон UpdateView

Источник

Оцените статью