Django创建后的基本操作

Posted pandaboy1123

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了Django创建后的基本操作相关的知识,希望对你有一定的参考价值。

1.创建Django项目做基本的配置步骤
Pycharm->new->New Project


2.基本的配置
settings.py-->STATIC_URL = \'/static/\'后面新增
STATICFILES_DIRS = (
os.path.join(BASE_DIR,\'static\'),
)


配置好后新增文件夹在项目文件夹下,命名为static
3.配置urls的新页面
1).新增语句 from django.conf.urls import url
from app01 import views
2).配置url链接
url(r\'^upload.html$\',views.upload),


4.写应用中配置的views方法
def upload(request):
#中间可以新增各种各样的逻辑判断方法
return render(request,\'upload.html\')


5.配置HTML文件

<!DOCTYPE html>
<html lang="en">
{% load staticfiles %}
<head>
    <meta charset="UTF-8">
    <title>Blog_test</title>
    <link rel="stylesheet" href="{% static \'bootstrap/css/bootstrap.css\' %}">
    <link rel="stylesheet" href="{% static \'bootstrap/js/bootstrap.js\' %}">
    <link rel="stylesheet" href="{% static \'bootstrap/fonts/glyphicons-halflings-regular.ttf\' %}">
    <link rel="stylesheet" href="{% static \'font-awesome/web-fonts-with-css/css/fontawesome-all.min.css\' %}">
    <script SRC="/static/Echarts/echarts.js"></script>
</head>
<body>
{# _______________________________________导航条__________________________________________________________#}
<nav class="navbar navbar-inverse">
  <div class="container-fluid">
    <!-- Brand and toggle get grouped for better mobile display -->
    <div class="navbar-header">
      <button type="button" class="navbar-toggle collapsed" data-toggle="collapse" data-target="#bs-example-navbar-collapse-1" aria-expanded="false">
        <span class="sr-only">Toggle navigation</span>
        <span class="icon-bar"></span>
        <span class="icon-bar"></span>
        <span class="icon-bar"></span>
      </button>
      <a class="navbar-brand" href="#">我的博客</a>
    </div>

    <!-- Collect the nav links, forms, and other content for toggling -->
    <div class="collapse navbar-collapse" id="bs-example-navbar-collapse-1">
      <ul class="nav navbar-nav">
        <li class="active"><a href="#">首页<span class="sr-only">(current)</span></a></li>
        <li><a href="#">我的随笔</a></li>
          <li><a href="#">我的文章</a></li>
          <li><a href="#">管理</a></li>
        <li class="dropdown">
          <a href="#" class="dropdown-toggle" data-toggle="dropdown" role="button" aria-haspopup="true" aria-expanded="false">统计<span class="caret"></span></a>
          <ul class="dropdown-menu">
            <li><a href="#">随笔:</a></li>
            <li><a href="#">文章:</a></li>
            <li><a href="#">评论:</a></li>
              <li><a href="#">引用:</a></li>
          </ul>
        </li>
      </ul>
      <form class="navbar-form navbar-left">
        <div class="form-group">
          <input type="text" class="form-control" placeholder="Search">
        </div>
        <button type="submit" class="btn btn-default">百度一下</button>
      </form>
      <ul class="nav navbar-nav navbar-right">
        <li><a href="#">联系我</a></li>
          <li><a href="http://127.0.0.1:8000/test.html">测--试</a></li>
        <li class="dropdown">
          <a href="#" class="dropdown-toggle" data-toggle="dropdown" role="button" aria-haspopup="true" aria-expanded="false">排行榜 <span class="caret"></span></a>
          <ul class="dropdown-menu">
            <li><a href="#">阅读排行榜</a></li>
                          <li role="separator" class="divider"></li>
            <li><a href="#">评论排行榜</a></li>
                          <li role="separator" class="divider"></li>
            <li><a href="#">推荐排行榜</a></li>
          </ul>
        </li>
          {# _____________________________________模态框(登录界面)___________________________________________________#}
          <li style="padding-top: 2%">
<!-- Button trigger modal -->
<button type="button" class="btn btn-inverse" data-toggle="modal" data-target="#myModal">
  登录
</button>
<!-- Modal -->
<div class="modal fade" id="myModal" tabindex="-1" role="dialog" aria-labelledby="myModalLabel">
  <div class="modal-dialog modal-sm" role="document">
    <div class="modal-content">
      <div class="modal-header">
        <button type="button" class="close" data-dismiss="modal" aria-label="Close"><span aria-hidden="true">&times;</span></button>
        <h4 class="modal-title" id="myModalLabel">用户登录</h4>
      </div>
        <form action="index.html" method="post" id="fm">
      <div class="modal-body">
          <p><i class="fa fa-user"><input  name="username" placeholder="用户名" type="text" style="height: 30px;width: 260px;"/></i></p>
          <p><i class="fa fa-unlock-alt"><input  name="password" placeholder="密码" type="password" style="height: 30px;width: 260px"/></i></p>
      </div>
      <div class="modal-footer">
        <button type="button" class="btn btn-default" data-dismiss="modal">关闭</button>
        <button type="submit" class="btn btn-primary" onclick="submitlogin()">登录</button>
      </div></form>
    </div>
  </div>
</div>
</li>
          {# _________________________________________________________________________________________________#}
      </ul>
    </div><!-- /.navbar-collapse -->
  </div><!-- /.container-fluid -->
</nav>
<script src="/static/js/jquery-3.3.1.min.js">
</script>
<script>
    function submitlogin() {
    $.ajax({
        url:\'index.html\',
        type:\'POST\',
        data:$(\'#fm\').serialize(),
        success:function (arg) {
            console.log(arg);
        }
    })
    }
</script>
<script src="/static/bootstrap/css/bootstrap.css"></script>
<script src="/static/bootstrap/js/bootstrap.js" type="text/javascript"></script>
</body>
</html>
index.html
from django.shortcuts import render,HttpResponse
from  Blog.models import UserInfo
# Create your views here.
def index(request):
    return render(request,\'index.html\')
def test(request):
    return render(request,\'test.html\')
def login(request):
    if request.method == \'GET\':
        return render(request,\'index.html\')
    else:
        u = request.POST.get(\'username\')
        p = request.POST.get(\'password\')
        users = UserInfo.objects.filter(username=u,password=p). \\
            values(\'nid\', \'nickname\',\'username\', \'email\',\'avatar\',).first()
        if users:
            return render(request,\'index.html\')
        else:
            return render(request,\'test.html\')
views.py
from django.db import models

# Create your models here.
class UserInfo(models.Model):
    """
    用户表
    """
    def __str__(self):
        return self.username
    nid = models.BigAutoField(primary_key=True)
    username = models.CharField(verbose_name=\'用户名\', max_length=32, unique=True)
    password = models.CharField(verbose_name=\'密码\', max_length=64)
    nickname = models.CharField(verbose_name=\'昵称\', max_length=32)
    email = models.EmailField(verbose_name=\'邮箱\', unique=True)
    avatar = models.ImageField(verbose_name=\'头像\')
models.py
"""
Django settings for MyBlog project.

Generated by \'django-admin startproject\' using Django 2.0.5.

For more information on this file, see
https://docs.djangoproject.com/en/2.0/topics/settings/

For the full list of settings and their values, see
https://docs.djangoproject.com/en/2.0/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.0/howto/deployment/checklist/

# SECURITY WARNING: keep the secret key used in production secret!
SECRET_KEY = \'tz)owazxyz+h!ysgs6=84(s__x!7zl!^+#5k-qk#iyw$nkz^+d\'

# 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\',
    \'Blog.apps.BlogConfig\',
]

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 = \'MyBlog.urls\'

TEMPLATES = [
    {
        \'BACKEND\': \'django.template.backends.django.DjangoTemplates\',
        \'DIRS\': [os.path.join(BASE_DIR, \'templates\')]
        ,
        \'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 = \'MyBlog.wsgi.application\'


# Database
# https://docs.djangoproject.com/en/2.0/ref/settings/#databases

DATABASES = {
    \'default\': {
        \'ENGINE\': \'django.db.backends.mysql\',
        \'NAME\': \'cms\',
        \'USER\': \'root\',
        \'PASSWORD\': \'123456\',
        \'HOST\': \'127.0.0.1\',
        \'PORT\': \'3306\',
    }
}


# Password validation
# https://docs.djangoproject.com/en/2.0/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.0/topics/i18n/

LANGUAGE_CODE = \'en-us\'

TIME_ZONE = \'UTC\'

USE_I18N = True

USE_L10N = True

USE_TZ = True


# Static files (CSS, JavaScript, Images)
# https://docs.djangoproject.com/en/2.0/howto/static-files/

STATIC_URL = \'/static/\'
STATICFILES_DIRS = (
    os.path.join(BASE_DIR,\'static\'),
)
settings.py

 

以上是关于Django创建后的基本操作的主要内容,如果未能解决你的问题,请参考以下文章

Sleep() 方法后的代码片段没有被执行

如何在 Django Summernote 中显示编程片段的代码块?

使用 Django 模板作为片段

Django rest_framewok框架的基本组件

MySQL+Django+Python+Pycharm开发!这才是企业级项目!非常完善

结合两个代码片段?将用户输入的 Youtube url 转换为嵌入 url,然后将 iframe src 替换为转换后的 url