用anaconda创建一个虚拟环境并进入环境
pip install django
然后按照如下操作验证是否安装成功
(django) C:\Users\M>python
Python 3.9.18 (main, Sep 11 2023, 14:09:26) [MSC v.1916 64 bit (AMD64)] on win32
Type "help", "copyright", "credits" or "license" for more information.
>>> import django
>>> print(django.get_version())
4.2.11
然后ctrl+z退出来,
(django) D:\>cd D:\Pycharm_data
(django) D:\Pycharm_data>django-admin startproject mysite
(django) D:\Pycharm_data>cd mysite
(django) D:\Pycharm_data\mysite>code .
然后你会进入vscode
(django) D:\Pycharm_data\mysite>python manage.py runserver
Watching for file changes with StatReloader
Performing system checks...
System check identified no issues (0 silenced).
You have 18 unapplied migration(s). Your project may not work properly until you apply the migrations for app(s): admin, auth, contenttypes, sessions.
Run 'python manage.py migrate' to apply them.
March 19, 2024 - 09:17:58
Django version 5.0.3, using settings 'mysite.settings'
Starting development server at http://127.0.0.1:8000/
Quit the server with CTRL-BREAK.
在项目中创建应用
创建应用
(django) D:\Pycharm_data\mysite>python manage.py startapp hello
激活应用
编写视图
views.py文件
from django.shortcuts import render
from django import http
# Create your views here.
def index(request):
return http.HttpResponse("hello world")
配置路由
主路由
mysite文件夹里的urls.py
from django.contrib import admin
from django.urls import path,include
urlpatterns = [
path("admin/", admin.site.urls),
path('hello/',include('hello.urls')),
]
子路由
在hello的文件夹里新建urls.py(只能是这个名字)
from django.urls import path
from . import views
urlpatterns=[
path("",views.index)
]