• 转发 django 初探


    https://www.cnblogs.com/franknihao/p/7682914.html

      

    https://blog.csdn.net/tang_jin2015/article/details/81193943

    启动mysql 

    WampServer

    https://www.cnblogs.com/xiaoyaojinzhazhadehangcheng/p/7914644.html

    http://www.docin.com/p-184159431.html

    多调试,交互式编程体验  

     https://www.cnblogs.com/justbestone/p/8022981.html

    https://blog.csdn.net/qq_37198814/article/details/79764144

    #########sample 参考 

    https://www.cnblogs.com/franknihao/p/7682914.html

    drop database Django_Test;
    CREATE DATABASE Django_Test DEFAULT CHARSET utf8;

    GRANT ALL PRIVILEGES ON Django_Test.* TO peng@'%';

    GRANT ALL PRIVILEGES ON Django_Test.* to peng identified by 'peng';
    FLUSH PRIVILEGES;


    crtl+s 重新运行程序

    ############################################
    学习django搭建个人博客时候,采用MySQL作为后台数据库,遇到如下问题

    django.core.exceptions.ImproperlyConfigured: Error loading MySQLdb module
    .

    Did you install mysqlclient?

    解决方案:

    1. 安装pymsql

    $ pip install pymysql
    1
    2. 安装完毕,打开_init_.py,添加代码:


    $ import pymysql

    $ pymysql.install_as_MySQLdb()
    1
    ---------------------
    作者:sars231
    来源:CSDN
    原文:https://blog.csdn.net/sars231/article/details/78999084?utm_source=copy
    版权声明:本文为博主原创文章,转载请附上博文链接!


    ######################


    http://wrongwaycn.github.io/django11/topics/db/models/index.html#topics-db-models

    快速示例(Quick example)¶
    这个例子定义了一个 Person model,它有 first_name 和 last_name 两个属性:

    from django.db import models

    class Person(models.Model):
    first_name = models.CharField(max_length=30)
    last_name = models.CharField(max_length=30)
    first_name 和 last_name 是 model 的 字段(fields)。每个字段都被指定成一个类属性,每个属性都映射一个数据库的列。

    上面的 Person model 会在数据库中创建这样一张表:

    CREATE TABLE myapp_person (
    "id" serial NOT NULL PRIMARY KEY,
    "first_name" varchar(30) NOT NULL,
    "last_name" varchar(30) NOT NULL
    );
    一些技术上的注意事项:

    这个表的名称 myapp_person, 是根据 model 中的元数据自动生成的,它也可以覆写为别的名称,详见 表名称(Table names) 。
    id 字段是自动添加的,但这个行为可以被重写。详见 自增主键字段(Automatic primary key fields).
    这个例子使用 PostgreSQL 语法格式化 CREATE TABLE SQL 语句。要注意,Django 根据 配置文件(settings file) 中指定的数据库类型生成相应的 SQL 语句。

    字段(Fields)¶
    model 中不可或缺且最为重要的,就是字段集,它是一组数据库字段的列表。字段被指定为类属性。

    例如:

    class Musician(models.Model):
    first_name = models.CharField(max_length=50)
    last_name = models.CharField(max_length=50)
    instrument = models.CharField(max_length=100)

    class Album(models.Model):
    artist = models.ForeignKey(Musician)
    name = models.CharField(max_length=100)
    release_date = models.DateField()
    num_stars = models.IntegerField()


    #############################


    mysql -upeng -ppeng
    mysql> use django_test
    mysql> show tables;

    ###############

    https://docs.djangoproject.com/en/2.1/intro/tutorial02/
    https://docs.djangoproject.com/en/2.1/intro/tutorial02/
    https://www.cnblogs.com/keer2345/p/6021661.html

    $python manage.py shell

    modeles.py
    from __future__ import unicode_literals
    from django.db import models

    # Create your models here.
    class Character(models.Model):
    name = models.CharField(max_length=200)
    age = models.IntegerField()

    # def __unicode__(self):
    # return self.name

    def __str__(self):
    return self.name


    import django
    from new_app.models import Character
    Character.objects.all()
    <QuerySet []>
    c = Character(name='peter',age='70')
    c.save()
    c.id
    1L
    c.name
    'John'
    c.name = 'Vamei'
    c.save()
    Character(name='John',age='70').save()
    Character.objects.all()
    <QuerySet [<Character: 1>, <Character: 2>, <Character: 3>]>

    Character.objects.filter(id=1)

    Character.objects.get(pk=1)

    ########################20181022
    http://www.runoob.com/django/django-template.html

    点击py file.右键,running python.py.

    hello.html
    <h1>{{ label }}</h1>

    new_app/urls.py
    from .views import new_first_page
    from .views import template_show

    urlpatterns = [
    url(r'^$', new_first_page),
    url(r'^hello/', template_show),
    # url(r'^hello/', new_first_page),

    ]


    new_app/view.py
    from django.shortcuts import render

    def template_show(request):
    context = {}
    context['label'] = 'Hello World dba'
    return render(request, 'hello.html', context)

    #########20181023
    http://www.runoob.com/django/django-form.html

    11.
    serach_form.html
    <!DOCTYPE html>
    <html lang="en">
    <head>
    <meta charset="UTF-8">
    <title>菜鸟教程(runoob.com)</title>
    </head>
    <body>
    <form action="/new/search" method="get">
    <input type="text" name="q">
    <input type="submit" value="搜索">
    </form>
    </body>
    </html>


    new_appurls.py
    from django.conf.urls import url

    from .views import new_first_page
    from .views import template_show
    from . import search

    urlpatterns = [
    url(r'^$', new_first_page),
    url(r'^hello/', template_show),
    url(r'^search-form$', search.search_form),
    url(r'^search$', search.search),
    # url(r'^hello/', new_first_page),

    ]


    new_appsearch.py

    from django.http import HttpResponse
    from django.shortcuts import render_to_response

    # 表单
    def search_form(request):
    return render_to_response('search_form.html')

    # 接收请求数据
    def search(request):
    request.encoding='utf-8'
    if 'q' in request.GET:
    message = '你搜索的内容为: ' + request.GET['q']
    else:
    message = '你提交了空表单'
    return HttpResponse(message)

    22.
    new_appurls.app

    from . import search,search2

    urlpatterns = [
    url(r'^$', new_first_page),
    url(r'^hello/', template_show),
    url(r'^search-form$', search.search_form),
    url(r'^search$', search.search),
    url(r'^search-post$', search2.search_post),
    # url(r'^hello/', new_first_page),


    search2.py

    # -*- coding: utf-8 -*-

    from django.shortcuts import render
    from django.views.decorators import csrf


    # 接收POST请求数据
    def search_post(request):
    ctx = {}
    if request.POST:
    ctx['rlt'] = request.POST['q']
    return render(request, "post.html", ctx)

    post.html

    <!DOCTYPE html>
    <html>
    <head>
    <meta charset="utf-8">
    <title>菜鸟教程(runoob.com)</title>
    </head>
    <body>
    <form action="/new/search-post" method="post">
    {% csrf_token %}
    <input type="text" name="q">
    <input type="submit" value="Submit">
    </form>

    <p>{{ rlt }}</p>
    </body>
    </html>


    33.
    view.py

    from django.template.context_processors import csrf

    def process(request):
    ctx = {}
    ctx.update(csrf(request))
    if request.POST:
    name,age = request.POST.get('name'),request.POST.get('age')
    new_record = Character(name=name,age=age)
    new_record.save()
    return render(request, 'formtest.html', ctx)


    urls.py

    from .views import template_show,process
    from . import search,search2

    urlpatterns = [
    url(r'^$', new_first_page),
    url(r'^hello/', template_show),
    url(r'^search-form$', search.search_form),
    url(r'^search$', search.search),
    url(r'^search-post$', search2.search_post),
    url(r'^process$', process),
    ]

    templateformtest.html
    <!DOCTYPE html>
    <html lang="en">
    <head>
    <meta charset="UTF-8">
    <title>post</title>
    </head>
    <body>
    <form method="post" action="/new/process">
    {% csrf_token %}
    <input type="text" name="name" />
    <input type="number" name="age" />
    <input type="submit" value="Submit" />
    </form>

    <p>{{ rlt }}</p>
    <p>{{ age }}</p>
    </body>
    </html>


    44.

    https://www.cnblogs.com/chenchao1990/p/5284237.html
    https://www.cnblogs.com/btchenguang/archive/2012/08/27/2658598.html
    https://www.cnblogs.com/chenchao1990/p/5284237.html
    https://code.ziqiangxuetang.com/django/django-csrf.html
    ######
    form的定义和model类的定义很像。我们可以使用python manage.py shell来查看form类的信息。

    import django
    from new_app.views import CharacterForm
    f=CharacterForm()
    print(f)
    f = CharacterForm({'subject1': 23})
    f = CharacterForm({'name': 'ok','age': 23})
    f.is_valid()
    f.clean()

    ####
    view.py


    from django import forms

    class CharacterForm(froms.Form):
    name = forms.Charfield(max_length=200,label="Your Name")
    age = forms.IntegerField(min_value=18)

    def process(request):
    context = {}
    context.update(csrf(request))
    if request.POST:
    form = CharacterForm(request.POST)
    if form.is_valid():
    #do something with data
    cd=form.cleaned_data
    print cd
    form = CharacterForm()
    context['form'] = form
    return render(request, 'form_test.html', context)

    ###########
    https://blog.csdn.net/u013176681/article/details/73844330/
    一旦你创建一个 Template 对象,你可以用 context 来传递数据给它。 一个context 是一系列变量和它们值的集合。
    它的构造函数带有一个可选的参数: 一个字典映射变量和它们的值。 调用 Template 对象 的 render() 方法并传递 context 来填充模板:


    >>> t = Template('My name is {{ name }}.')
    >>> c = Context({'name': 'nowamagic'})
    >>> t.render(c)
    'My name is nowamagic.'
    ##########


    #########20181024

    ref https://blog.csdn.net/IamNieo/article/details/50442799

    将database加入到INSTALLED_APPS
    settings.py
    # RestfulProject/settings.py
    INSTALLED_APPS = (
    ...
    "new_app",
    ...
    )


    admin.py

    from new_app.models import Character
    admin.site.register(Character)

    ############2

    https://www.cnblogs.com/phyger/p/8035253.html


    python manage.py createsuperuser

    pengdba/123456

    models.py
    class Role(models.Model):
    role_code = models.IntegerField(primary_key=True)
    role_name = models.CharField(max_length=100)
    def __str__(self):
    return self.role_name

    class User(models.Model):
    name = models.CharField(max_length=100,primary_key=True)
    age = models.IntegerField()
    email = models.EmailField()
    role = models.ForeignKey(Role,on_delete=models.CASCADE,)
    def __str__(self):
    return '%s(%s) Mail:%s' % (self.name,self.age,self.email)

    # def __unicode__(self):
    # return self.name


    admin.py

    from django.contrib import admin

    from new_app.models import User,Role

    class UserShow(admin.ModelAdmin):
    fields = ('name','age','role') #没加email

    admin.site.register(User,UserShow)
    admin.site.register(Role)

    项目中已经设计好了表,就差把表结构给注入数据库了。
    python manage.py migrate
    python manage.py makemigrations
    python manage.py migrate


    admin.py
    class UserShow(admin.ModelAdmin):
    fieldsets = (
    ['基本信息',{
    'classes' : ('collapse',), # CSS设置
    'fields' : ('name','age')
    }],
    ['更多信息',{
    'classes' : ('collapse',),
    'fields' : ('email','role')
    }]
    )

    ##########20181026


      在进行下面的说明之前,我们先建立一个名为users的App来单独进行用户的一些操作:python manage.py startapp users

    #define in user table
    mike/oracle11

    template/login.html
    <!-- login.html -->
    <!DOCTYPE html>
    <html lang="en">
    <head>
    <meta charset="UTF-8">
    <title>{{ request.path }}</title>
    </head>
    <body>
    <form method="post" action="/users/login">
    {% csrf_token %}
    {{ form.as_p }}
    <input type="submit" value="Go!" />
    </form>

    </body>
    </html>


    users/urls.py
    from django.conf.urls import url
    from .views import user_login,auth_test,user_logout

    urlpatterns = [
    url(r'^login$', user_login),
    url(r'^auth$', auth_test),
    url(r'^logout$', user_logout),

    ]


    users/views.py
    # -*- coding: utf-8 -*-
    from __future__ import unicode_literals

    from django.shortcuts import render,redirect
    from django.template.context_processors import csrf
    from django import forms
    from django.contrib.auth import authenticate,login
    from django.http import HttpResponse
    from django.contrib.auth.decorators import login_required
    from django.contrib.auth import logout


    # Create your views here.

    class LoginForm(forms.Form):
    username = forms.CharField(max_length=100,min_length=3)
    password = forms.CharField(min_length=8,widget=forms.PasswordInput)
    email = forms.EmailField()

    def user_login(request):
    context = {}
    context.update(csrf(request))
    login_form = LoginForm()
    if request.POST:
    username = password = ''
    username = request.POST.get('username')
    password = request.POST.get('password')
    user = authenticate(username=username,password=password)
    if user is not None and user.is_active:
    login(request,user)
    return redirect('/users/auth')
    else:
    return redirect('/users/login')
    context['form'] = login_form
    return render(request,'login.html',context)

    @login_required
    def auth_test(request):
    return HttpResponse('<p>%s</p>' % request.user.get_username())

    #def auth_test(request):
    # context = {}
    # if request.user.is_authenticated:
    # return HttpResponse('<p>%s</p>' % request.user.get_username())
    # else:
    # return redirect('/user/login')


    def user_logout(request):
    logout(request)
    return redirect('/')


    testdjango/urls.py

    url(r'^users/', include('users.urls')),


    ###########20181028


    user/views


    from django.contrib.auth.forms import UserCreationForm
    from django.shortcuts import redirect,render
    from django.template.context_processors import csrf

    def user_register(request):
    if request.method == 'POST':
    form = UserCreationForm(request.POST)
    if form.is_valid():
    new_user = form.save()
    return redirect('/')

    else:
    form = UserCreationForm()
    context = {'form':form}
    context.update(csrf(request))
    return render(request, 'register.html', context)

    register.html
    <form action="" method="post">
    {% csrf_token %}
    {{ form.as_p }}
    <input type="submit" value="Submit" />
    </form>

    users/urls.py

    url(r'^register$', user_register),

  • 相关阅读:
    Servlet监听器及在线用户
    数据分页jdbc+mysql实现
    使用ajax验证用户名重复
    Mysql中的事务
    用户登录注册案例分析
    Java连接mysql数据库
    Java连接sqlite数据库
    虚拟主机TOMCAT配置
    用jquery控制表格奇偶行及活动行颜色
    JDK安装后 没有tools.jar 和dt.jar包的解决办法
  • 原文地址:https://www.cnblogs.com/feiyun8616/p/9800996.html
Copyright © 2020-2023  润新知