Django Unleashed Framework
1.42K subscribers
2.21K photos
1 video
2.64K links
Лучшие материалы по разработке на фреймворке Django на русском и английском языке

Разместить рекламу: @tproger_sales_bot

Правила общения: https://tprg.ru/rules

Другие каналы: @tproger_channels

Другие наши проекты: https://tprg.ru/media
Download Telegram
Django Charts via DRF and Chart.js - Step-by-Step Tutorial

Hello Coders!
Django is a powerful web framework built with Python that you can use to create fully functional web applications or web APIs. This article explains step-by-step how to showcase three different charts (pie, line, and bar chart) using D...

Read: https://app-generator.hashnode.dev/django-charts-via-drf-and-chartjs-step-by-step-tutorial
👍1
Jobs At * ReadTheDocs * April 2022 * Product-focused Application Developer

Job Posting: Product-focused Application Developer
Location: Fully remote
Timezone: UTC-8 to UTC+1
Schedule: 4 or 5 days
Salary: $60,000-$90,000
Status: Contractor
Experience: 3+ years in a software-related job
Thanks for your interest in working at ...

Read: https://kb.mdmdm.org/jobs-at-readthedocs-april-2022-product-focused-application-developer
Django Cheat Sheet

Here are some common commands you'll use while working with Django. If you can think of anything I should add, let me know!
Creating a New Project
django-admin startproject projectname

Read: https://chuckygari.hashnode.dev/django-cheat-sheet
👍3
Как загружать файлы и изображения в приложении Django

Подготовка проекта

Для начала создайте каталог, в котором будут находиться проект и виртуальная среда (она нужна, чтобы отделять проектные зависимости от операционной системы).

Теперь выполните команду cdна этот каталог и сформируйте виртуальную среду:
mkdir filesDjango
cd filesDjango
python3.8 -m venv env

Активируйте ее и туда же установите Django:
source env/bin/activate

pip install Django

Создайте новый проект Django и назовите его file uploads:
django-admin startproject fileuploads
В каталоге данного проекта создайте приложение с именем files. Приложения в Django используются для разделения различных компонентов и необходимы для масштабирования самих приложений. Они также являются перемещаемыми элементами и их можно перетащить в другой проект Django, не ломая код.
django-admin startapp files
Добавьте файлы приложения к списку установленного софта в файле settings.py:
INSTALLED_APPS = [
'django.contrib.admin',
'django.contrib.auth',
'django.contrib.contenttypes',
'django.contrib.sessions',
'django.contrib.messages',
'django.contrib.staticfiles',
'files',
]

Django сохраняет файлы локально с помощью параметров MEDIA_ROOTи MEDIA_URL.

Определим эти константы в файле settings.py.:
import os

MEDIA_URL = "/media/"
MEDIA_ROOT = os.path.join(BASE_DIR, 'media')

MEDIA_ROOTбудет использоваться для управления сохраненными данными, а MEDIA_URL—  как url данных, которые требуется предоставить.

Загрузка данных

Самый простой вариант  —  загружать файлы с помощью FileFields. Начните с создания простой модели в файле models.py, которая будет содержать три поля: имя, электронную почту и файл для загрузки.
from django.db import models

# Создайте модели здесь.

class Resume(models.Model):
email = models.EmailField()
name = models.CharField(max_length= 255, blank=False, null=False)
file = models.FileField(upload_to= 'files/',null=True)

def __repr__(self):
return 'Resume(%s, %s)' % (self.name, self.file)

def __str__ (self):
return self.name

Параметр upload_toуказывает, куда будут перемещены файлы.

Запуск миграций

Миграции создадут актуальные таблицы в базе данных.
python3.8 manage.py migrate
Формы

Django имеет встроенный класс ModelForm, позволяющий легко создавать формы из модельных полей. Создайте новый файл forms.pyи добавьте код:
from django import forms
from .models import Resume

class ResumeForm(forms.ModelForm):

class Meta:
model = Resume
fields = ['email','name','file']

Определив форму, вы получите данные из нее с помощью request.FILES, используя запрос POSTв представлении. Чтобы получить данные, содержащиеся в форме, откройте файл view.pyи напишите следующий код:
from django.shortcuts import render
from django.http import HttpResponseRedirect
from .forms import ResumeForm

# Создайте здесь представления.

def upload_resume(request):
if request.method == 'POST':
form = ResumeForm(request.POST, request.FILES)
if form.is_valid():
form.save()
return HttpResponseRedirect("/")
else:
form = ResumeForm
return render(request, 'files/resume.html', {'form':form})

В вышеизложенном коде проверьте, чтобы метод запроса был POST, затем получите данные из формы, проверьте их и сохраните в базе данных. Если метод запроса  — GET, то отобразите форму в шаблоне.

Мы еще не создали шаблон upload.html(Django автоматически найдет его в соответствующем каталоге), с помощью которого будет отображена форма, так что давайте приступим. Создайте файлы, как показано ниже:
templates/
files/
-upload.html

Для отп[...]
👍3
HTML Template to PDF in Django

In this tutorial you will learn how to create a pdf from a HTML template using Django.
This may be very useful if you need to create an app that automize pdf generation. For this you can create a Django form, pass as context all the variables you wan...

Read: https://carlosenriquesalas.hashnode.dev/html-template-to-pdf-in-django
A simple approach for background task in Django

Introductino & Proof-Of-Concept
When there is a long running task, there are usually below 2 requirements:

As a user, I want to know the progress of the task
As a user, I want to get the output of the task if it is finished

We will use the out of t...

Read: https://ivanyu2021.hashnode.dev/a-simple-approach-for-background-task-in-django
How To Add A Custom Rich Text-Editor In Your Django Website

In this article, I'll be taking you through the steps of integrating a text editor with the Django-Ckeditor package.
We wil going through 8 simple steps.
Let's get started...

Step 1: Installing Django-Ckeditor.
It'll only take a few steps.

Open the...

Read: https://dapoadedire.hashnode.dev/how-to-add-a-custom-rich-text-editor-in-your-django-website
Jobs Udemy April 2022 Senior Staff Software Engineer - Marketplace

ABOUT THE ROLE:
Do you love what you do? Are you passionate about programming? If you love challenges and strive for excellence, come build the future of learning with us! We are a small, collaborative, fun group of engineers looking for someone like...

Read: https://kb.mdmdm.org/jobs-udemy-april-2022-senior-staff-software-engineer-marketplace
Using Minio with django-storages

TL;DR Here's the example code on github: https://github.com/naomiaro/django-minio-storage
This post assumes that you've added a host entry for minio to /etc/hosts
127.0.0.1 minio
Recently while working on an application for the BC Public Service, I...

Read: https://naomiaro.hashnode.dev/using-minio-with-django-storages
Build a Contact Application with Django

A contact application is a database that collects and stores user contact data. The contact app is a widely used application, similar to the contact application on your mobile phone, that stores data such as user contact names, phone numbers, email a...

Read: https://appsmith.hashnode.dev/build-a-contact-application-with-django
Authentication And Authorization in Django

In this article, we will be reviewing what authentication and authorization mean.
Most times it gets confusing to differentiate between authentication and authorization. I hope this article solves this confusion. Stay focused as we dive into this to...

Read: https://steelthedev.hashnode.dev/authentication-and-authorization-in-django
Behind the Scenes: Argonaut and AWS Lambda

There are two primary cloud-native environments that you see in today’s world:

Kubernetes/containers
Serverless

End users want to focus more on the application that is deployed rather than the infrastructure powering it.
With Argonaut, you’ll find ...

Read: https://argonaut.hashnode.dev/behind-the-scenes-argonaut-and-aws-lambda
Django News - Python in the Browser - May 6th 2022

Read: https://django-news.com/issues/126
Multiple File Upload With One Request In Django Rest Framework

Most times, we might want to upload multiple files to our server in a single request. In this tutorial I'll be uploading multiple files and then returning the image URL as response. I assume we already know how to install and setup django, django re...

Read: https://budescode.hashnode.dev/multiple-file-upload-with-one-request-in-django-rest-framework
👍2
How to auto generate Rest API Docs in Django Rest Framework with Open API schema for your Rest API?

Let's directly jump into the steps without wasting any time.

Open your root urls.py and paste this code at the end of your urls.py file -

from rest_framework.documentation import include_docs_urls

urlpatterns.extend([
# For autogenerated API d...

Read: https://blog.devjunction.in/how-to-auto-generate-rest-api-docs-in-django-rest-framework-with-open-api-schema-for-your-rest-api
Electron + Django, package it to production

1. Introduction & POC
How do we package the electron app with django? you may be more eager to know the answer if you have completed reading "Electron + Django, desktop app integrate JavaScript & Python".
In this blog, I would like to explain the pa...

Read: https://ivanyu2021.hashnode.dev/electron-django-package-it-to-production
Electron + Django ( Part 2 ), package it to production

1. Introduction & POC
How do we package the electron app with django? you may be more eager to know the answer if you have completed reading "Electron + Django ( Part 1 ), desktop app integrate JavaScript & Python".
In this blog, I would like to exp...

Read: https://ivanyu2021.hashnode.dev/electron-django-part-2-package-it-to-production
👍1
Managing Multiple User Types With Django And Django Rest Framework

When creating a Django program you might want to have different users with varied permissions and features accessible to them. I've seen that this is a typical difficulty that many developers face in the early phases of development, therefore I've de...

Read: https://lyrx.hashnode.dev/managing-multiple-user-types-with-django-and-django-rest-framework
Google SSO Integration with Django

Hi ,
Nowadays Instead of custom authentication everybody is using the SSO . Instead of maintaining the passwords and user information we are depending on the trusted companies like Google , OKTA... etc. In the same way I migrated project to remove th...

Read: https://venkatesh.hashnode.dev/google-sso-integration-with-django
How to set up environment variables in Django?

Django does not come with built-in support for dot env(.env) files. But we have an amazing Python package for that.

Let’s first install this package in our Django project’s virtual environment.

pip install python-dotenv


The next step is to create...

Read: https://blog.devjunction.in/set-up-environment-variables-in-django