current position:Home>Day 1: learn the Django framework of Python development
Day 1: learn the Django framework of Python development
2022-01-30 00:56:31 【Job theory test】
Little knowledge , Great challenge ! This article is participating in “ A programmer must have a little knowledge ” Creative activities .
Django Introduce
Django It's an open Source code Of Web Application framework , from Python It's written in . Adopted MTV Framework model of , The model M, View V And templates T. It was originally developed to manage news content based websites owned by Lawrence publishing group , That is CMS( Content management system ) Software . And in 2005 year 7 Month in BSD license Issue under . This framework is based on the gypsy of Belgium Jazz guitar hand Django Reinhardt Named after .2019 year 12 month 2 Japan ,Django 3. 0 Release [1] .
---- From baidu baike
Start your Django The first step of the journey !
- Environment building :Python Distribution version anaconda Tools to manage local development environments
If you don't want to install anaconda, You can use python -m venv to_path< route >, Creating a virtual environment
Switch to the development environment , The virtual environment will basically have a activate file <linux yes sh,win yes bat Extension >
install Django edition , At present, it has reached 3.2.6 The development version of , Then you can choose the latest stable version :3.2.5.
Copy code
- The first step is to install :pip install Django # Install the latest version by default
D:> django-admin -h # Check the help document before creating the project
Type 'django-admin help ' for help on a specific subcommand.
Available subcommands:
[django]
check
compilemessages
createcachetable
dbshell
diffsettings
dumpdata
flush
inspectdb
loaddata
makemessages
makemigrations
migrate
runserver
sendtestemail
shell
showmigrations
sqlflush
sqlmigrate
sqlsequencereset
squashmigrations
startapp
startproject
test
testserver
Note that only Django core commands are listed as settings are not properly configured
(error: Requested setting INSTALLED_APPS, but settings are not configured. You must either
define the environment variable DJANGO_SETTINGS_MODULE or call settings.configure() before
accessing settings.).
Copy code
- Step 2: create a project :
django-admin startproject myDjango
- Step 3: create sub application : Enter the project first < There can be multiple sub applications in a project >
python manage.py startapp myapp
- Step 4: create a model :
from django.db import models
# Create your models here.
class UserInfo(models.Model):
name=models.CharField(max_length=10)
age=models.IntegerField()
addr=models.CharField(max_length=100)
gender=models.BooleanField()
birth=models.DateField()
def __str__(self):
return self.name
class ClassInfo(models.Model):
teacher=models.CharField(max_length=10)
class_room=models.IntegerField()
book=models.CharField(max_length=20)
def __str__(self):
""" In order to be in admin The field is displayed in the background and overridden str,1.x, Chinese garbled code still needs encode("utf-8") transcoding """
return self.teacher
Copy code
- Step 5: generate the migration script
python manage.py makemigrations myapp
- Step 6 execute the migration script
python manage.py migrate
- Step 7 create an administrator account
python manage.py createsuperuser
- Step 8 register admin
Register model class , If you want to manage foreground data through the background
from django.contrib import admin
from myapp.models import UserInfo, ClassInfo
# Register your models here.
class UserInfoAdmin(admin.ModelAdmin):
# This is displayed when registering for background editing ; Default full display
# fields = [ "name", "age", "gender", "addr", "birth"]
list_display = ("id", "name", "age", "gender", "addr", "birth")
class ClassInfoAdmin(admin.ModelAdmin):
# fields = [ "teacher", "class_room", "book"]
list_display = ("id", "teacher", "class_room", "book")
admin.site.register(UserInfo, UserInfoAdmin)
admin.site.register(ClassInfo, ClassInfoAdmin)
Copy code
- Step 9 enter the sub application views.py Create view
from django.shortcuts import render
from django.http.response import HttpResponse
# Create your views here.
def index(request):
return HttpResponse("Hello World!")
def detail(request):
return render(request,template_name="myapp/detail.html",content={"list":range(10)})
Copy code
- Step 10 configure urls, In the management background urls.py
from django.contrib import admin
from django.urls import path
# django1.1 After the version , String defined views are no longer supported
from myapp import views
urlpatterns = [
path('admin/', admin.site.urls),
re_path(r"^$",views.index),
path("detail/",views.detail),
]
# stay 1.x Version USES url, Support absolute and regular matching ;3.x distinguish path and re_path
Copy code
- Step 11 create a template file in the project root path :templates/myapp
<html>
<title></title>
<body>
<ul>
{% for info in infoList %}
<li>{{info}}</li>
{% endfor %}
</ul>
</body>
</html>
Copy code
- The twelfth step settings Set up
# myapp Need to be in settings/INSTALLED_APPS Additional application
INSTALLED_APPS=["...","...",
# Own application
"myapp",]
# admin The Chinese prompt area is displayed in the background
LANGUAGE_CODE='zh-hans'
TIME_ZONE = 'Asia/Shanghai'
# Total path configuration , Then go again. urls Find view
ROOT_URLCONF='myDjango.urls'
# Configure template path
TEMPLATES
***
'DIRS': [os.path.join(BASE_DIR,"templates")], # Be careful not to configure and view render The template path of is repeated
***
Copy code
Expand :python manage.py shell
Access to sqlite3 Database operation
>>> from myapp.models import ClassInfo
>>> ci=ClassInfo()
>>> ci.teacher=" Miss Tang "
>>> ci.class_room=1001
>>> ci.book="java"
>>> ci.save() # Remember to save after adding or modifying
>>> ci.delete() # Delete
>>> ClassInfo.objects.all() # Get all the data
>>> ClassInfo.objects.get(id=1) # The modified record is obtained first and then assigned and saved
Copy code
Start the application :python manage.py runserver
visit :http://127.0.0.1:8000/admin/
copyright notice
author[Job theory test],Please bring the original link to reprint, thank you.
https://en.pythonmana.com/2022/01/202201300056293499.html
The sidebar is recommended
- Install tensorflow and python 3.6 in Windows 7
- Python collects and monitors system data -- psutil
- Getting started with Python - object oriented - special methods
- Teach you how to use Python to transform an alien invasion game
- You can easily get started with Excel. Python data analysis package pandas (VI): sorting
- Implementation of top-level design pattern in Python
- Using linear systems in python with scipy.linalg
- How to get started quickly? How to learn Python
- Modifying Python environment with Mac OS security
- Better use atom to support jupyter based Python development
guess what you like
-
Better use atom to support jupyter based Python development
-
Fast power modulus Python implementation of large numbers
-
Python architects recommend the book "Python programmer's Guide" which must be read by self-study Python architects. You are welcome to take it away
-
Decoding the verification code of Taobao slider with Python + selenium, the road of information security
-
Python game development, pyGame module, python implementation of skiing games
-
Python collects and monitors system data -- psutil
-
Python + selenium automated test: page object mode
-
You can easily get started with Excel. Python data analysis package pandas (IV): any grouping score bar
-
Opencv skills | saving pictures in common formats as transparent background pictures (with Python source code) - teach you to easily make logo
-
Python ThreadPoolExecutor restrictions_ work_ Queue size
Random recommended
- Python generates and deploys verification codes with one click (Django)
- With "Python" advanced, you can catch all the advanced syntax! Advanced function + file operation, do not look at regret Series ~
- At the beginning of "Python", you must see the series. 10000 words are only for you. It is recommended to like the collection ~
- [Python kaggle] pandas basic exercises in machine learning series (6)
- Using linear systems in python with scipy.linalg
- The founder of pandas teaches you how to use Python for data analysis (mind mapping)
- Using Python to realize national second-hand housing data capture + map display
- Python image processing, automatic generation of GIF dynamic pictures
- Pandas advanced tutorial: time processing
- How to make Python run faster? Six tips!
- Django: use of elastic search search system
- Python 3.10 official release
- Python chat room (Tkinter writing interface, streaming, socket to realize private chat, group chat, check chat records, Mysql to store data)
- This pandas exercise must be successfully won
- [algorithm learning] sword finger offer 64 Find 1 + 2 +... + n (Java / C / C + + / Python / go / trust)
- leetcode 58. Length of Last Word(python)
- Problems encountered in writing the HTML content of articles into the database during the development of Django blog
- Understand Python's built-in function and add a print function yourself
- Python implements JS encryption algorithm in thousands of music websites
- leetcode 35. Search Insert Position(python)
- leetcode 1829. Maximum XOR for Each Query(python)
- [introduction to Python visualization]: 12 small examples of complete data visualization, taking you to play with visualization ~
- Learning this Python library can reduce at least 100 lines of code
- leetcode 67. Add Binary(python)
- Regular re parameter replacement of Python 3 interface automation test framework
- V. pandas based on Python
- Only 15 lines of code is needed for face detection! (using Python and openCV)
- [Python crawler Sao operation] you can crawl Sirius cinema movies without paying
- leetcode 69. Sqrt(x)(python)
- Teach you to read the source code of Cpython (I)
- Snowball learning started in the fourth quarter of Python. One needs three meals. I have a new understanding of Python functional programming, process-oriented, object-oriented and functional
- leetcode 88. Merge Sorted Array(python)
- Don't you know more about a python library before the end of 2021?
- Python crawler web page parsing artifact XPath quick start teaching!!!
- Use Python and OpenCV to watermark the image
- String and related methods of Python data type introduction
- Heapq module of Python module
- Introduction to beautiful soup of Python crawler weapon, detailed explanation, actual combat summary!!!
- Event loop of Python collaboration series
- Django docking pin login system