django配置*app*登录案例*orm简用
1.静态文件的配置和使用
1.静态文件的配置和使用
没有css样式:
添加样式
结果:
<html lang="en"> <head> <meta charset="utf-8"> <title>Signin Template for Bootstrap</title> <!-- Bootstrap core CSS --> <link href="https://cdn.bootcss.com/bootstrap/3.3.7/css/bootstrap.min.css" rel="stylesheet"> <!-- IE10 viewport hack for Surface/desktop Windows 8 bug --> <link href="../../assets/css/ie10-viewport-bug-workaround.css" rel="stylesheet"> <!-- Custom styles for this template --> <link href="signin.css" rel="stylesheet"> <!-- Just for debugging purposes. Don't actually copy these 2 lines! --> <!--[if lt IE 9]><script src="../../assets/js/ie8-responsive-file-warning.js"></script><![endif]--> <script src="../../assets/js/ie-emulation-modes-warning.js"></script> </head> <body> <div class="container"> <form class="form-signin"> <h2 class="form-signin-heading">Please sign in</h2> <label for="inputEmail" class="sr-only">Email address</label> <input type="email" id="inputEmail" class="form-control" placeholder="Email address" required="" autofocus=""> <label for="inputPassword" class="sr-only">Password</label> <input type="password" id="inputPassword" class="form-control" placeholder="Password" required=""> <div class="checkbox"> <label> <input type="checkbox" value="remember-me"> Remember me </label> </div> <button class="btn btn-lg btn-primary btn-block" type="submit">Sign in</button> </form> </div> <!-- /container --> <!-- IE10 viewport hack for Surface/desktop Windows 8 bug --> <script src="../../assets/js/ie10-viewport-bug-workaround.js"></script> </body> </html>
<html lang="en"> <head> <meta charset="utf-8"> <title>Signin Template for Bootstrap</title> <!-- Bootstrap core CSS --> <link href="https://cdn.bootcss.com/bootstrap/3.3.7/css/bootstrap.min.css" rel="stylesheet"> <!-- IE10 viewport hack for Surface/desktop Windows 8 bug --> <link href="../../assets/css/ie10-viewport-bug-workaround.css" rel="stylesheet"> <!-- Custom styles for this template --> <link href="signin.css" rel="stylesheet"> <!-- Just for debugging purposes. Don't actually copy these 2 lines! --> <!--[if lt IE 9]><script src="../../assets/js/ie8-responsive-file-warning.js"></script><![endif]--> <script src="../../assets/js/ie-emulation-modes-warning.js"></script> </head> <body> <div class="container"> <form class="form-signin"> <h2 class="form-signin-heading">请登录:</h2> <label for="inputEmail" class="sr-only">Email address</label> <input type="text" id="inputEmail" class="form-control" placeholder="用户名" required="" autofocus=""> <label for="inputPassword" class="sr-only">Password</label> <input type="password" id="inputPassword" class="form-control" placeholder="密码" required=""> <div class="checkbox"> <label> <input type="checkbox" value="remember-me"> 记住密码 </label> </div> <button class="btn btn-lg btn-primary btn-block" type="submit">登录</button> </form> </div> <!-- /container --> <!-- IE10 viewport hack for Surface/desktop Windows 8 bug --> <script src="../../assets/js/ie10-viewport-bug-workaround.js"></script> </body> </html>
body { padding-top: 40px; padding-bottom: 40px; background-color: #eee; } .form-signin { max-width: 330px; padding: 15px; margin: 0 auto; } .form-signin .form-signin-heading, .form-signin .checkbox { margin-bottom: 10px; } .form-signin .checkbox { font-weight: normal; } .form-signin .form-control { position: relative; height: auto; -webkit-box-sizing: border-box; -moz-box-sizing: border-box; box-sizing: border-box; padding: 10px; font-size: 16px; } .form-signin .form-control:focus { z-index: 2; } .form-signin input[type="email"] { margin-bottom: -1px; border-bottom-right-radius: 0; border-bottom-left-radius: 0; } .form-signin input[type="password"] { margin-bottom: 10px; border-top-left-radius: 0; border-top-right-radius: 0; }
现在是直接本地打开的登录页面,我们应该是访问网页时才打开网页:
settings最后面有个配置 是静态页面存放的目录别名 STATIC_URL = '/static/'
STATIC_URL = '/static/' # 别名,浏览器上访问的是别名static,找资源是从STATICFILES_DIRS里面找,不是用static1,2访问,但是能访问到这些目录下的静态文件 STATICFILES_DIRS = [ #如果静态文件放到这些目录下,并且外接引入css,那么访问别名static的时候就能将这里面样式链接使用出来。 os.path.join(BASE_DIR, 'static1'), #static下有css,js,img,插件等等目录。 os.path.join(BASE_DIR, 'static'), #如果多个静态目录中相同路径有相同的文件,那么从这里按顺序往下找,使用找到的第一个文件。前面的目录中优先使用。 os.path.join(BASE_DIR, 'static2'), ]
<link rel="stylesheet" href="/static/css/login.css"> # 别名开头 链接使用,路径从跟开始
按照STATICFILES_DIRS列表的顺序进行查找。
我的理解是,django框架中,函数render首页文件,也会将静态文件发送到浏览器上,然后浏览器上根据这些文件就能完整展示页面的样式。
修改样式等内容后,防止缓存对调试产生影响,勾选不使用缓存
有些使用的网上别人写好的,将路径修改正确,举个栗子如果背景图没有,在index.html中也没有看到哪里使用的背景图,那么可能在别处引用了。这里的案例是在一个css文件中,可以在其它文件中ctrl+f查找这个背景图的名字,将这个背景图的src改为当前的正确路径,背景图就出来了。
如果引入静态文件目录中的文件,src必须是别名,而不是目录名字。否则控制台报错找不到资源。
即使三个图片在三个不同的设置的静态文件目录中,但是引入时都用别名开头,那么才能正确使用资源。
按照STATICFILES_DIRS列表的顺序进行查找。
2.简单的登录的实例
form表单提交数据注意的问题:
1. 提交的地址action="" 请求的方式 method="post"
2. 所有的input框有name属性
3. 有一个input框的type="submit" 或者 有一个button
提交POST请求,把settings中MIDDLEWARE的'django.middleware.csrf.CsrfViewMiddleware'注释掉
这里写了用户名密码,点击登录之后应该登录才对,这里只是这个页面刷新了一下:地址栏也多了个问号,这是发送了一个get请求
<input type="text" id="inputEmail" class="form-control" placeholder="用户名" required="" autofocus="">
required=''''表示这一个必填
1. 提交的地址action="" 请求的方式 method="post",默认是get请求,提交到当前的地址,那么不用写地址
2. 所有的input框有name属性,这样可以取form表单中的键值对
3. 有一个input框的type="submit" 或者 有一个button,作为提价用。
<html lang="en"> <head> <meta charset="utf-8"> <title>魔降风云变</title> <link href="https://cdn.bootcss.com/bootstrap/3.3.7/css/bootstrap.min.css" rel="stylesheet"> <link href="/static/css/signin.css" rel="stylesheet"> </head> <body> <div class="container"> <form class="form-signin" action="" method="post" > <h2 class="form-signin-heading">请登录:</h2> <label for="inputEmail" class="sr-only">Email address</label> <input type="text" id="inputEmail" class="form-control" placeholder="用户名" required="" autofocus="" name="username"> <label for="inputPassword" class="sr-only">Password</label> <input type="password" id="inputPassword" class="form-control" placeholder="密码" required="" name="passwd"> <div class="checkbox"> <label> <input type="checkbox" value="remember-me"> 记住密码 </label> </div> <button class="btn btn-lg btn-primary btn-block" type="submit" name="submit">登录</button > </form> </div> <!-- /container --> <!-- IE10 viewport hack for Surface/desktop Windows 8 bug --> <script src="../../assets/js/ie10-viewport-bug-workaround.js"></script> </body> </html>
然后写入信息点击提交,提交之后显示403禁止
这个的原因是django的css校验。暂时不用管,进入settings中将中间件中的关于csrf的注释掉。
然后再点击登录,就会刷新登录页面
因为函数里面么有区分,无论post还是get请求都返回的这个页面
实际应该是如果是post请求,就返回的是别的东西了。
那么打印一下request是什么:
def login(request): print(request) return render(request,'login.html') --------------结果: <WSGIRequest: POST '/login/'> #当我登录提交的时候是post,一个类 <WSGIRequest: GET '/login/'> #当我登录的时候是get
<WSGIRequest: GET '/login/'> <class 'django.core.handlers.wsgi.WSGIRequest'>
那么在函数中根据浏览器的请求方式,返回不同的内容
from django.shortcuts import render def login(request): if request.method=='get': return render(request, 'login.html') else: print(request.method,type(request.method)) #GET <class 'str'>
如下报错是没有返回对象 The view Django02.urls.login didn't return an HttpResponse object. It returned None instead.
ValueError at /login/ The view Django02.urls.login didn't return an HttpResponse object. It returned None instead. Request Method: GET Request URL: http://127.0.0.1:8000/login/ Django Version: 1.11.21 Exception Type: ValueError Exception Value: The view Django02.urls.login didn't return an HttpResponse object. It returned None instead. Exception Location: C:\python3\lib\site-packages\django\core\handlers\base.py in _get_response, line 198 Python Executable: C:\python3\python3.exe Python Version: 3.6.8 Python Path: ['C:\\mcw\\Django02', 'C:\\mcw\\Django02', 'C:\\python3\\python36.zip', 'C:\\python3\\DLLs', 'C:\\python3\\lib', 'C:\\python3', 'C:\\python3\\lib\\site-packages', 'C:\\软件安装\\PyCharm 2018.3.5\\helpers\\pycharm_matplotlib_backend'] Server time: Wed, 12 Jun 2019 08:57:00 +0000 Traceback Switch to copy-and-paste view C:\python3\lib\site-packages\django\core\handlers\exception.py in inner response = get_response(request) ... ▶ Local vars C:\python3\lib\site-packages\django\core\handlers\base.py in _get_response "returned None instead." % (callback.__module__, view_name) ... ▶ Local vars Request information USER AnonymousUser GET No GET data POST No POST data FILES No FILES data COOKIES No cookie data META Variable Value ALLUSERSPROFILE 'C:\\ProgramData' APPDATA 'C:\\Users\\Administrator\\AppData\\Roaming' COMMONPROGRAMFILES 'C:\\Program Files (x86)\\Common Files' COMMONPROGRAMFILES(X86) 'C:\\Program Files (x86)\\Common Files' COMMONPROGRAMW6432 'C:\\Program Files\\Common Files' COMPUTERNAME 'PC-20190328RVNA' COMSPEC 'C:\\Windows\\system32\\cmd.exe' CONTENT_LENGTH '' CONTENT_TYPE 'text/plain' DJANGO_SETTINGS_MODULE 'Django02.settings' FP_NO_HOST_CHECK 'NO' GATEWAY_INTERFACE 'CGI/1.1' HOMEDRIVE 'C:' HOMEPATH '\\Users\\Administrator' HTTP_ACCEPT 'text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,image/apng,*/*;q=0.8,application/signed-exchange;v=b3' HTTP_ACCEPT_ENCODING 'gzip, deflate, br' HTTP_ACCEPT_LANGUAGE 'zh-CN,zh;q=0.9' HTTP_CACHE_CONTROL 'no-cache' HTTP_CONNECTION 'keep-alive' HTTP_HOST '127.0.0.1:8000' HTTP_PRAGMA 'no-cache' HTTP_UPGRADE_INSECURE_REQUESTS '1' HTTP_USER_AGENT ('Mozilla/5.0 (Windows NT 6.1; Win64; x64) AppleWebKit/537.36 (KHTML, like ' 'Gecko) Chrome/74.0.3729.169 Safari/537.36') LOCALAPPDATA 'C:\\Users\\Administrator\\AppData\\Local' LOGONSERVER '\\\\PC-20190328RVNA' NUMBER_OF_PROCESSORS '4' OS 'Windows_NT' PATH 'C:\\Windows\\system32;C:\\Windows;C:\\Windows\\System32\\Wbem;C:\\Windows\\System32\\WindowsPowerShell\\v1.0\\;C:\\软件安装\\Git\\cmd;C:\\mysql\\mysql-5.6.44-winx64\\bin;C:\\python3\\Scripts\\;C:\\python3\\' PATHEXT '.COM;.EXE;.BAT;.CMD;.VBS;.VBE;.JS;.JSE;.WSF;.WSH;.MSC' PATH_INFO '/login/' PROCESSOR_ARCHITECTURE 'x86' PROCESSOR_ARCHITEW6432 'AMD64' PROCESSOR_IDENTIFIER 'Intel64 Family 6 Model 58 Stepping 9, GenuineIntel' PROCESSOR_LEVEL '6' PROCESSOR_REVISION '3a09' PROGRAMDATA 'C:\\ProgramData' PROGRAMFILES 'C:\\Program Files (x86)' PROGRAMFILES(X86) 'C:\\Program Files (x86)' PROGRAMW6432 'C:\\Program Files' PSMODULEPATH 'C:\\Windows\\system32\\WindowsPowerShell\\v1.0\\Modules\\' PUBLIC 'C:\\Users\\Public' PYCHARM_HOSTED '1' PYCHARM_MATPLOTLIB_PORT '57596' PYTHONIOENCODING 'UTF-8' PYTHONPATH ('C:\\mcw\\Django02;C:\\软件安装\\PyCharm ' '2018.3.5\\helpers\\pycharm_matplotlib_backend') PYTHONUNBUFFERED '1' QUERY_STRING '' REMOTE_ADDR '127.0.0.1' REMOTE_HOST '' REQUEST_METHOD 'GET' RUN_MAIN 'true' SCRIPT_NAME '' SERVER_NAME 'PC-20190328RVNA' SERVER_PORT '8000' SERVER_PROTOCOL 'HTTP/1.1' SERVER_SOFTWARE 'WSGIServer/0.2' SESSIONNAME 'Console' SYSTEMDRIVE 'C:' SYSTEMROOT 'C:\\Windows' TEMP 'C:\\Users\\ADMINI~1\\AppData\\Local\\Temp' TMP 'C:\\Users\\ADMINI~1\\AppData\\Local\\Temp' USERDOMAIN 'PC-20190328RVNA' USERNAME 'Administrator' USERPROFILE 'C:\\Users\\Administrator' WINDIR 'C:\\Windows' WINDOWS_TRACING_FLAGS '3' WINDOWS_TRACING_LOGFILE 'C:\\BVTBin\\Tests\\installpackage\\csilogfile.log' wsgi.errors <_io.TextIOWrapper name='<stderr>' mode='w' encoding='UTF-8'> wsgi.file_wrapper '' wsgi.input <_io.BufferedReader name=580> wsgi.multiprocess False wsgi.multithread True wsgi.run_once False wsgi.url_scheme 'http' wsgi.version (1, 0) Settings Using settings module Django02.settings Setting Value ABSOLUTE_URL_OVERRIDES {} ADMINS [] ALLOWED_HOSTS [] APPEND_SLASH True AUTHENTICATION_BACKENDS ['django.contrib.auth.backends.ModelBackend'] AUTH_PASSWORD_VALIDATORS '********************' AUTH_USER_MODEL 'auth.User' BASE_DIR 'C:\\mcw\\Django02' CACHES {'default': {'BACKEND': 'django.core.cache.backends.locmem.LocMemCache'}} CACHE_MIDDLEWARE_ALIAS 'default' CACHE_MIDDLEWARE_KEY_PREFIX '********************' CACHE_MIDDLEWARE_SECONDS 600 CSRF_COOKIE_AGE 31449600 CSRF_COOKIE_DOMAIN None CSRF_COOKIE_HTTPONLY False CSRF_COOKIE_NAME 'csrftoken' CSRF_COOKIE_PATH '/' CSRF_COOKIE_SECURE False CSRF_FAILURE_VIEW 'django.views.csrf.csrf_failure' CSRF_HEADER_NAME 'HTTP_X_CSRFTOKEN' CSRF_TRUSTED_ORIGINS [] CSRF_USE_SESSIONS False DATABASES {'default': {'ATOMIC_REQUESTS': False, 'AUTOCOMMIT': True, 'CONN_MAX_AGE': 0, 'ENGINE': 'django.db.backends.sqlite3', 'HOST': '', 'NAME': 'C:\\mcw\\Django02\\db.sqlite3', 'OPTIONS': {}, 'PASSWORD': '********************', 'PORT': '', 'TEST': {'CHARSET': None, 'COLLATION': None, 'MIRROR': None, 'NAME': None}, 'TIME_ZONE': None, 'USER': ''}} DATABASE_ROUTERS [] DATA_UPLOAD_MAX_MEMORY_SIZE 2621440 DATA_UPLOAD_MAX_NUMBER_FIELDS 1000 DATETIME_FORMAT 'N j, Y, P' DATETIME_INPUT_FORMATS ['%Y-%m-%d %H:%M:%S', '%Y-%m-%d %H:%M:%S.%f', '%Y-%m-%d %H:%M', '%Y-%m-%d', '%m/%d/%Y %H:%M:%S', '%m/%d/%Y %H:%M:%S.%f', '%m/%d/%Y %H:%M', '%m/%d/%Y', '%m/%d/%y %H:%M:%S', '%m/%d/%y %H:%M:%S.%f', '%m/%d/%y %H:%M', '%m/%d/%y'] DATE_FORMAT 'N j, Y' DATE_INPUT_FORMATS ['%Y-%m-%d', '%m/%d/%Y', '%m/%d/%y', '%b %d %Y', '%b %d, %Y', '%d %b %Y', '%d %b, %Y', '%B %d %Y', '%B %d, %Y', '%d %B %Y', '%d %B, %Y'] DEBUG True DEBUG_PROPAGATE_EXCEPTIONS False DECIMAL_SEPARATOR '.' DEFAULT_CHARSET 'utf-8' DEFAULT_CONTENT_TYPE 'text/html' DEFAULT_EXCEPTION_REPORTER_FILTER 'django.views.debug.SafeExceptionReporterFilter' DEFAULT_FILE_STORAGE 'django.core.files.storage.FileSystemStorage' DEFAULT_FROM_EMAIL 'webmaster@localhost' DEFAULT_INDEX_TABLESPACE '' DEFAULT_TABLESPACE '' DISALLOWED_USER_AGENTS [] EMAIL_BACKEND 'django.core.mail.backends.smtp.EmailBackend' EMAIL_HOST 'localhost' EMAIL_HOST_PASSWORD '********************' EMAIL_HOST_USER '' EMAIL_PORT 25 EMAIL_SSL_CERTFILE None EMAIL_SSL_KEYFILE '********************' EMAIL_SUBJECT_PREFIX '[Django] ' EMAIL_TIMEOUT None EMAIL_USE_LOCALTIME False EMAIL_USE_SSL False EMAIL_USE_TLS False FILE_CHARSET 'utf-8' FILE_UPLOAD_DIRECTORY_PERMISSIONS None FILE_UPLOAD_HANDLERS ['django.core.files.uploadhandler.MemoryFileUploadHandler', 'django.core.files.uploadhandler.TemporaryFileUploadHandler'] FILE_UPLOAD_MAX_MEMORY_SIZE 2621440 FILE_UPLOAD_PERMISSIONS None FILE_UPLOAD_TEMP_DIR None FIRST_DAY_OF_WEEK 0 FIXTURE_DIRS [] FORCE_SCRIPT_NAME None FORMAT_MODULE_PATH None FORM_RENDERER 'django.forms.renderers.DjangoTemplates' IGNORABLE_404_URLS [] INSTALLED_APPS ['django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles'] INTERNAL_IPS [] LANGUAGES [('af', 'Afrikaans'), ('ar', 'Arabic'), ('ast', 'Asturian'), ('az', 'Azerbaijani'), ('bg', 'Bulgarian'), ('be', 'Belarusian'), ('bn', 'Bengali'), ('br', 'Breton'), ('bs', 'Bosnian'), ('ca', 'Catalan'), ('cs', 'Czech'), ('cy', 'Welsh'), ('da', 'Danish'), ('de', 'German'), ('dsb', 'Lower Sorbian'), ('el', 'Greek'), ('en', 'English'), ('en-au', 'Australian English'), ('en-gb', 'British English'), ('eo', 'Esperanto'), ('es', 'Spanish'), ('es-ar', 'Argentinian Spanish'), ('es-co', 'Colombian Spanish'), ('es-mx', 'Mexican Spanish'), ('es-ni', 'Nicaraguan Spanish'), ('es-ve', 'Venezuelan Spanish'), ('et', 'Estonian'), ('eu', 'Basque'), ('fa', 'Persian'), ('fi', 'Finnish'), ('fr', 'French'), ('fy', 'Frisian'), ('ga', 'Irish'), ('gd', 'Scottish Gaelic'), ('gl', 'Galician'), ('he', 'Hebrew'), ('hi', 'Hindi'), ('hr', 'Croatian'), ('hsb', 'Upper Sorbian'), ('hu', 'Hungarian'), ('ia', 'Interlingua'), ('id', 'Indonesian'), ('io', 'Ido'), ('is', 'Icelandic'), ('it', 'Italian'), ('ja', 'Japanese'), ('ka', 'Georgian'), ('kk', 'Kazakh'), ('km', 'Khmer'), ('kn', 'Kannada'), ('ko', 'Korean'), ('lb', 'Luxembourgish'), ('lt', 'Lithuanian'), ('lv', 'Latvian'), ('mk', 'Macedonian'), ('ml', 'Malayalam'), ('mn', 'Mongolian'), ('mr', 'Marathi'), ('my', 'Burmese'), ('nb', 'Norwegian Bokmål'), ('ne', 'Nepali'), ('nl', 'Dutch'), ('nn', 'Norwegian Nynorsk'), ('os', 'Ossetic'), ('pa', 'Punjabi'), ('pl', 'Polish'), ('pt', 'Portuguese'), ('pt-br', 'Brazilian Portuguese'), ('ro', 'Romanian'), ('ru', 'Russian'), ('sk', 'Slovak'), ('sl', 'Slovenian'), ('sq', 'Albanian'), ('sr', 'Serbian'), ('sr-latn', 'Serbian Latin'), ('sv', 'Swedish'), ('sw', 'Swahili'), ('ta', 'Tamil'), ('te', 'Telugu'), ('th', 'Thai'), ('tr', 'Turkish'), ('tt', 'Tatar'), ('udm', 'Udmurt'), ('uk', 'Ukrainian'), ('ur', 'Urdu'), ('vi', 'Vietnamese'), ('zh-hans', 'Simplified Chinese'), ('zh-hant', 'Traditional Chinese')] LANGUAGES_BIDI ['he', 'ar', 'fa', 'ur'] LANGUAGE_CODE 'en-us' LANGUAGE_COOKIE_AGE None LANGUAGE_COOKIE_DOMAIN None LANGUAGE_COOKIE_NAME 'django_language' LANGUAGE_COOKIE_PATH '/' LOCALE_PATHS [] LOGGING {} LOGGING_CONFIG 'logging.config.dictConfig' LOGIN_REDIRECT_URL '/accounts/profile/' LOGIN_URL '/accounts/login/' LOGOUT_REDIRECT_URL None MANAGERS [] MEDIA_ROOT '' MEDIA_URL '' MESSAGE_STORAGE 'django.contrib.messages.storage.fallback.FallbackStorage' MIDDLEWARE ['django.middleware.security.SecurityMiddleware', 'django.contrib.sessions.middleware.SessionMiddleware', 'django.middleware.common.CommonMiddleware', 'django.contrib.auth.middleware.AuthenticationMiddleware', 'django.contrib.messages.middleware.MessageMiddleware', 'django.middleware.clickjacking.XFrameOptionsMiddleware'] MIDDLEWARE_CLASSES ['django.middleware.common.CommonMiddleware', 'django.middleware.csrf.CsrfViewMiddleware'] MIGRATION_MODULES {} MONTH_DAY_FORMAT 'F j' NUMBER_GROUPING 0 PASSWORD_HASHERS '********************' PASSWORD_RESET_TIMEOUT_DAYS '********************' PREPEND_WWW False ROOT_URLCONF 'Django02.urls' SECRET_KEY '********************' SECURE_BROWSER_XSS_FILTER False SECURE_CONTENT_TYPE_NOSNIFF False SECURE_HSTS_INCLUDE_SUBDOMAINS False SECURE_HSTS_PRELOAD False SECURE_HSTS_SECONDS 0 SECURE_PROXY_SSL_HEADER None SECURE_REDIRECT_EXEMPT [] SECURE_SSL_HOST None SECURE_SSL_REDIRECT False SERVER_EMAIL 'root@localhost' SESSION_CACHE_ALIAS 'default' SESSION_COOKIE_AGE 1209600 SESSION_COOKIE_DOMAIN None SESSION_COOKIE_HTTPONLY True SESSION_COOKIE_NAME 'sessionid' SESSION_COOKIE_PATH '/' SESSION_COOKIE_SECURE False SESSION_ENGINE 'django.contrib.sessions.backends.db' SESSION_EXPIRE_AT_BROWSER_CLOSE False SESSION_FILE_PATH None SESSION_SAVE_EVERY_REQUEST False SESSION_SERIALIZER 'django.contrib.sessions.serializers.JSONSerializer' SETTINGS_MODULE 'Django02.settings' SHORT_DATETIME_FORMAT 'm/d/Y P' SHORT_DATE_FORMAT 'm/d/Y' SIGNING_BACKEND 'django.core.signing.TimestampSigner' SILENCED_SYSTEM_CHECKS [] STATICFILES_DIRS ['C:\\mcw\\Django02\\static1', 'C:\\mcw\\Django02\\static', 'C:\\mcw\\Django02\\static2'] STATICFILES_FINDERS ['django.contrib.staticfiles.finders.FileSystemFinder', 'django.contrib.staticfiles.finders.AppDirectoriesFinder'] STATICFILES_STORAGE 'django.contrib.staticfiles.storage.StaticFilesStorage' STATIC_ROOT None STATIC_URL '/static/' TEMPLATES [{'APP_DIRS': True, 'BACKEND': 'django.template.backends.django.DjangoTemplates', 'DIRS': ['C:\\mcw\\Django02\\templates'], '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']}}] TEST_NON_SERIALIZED_APPS [] TEST_RUNNER 'django.test.runner.DiscoverRunner' THOUSAND_SEPARATOR ',' TIME_FORMAT 'P' TIME_INPUT_FORMATS ['%H:%M:%S', '%H:%M:%S.%f', '%H:%M'] TIME_ZONE 'UTC' USE_ETAGS False USE_I18N True USE_L10N True USE_THOUSAND_SEPARATOR False USE_TZ True USE_X_FORWARDED_HOST False USE_X_FORWARDED_PORT False WSGI_APPLICATION 'Django02.wsgi.application' X_FRAME_OPTIONS 'SAMEORIGIN' YEAR_MONTH_FORMAT 'F Y' You're seeing this error because you have DEBUG = True in your Django settings file. Change that to False, and Django will display a standard page generated by the handler for this status code.
如果判断请求方式是GET,否则打印post的,那么报错:
from django.shortcuts import render def login(request): if request.method=='get': return render(request, 'login.html') else: print(request.post)
'WSGIRequest' object has no attribute 'post'
将小写改成大小的get就能get出来东西了。
但是有没有判断请求是POST,都是打印请求.POST,这样报错,么有这个属性。 'WSGIRequest' object has no attribute 'post' ,这里写错了,请求.POST写成了请求.post,没有这个属性
改写成大写就是这个报错:
from django.shortcuts import render def login(request): if request.method=='GET': return render(request, 'login.html') elif request.method=='POST': print(request.POST) #<QueryDict: {'username': ['小马过河'], 'passwd': ['111111'], 'submit': ['']}>,类似字典也可以这样取,这样获取到了post请求的键值对
没有返回对象:
The view Django02.urls.login didn't return an HttpResponse object. It returned None instead.
下面的登录逻辑才是符合实际的逻辑:
from django.shortcuts import render,redirect def login(request): if request.method=='POST': username=request.POST['username'] passwd=request.POST['passwd'] if username=='小马过河' and passwd=='111111': return redirect(request, 'index.html') return render(request, 'login.html')
逻辑符合了,登录满足条件时由于没有或没有找到index.html报错;首先是我redirect写错了,其次是我也没发现啥问题呢。
Reverse for '<WSGIRequest: POST '/login/'>' not found. '<WSGIRequest: POST '/login/'>' is not a valid view function or pattern name.
那么将重定向改成百度网址试试:
def login(request): if request.method=='POST': username=request.POST['username'] passwd=request.POST['passwd'] if username=='小马过河' and passwd=='111111': return redirect('www.baidu.com') return render(request, 'login.html')
报错原因是,没有写https://,直接在当前url login下拼接的。
这次成功跳转到了百度页面,代码如下
def login(request): if request.method=='POST': username=request.POST['username'] passwd=request.POST['passwd'] if username=='小马过河' and passwd=='111111': return redirect('https://www.baidu.com') return render(request, 'login.html')
代码如下;
def login(request): if request.method=='POST': username=request.POST['username'] passwd=request.POST['passwd'] if username=='小马过河' and passwd=='111111': return redirect('/index/') return render(request, 'login.html') def index(request): return render(request,'index.html') urlpatterns = [ url(r'^admin/', admin.site.urls), url(r'^login/', login), ]
满足条件,重定向到index,重定向写的是外部url或者是自己项目的urlpatterns中路由的字符串,这里index没有在路由中定义,所以找不到本地的页面;如果是外界的链接地址,redirect方法之后它会直接跳转
302从login跳转到别处的实现
定位到index,重定向似乎就是服务器返回一个location,然后浏览器根据location再次get请求这个地址的函数
3.app
将函数写在url里面,函数越来越多,需要将函数分开在不同的目录,这就需要创建app。
创建APP
3.1命令行
python manage.py startapp app名称 #然后生成app目录
3.2、pycharm工具
tools ——》 run manage.py task ——》 startapp app名称
由于app注册了两遍,所以这里点击报错了。
直接startapp app名称 生成新的app目录
3.3、也可以在创建django项目时创建app。
它会自动生成这个app并注册app
注册APP
```python
INSTALLED_APPS = [
...
'app01',
'app01.apps.App01Config', # 推荐写法
]
```
setting中安装apps,Apps01Config是个类
将之前在url.py中写的函数放到新建的app01中的views.py中,并且将这个模块导入url.py文件。这样就可以在app中写函数,在url.py中使用函数了。
4、ORM
推荐原理学习链接:https://www.cnblogs.com/maple-shaw/p/9323320.html
views.py中的函数判断用户名和密码,是用数据库查询的数据进行判断。因此需要连接数据库查询:
4.1、Django中使用MySQL数据库的流程
1.创建一个MySQL数据库。
django默认创建的一个数据库,setting中这样配置的。
2.在settings中配置,Django连接MySQL数据库:
DATABASES = {
'default': {
'ENGINE': 'django.db.backends.mysql', # 引擎
'NAME': 'djangotest', # 数据库名称
'HOST': '127.0.0.1', # ip地址
'PORT':3306, # 端口
'USER':'root', # 用户
'PASSWORD':'123' # 密码
}
修改引擎为mysql,其它的都加上。这里有数据库的密码,因此项目不能随便就上传到GitHub,这样暴露了数据库,别人能连接数据库做操作的。
修改之后报错:
django.core.exceptions.ImproperlyConfigured: Error loading MySQLdb module: No module named 'MySQLdb'.
Did you install mysqlclient or MySQL-python?
mysqldb模块只支持Python2,
3.使用pymysql代替MySQLdb;在与settings同级目录下的 init文件中写:
在setting中可以的。
import pymysql
pymysql.install_as_MySQLdb()
刚刚导入不了pymysql,查看pycharm的setting中没有这个模块。重新安装了。似乎不能用我之前想的那个目录的pymysql。
4.创建表(在app下的models.py中写类):
from django.db import models
class User(models.Model):
username = models.CharField(max_length=32) # username varchar(32)
password = models.CharField(max_length=32) # username varchar(32)
写上用户密码,下载文件,java写的
测试数据库连接成功
如果密码错误:
不知为啥,第一次创建表是这样的。
5.执行数据库迁移的命令
python manage.py makemigrations # 检测每个注册app下的model.py 记录model的变更记录
python manage.py migrate # 同步变更记录到数据库中
没有注册不能记录变更记录:No changes detected
注册app名字写错了:
"'%s' must supply a name attribute." % entry)
django.core.exceptions.ImproperlyConfigured: 'app01.apps.AppConfig' must supply a name attribute.
正确注册之后就可以了
同步变更记录到数据库中:1处生成的表是app名字_表。2处是jango生成的表,3处可以执行sql语句
变更记录是收集到下面这里了。
下面表中有操作的记录:
1处执行成功,2处表中没有数据。原因:3处settings中没有配置自己想要的mysql数据库。settings很多个配置内容,有s,复数。
测试报错之一:
解决方法;
4.2、添加数据
提交到数据库中:
没有写uri,显示出所有能拼接的匹配路径
url中写了一个路径,views中写了个函数,不需要重启项目,但是配置文件的修改必须重启项目才能生效:
from app01.models import User #或者下 from app01 import models def orm_test(request): #orm操作 ret=models.User.objects.all() #通过这个类获取所有数据记录对象 print(ret,type(ret)) return HttpResponse('ok')
打印结果; 获取到表中所有行,每行都是一个对象,在一个类似列表的数据类型中,
<QuerySet [<User: User object>, <User: User object>]> <class 'django.db.models.query.QuerySet'>
4.2、 orm操作
# 获取表中所有的数据 ret = models.User.objects.all() # QuerySet 对象列表 【对象】 # 获取一个对象(有且唯一) obj = models.User.objects.get(username='alex') # 获取不到或者获取到多个对象会报错 # 获取满足条件的对象 ret = models.User.objects.filter(username='alex1',password='dasb') # QuerySet 对象列表
1)使用orm通过for循环获取数据库中每行记录的各个字段值
2、通过orm获取单行数据库的各个字段
多个条件匹配数据库某行数据。
from app01 import models def orm_test(request): #orm操作 obj=models.User.objects.get(username='mcw',password='1') #通过这个类 print(obj,type(obj)) print(obj.username,obj.password) return HttpResponse('ok')
当匹配失败时,页面返回错误:
DoesNotExist at /orm_test/
User matching query does not exist.
当多个条件都匹配成功了:没问题
使用get方法获取到多个满足条件的数据表记录时:
MultipleObjectsReturned at /orm_test/
get() returned more than one User -- it returned 2!
def orm_test(request): #orm操作 obj=models.User.objects.get(username='mcw',password='111') #通过这个类 print(obj,type(obj)) print(obj.username,obj.password) return HttpResponse('ok')
get方法获取到或者获取不到都会报错
3)fillter过滤一条数据,有几条返回几条,没有匹配到返回空列表对象,前端后端都不报错
def orm_test(request): #orm操作 obj=models.User.objects.filter(username='mcw',password='1111') #通过这个类 print(obj,type(obj)) print(obj.username,obj.password) return HttpResponse('ok')
get改成fillter就报错了。需要再补充
<QuerySet []> <class 'django.db.models.query.QuerySet'>