学习笔记6.0 Django入门创建一个钓鱼网站

太久没写博客了,2020年上半年荒废了大部分时光。从现在开始改变吧,学习django开发的知识。

用了两天的时间,终于学会了如何用pycharm开发django,会自己写一个hello world。虽然看起来不是很复杂(确实),但中途踩了许多坑,所以希望后来的人看了这篇博客可以避免我犯过的错误。

http://39.96.86.88/

准备:

pycharm专业版 + django2.1(兼容性好)

由于pycharm会创建独立的django虚拟环境,所以建议另新建一个文件夹专门放django项目

image-20200622145239424

这里的python目录下放平时练手的文件,然后在Djangoproject文件夹里放django项目。

1.创建django项目

image-20200622145833898

会问你窗口生成的问题,选择attach(附着),创建好后进入pycharm配置项 File -> settings

image-20200622150030516 image-20200622150123621

这样就能在侧边栏管理多个项目了

image-20200622150242343

2.pycharm启动django设置

先在pycharm下运行于manage.py会提示报错,然后点击edit configurations

image-20200622150415147

image-20200622150455775

这样就能用pycharm启动django项目了

初了解:

image-20200622111256718

以下一,二,三为命令行创建django教程(务必阅读),四为钓鱼网站具体创建过程

创建一个django项目

django-admin startproject webDemo        #

image-20200621191921376

创建后端函数(webApp里写html等待处理函数)

cd webDemo # 进入文件夹
django-admin startapp webApp

修改配置文件(settings.py)

1.添加webApp的信息,便于django解析

image-20200621192503564

2.注释csrf,取消跨站攻击保护

image-20200621192516065

3.允许接受所有请求

image-20200621194223340

1.运行django

python manage.py runserver 0.0.0.0:8090(端口号任意)

image-20200621194504144

image-20200621194517013

2.增加前台请求和后台处理逻辑映射,修改url.py文件

from webApp import views # 先添加包

image-20200621194804061

               第一个为:路径                  第二个为:处理方法(views里面的hello函数)

3.编辑views.py里的hello函数

image-20200621200614722

4.将html文件放置在templates目录下,js放在static文件夹目录下

html:

image-20200621200013183

image-20200621200039659

js:

image-20200621200156745

image-20200621200236258

5.其他

image-20200622104812401

写一个钓鱼网站

1.创建static文件夹(放置js,css,图片等),templates(放置html)

image-20200622105541834

image-20200622110032238

image-20200622110408042

2.创建数据库模型

image-20200622111757474

# 创建数据模型(数据库) ,保存账号密码
class User(models.Model):
    # 创建两个个字符串类型(name和password)的字段
    name = models.CharField(max_length=20)
    password = models.CharField(max_length=20)

但此时仅仅构造了创建数据库的代码,但还没有生效

image-20200622112025660

image-20200622112525325

image-20200622113030370

3.编辑视图函数(views.py) 逻辑映射

image-20200622113928109

import json
from django.shortcuts import render
from django.http import JsonResponse

'''
视图函数
    返回网站首页
'''
def index(request):
    return render(request, 'index.html', locals())

4.添加路径(urls.py)

image-20200622114742936

from django.contrib import admin
from django.urls import path
from webApp import views
# from webApp.views import index # 导入刚写的函数

urlpatterns = [
    path('admin/', admin.site.urls),
    path('index/', views.index),
    # path('hello/', views.hello),
]

这时后启动django报错了,注释掉index.html里面的第42行

image-20200622114907874

成功访问127.0.0.1/index(由于这里只有html文件,特别简陋)

image-20200622115019531

5.相同步骤配置denlu.html

views.py下

image-20200622122957611

from django.views import View # 基于类的函数
'''
基于类的视图
    登录功能
'''
class Login(View):
    def get(self, request):
        return render(request, 'denlu.html', locals())


2020/6/20

猜你喜欢

转载自blog.csdn.net/qq_43478096/article/details/106902388