仅作为记录,大佬请跳过。
感谢b站大佬视频:传送门
一、建立django项目
这次博主使用第二种方式windows的命令提示符——建立django项目(之前是使用pycharm专业版建立传送门)
1、在windows的命令提示符里依次输入:
e:
cd 20210317web\a5djangocalculator
django-admin startproject mainproject
cd mainproject
python manage.py startapp firstweb
展示:
2、然后新建templates文件夹:
至此,django项目搭建完成。
最终框架展示:
二、所有源代码
现把所有文件的源代码列出:(实际上需要编写的文件只有标红框的文件
,其他文件不用处理(系统生成的什么就是什么);在此都列出)
1、migrations文件夹里的代码不用动
2、templates文件夹里
cal.html:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>计算页面</title>
</head>
<body>
<form method="POST" action="/cal">
{%csrf_token%}
第一个数字<input type="number" name="valueA">
+
第二个数字<input type="number" name="valueB">
<input type="submit" value="提交计算">
</form>
</body>
</html>
index.html:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>my first web from django</title>
</head>
<body>
<h1 style="color: red">my first django website</h1>
</body>
</html>
result.html:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>结果页面</title>
</head>
<body>
<h1>计算结果是:</h1><h2>{{data}}</h2>
</body>
</html>
3、母文件夹firstweb中
_init.py文件空
admin.py:
from django.contrib import admin
# Register your models here.
apps.py:
from django.apps import AppConfig
class FirstwebConfig(AppConfig):
name = 'firstweb'
model.py:
from django.db import models
# Create your models here.
tests.py:
from django.test import TestCase
# Create your tests here.
views.py:
from django.shortcuts import render
# Create your views here.
def index(request):
return render(request,'index.html')
def calpage(request):
return render(request,'cal.html')
def cal(request):
value_a=request.POST['valueA']
value_b=request.POST['valueB']
result=int(value_a)+int(value_b)
return render(request,'result.html',context={'data': result})
4、mainproject文件夹里
_init.py文件空;
settings.py:
"""
Django settings for mainproject project.
Generated by 'django-admin startproject' using Django 2.2.5.
For more information on this file, see
https://docs.djangoproject.com/en/2.2/topics/settings/
For the full list of settings and their values, see
https://docs.djangoproject.com/en/2.2/ref/settings/
"""
import os
# Build paths inside the project like this: os.path.join(BASE_DIR, ...)
BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
# Quick-start development settings - unsuitable for production
# See https://docs.djangoproject.com/en/2.2/howto/deployment/checklist/
# SECURITY WARNING: keep the secret key used in production secret!
SECRET_KEY = 'dh14=e^sy2*459-(833o=1g-9+*5qcy($=#0s7q$5xgymghwq9'
# SECURITY WARNING: don't run with debug turned on in production!
DEBUG = True
ALLOWED_HOSTS = []
# Application definition
INSTALLED_APPS = [
'django.contrib.admin',
'django.contrib.auth',
'django.contrib.contenttypes',
'django.contrib.sessions',
'django.contrib.messages',
'django.contrib.staticfiles',
'firstweb',
]
MIDDLEWARE = [
'django.middleware.security.SecurityMiddleware',
'django.contrib.sessions.middleware.SessionMiddleware',
'django.middleware.common.CommonMiddleware',
'django.middleware.csrf.CsrfViewMiddleware',
'django.contrib.auth.middleware.AuthenticationMiddleware',
'django.contrib.messages.middleware.MessageMiddleware',
'django.middleware.clickjacking.XFrameOptionsMiddleware',
]
ROOT_URLCONF = 'mainproject.urls'
TEMPLATES = [
{
'BACKEND': 'django.template.backends.django.DjangoTemplates',
'DIRS': [],
'APP_DIRS': True,
'OPTIONS': {
'context_processors': [
'django.template.context_processors.debug',
'django.template.context_processors.request',
'django.contrib.auth.context_processors.auth',
'django.contrib.messages.context_processors.messages',
],
},
},
]
WSGI_APPLICATION = 'mainproject.wsgi.application'
# Database
# https://docs.djangoproject.com/en/2.2/ref/settings/#databases
DATABASES = {
'default': {
'ENGINE': 'django.db.backends.sqlite3',
'NAME': os.path.join(BASE_DIR, 'db.sqlite3'),
}
}
# Password validation
# https://docs.djangoproject.com/en/2.2/ref/settings/#auth-password-validators
AUTH_PASSWORD_VALIDATORS = [
{
'NAME': 'django.contrib.auth.password_validation.UserAttributeSimilarityValidator',
},
{
'NAME': 'django.contrib.auth.password_validation.MinimumLengthValidator',
},
{
'NAME': 'django.contrib.auth.password_validation.CommonPasswordValidator',
},
{
'NAME': 'django.contrib.auth.password_validation.NumericPasswordValidator',
},
]
# Internationalization
# https://docs.djangoproject.com/en/2.2/topics/i18n/
LANGUAGE_CODE = 'zh-Hans'
TIME_ZONE = 'Asia/Shanghai'
USE_I18N = True
USE_L10N = True
USE_TZ = True
# Static files (CSS, JavaScript, Images)
# https://docs.djangoproject.com/en/2.2/howto/static-files/
STATIC_URL = '/static/'
urls.py:
"""mainproject URL Configuration
The `urlpatterns` list routes URLs to views. For more information please see:
https://docs.djangoproject.com/en/2.2/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
from firstweb import views
urlpatterns = [
path('admin/', admin.site.urls),
path('index/',views.index),
path('calpage/',views.calpage),
path('cal',views.cal)
]
wsgi.py:
"""
WSGI config for mainproject project.
It exposes the WSGI callable as a module-level variable named ``application``.
For more information on this file, see
https://docs.djangoproject.com/en/2.2/howto/deployment/wsgi/
"""
import os
from django.core.wsgi import get_wsgi_application
os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'mainproject.settings')
application = get_wsgi_application()
5、db.sqlite3是数据库,不用处理;
6、manage.py:
#!/usr/bin/env python
"""Django's command-line utility for administrative tasks."""
import os
import sys
def main():
os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'mainproject.settings')
try:
from django.core.management import execute_from_command_line
except ImportError as exc:
raise ImportError(
"Couldn't import Django. Are you sure it's installed and "
"available on your PYTHONPATH environment variable? Did you "
"forget to activate a virtual environment?"
) from exc
execute_from_command_line(sys.argv)
if __name__ == '__main__':
main()
首先的首先,在新建好django项目后,在settings.py里增加firstweb项
三、运行
在windows的命令提示符里使用
python manage.py runserver
然后在网页里输入相应网址即可。
结束web服务器按ctrl和c
,在命令提示符里先点击一下。
四、展示
结合urls.py的名称,输入网址:
http://127.0.0.1:8000/index/
http://127.0.0.1:8000/calpage/
参考
django目录:
————————————————————————————
随笔
pycharm的html自动填充快捷键
用tab
做法:先输入h1,再按tab