django 实现

发布时间:2019-03-13 22:47:03编辑:auto阅读(1781)

    Title

    1.输入信息,在底部输出用户输入的信息(数据存储在数据库中)

    urls.py
    
    from django.contrib import admin
    from django.urls import path
    from first import views
    
    urlpatterns = [
        path('admin/', admin.site.urls),
        path('info/', views.show_info),
        path('userInfo', views.show_userInfo),
    ]
    models.py
    
    from django.db import models
    
    # Create your models here.
    
    
    class userinfo_table(models.Model):
    
        name = models.CharField(max_length=64)
        sex = models.CharField(max_length=64)
        email = models.CharField(ma
    views.py
    
    
    from django.shortcuts import render, HttpResponse
    
    from first import models
    
    # Create your views here.
    
    # import datetime
    # def show_info(request):
    # 
    #     now_time = datetime.datetime.now()
    #     request_content = request.method
    #     return render(request, 'show_info.html', {'time': now_time, 'content': request_content})
    
    # info_list = []
    def show_userInfo(request):
    
        if request.method == 'POST':
            userName = request.POST.get('name', None)  # 拿到前端用户输入的数据
            userSex = request.POST.get('sex', None)
            userEmail = request.POST.get('email', None)
    
            # userinfo = {'username': userName, 'usersex': userSex, 'useremail': userEmail}
    
            models.userinfo_table.objects.create(     # 向数据表中插入数据
                name=userName,
                sex=userSex,
                email=userEmail,
            )
    
            # 从数据库中取出数据,就相当于以键值对的方式进行存储,将多条字典数据存储在一个列表中
    
        info_list = models.userinfo_table.objects.all()
    
            # info_list.append(userinfo)
    
        return render(request, 'userInfo.html', {'info_list': info_list})
    userInfo.html
    
    <!DOCTYPE html>
    <html lang="en">
    <head>
        <meta charset="UTF-8">
        <title>Title</title>
    </head>
    <body>
        <form action="/userInfo" method="post">
            <p>姓名:<input type="text" name="name"></p>
            <p>性别:<input type="text" name="sex"></p>
            <p>邮箱:<input type="text" name="email"></p>
            <p><input type="submit" name="submit"></p>
        </form>
    
        <table border="1px">
    
            <tr>
                <td>姓名</td>
                <td>性别</td>
                <td>邮箱</td>
            </tr>
    
            {% for info in info_list %}
                <tr>
                    <td>{{ info.name }}</td>
                    <td>{{ info.sex }}</td>
                    <td>{{ info.email }}</td>
                </tr>
            {% endfor %}
    
    
        </table>
    
    
    </body>
    </html>

     2.可注册,可登录,用户登录信息存放再数据库中(django)

    urls.py
    
    from django.contrib import admin
    from django.urls import path
    from first import views
    
    urlpatterns = [
        path('admin/', admin.site.urls),
        path('info/', views.show_info),
        # path('userInfo', views.show_userInfo),
        path('login', views.login),
        path('signIn', views.signIn),
        path('firstPage', views.firstPage),
    ]
    models.py
    
    from django.db import models
    
    # Create your models here.
    
    
    # class userinfo_table(models.Model):
    # 
    #     name = models.CharField(max_length=64)
    #     sex = models.CharField(max_length=64)
    #     email = models.CharField(max_length=64)
    
    class id_and_pwd(models.Model):
    
        userId = models.CharField(max_length=64)
        userPwd = models.CharField(max_length=64)
    views.py
    
    
    from django.shortcuts import render, HttpResponse
    
    from first import models
    
    # Create your views here.
    
    import datetime
    
    def login(req):   # 登录
    
        if req.method == 'POST':
            user_id = req.POST.get('Id')
            user_pwd = req.POST.get('Pwd')
    
            # models.id_and_pwd.objects.create(
            #     userId=user_id,
            #     userPwd=user_pwd
            # )
    
            all_userInfo = models.id_and_pwd.objects.all()
    
            for info in all_userInfo:
                if user_id == info.userId and user_pwd == info.userPwd:
                    return HttpResponse('<h1>login succeed!</h1>')
    
    
        return render(req, 'login.html')
    
    
    def firstPage(req):  # 显示首页
    
        return render(req, 'firstPage.html')
    
    def signIn(req):  # 注册
    
        if req.method == "POST":
            user_id = req.POST.get('Id')
            user_pwd = req.POST.get('Pwd')
    
            models.id_and_pwd.objects.create(
                userId=user_id,
                userPwd=user_pwd
            )
    
        return render(req, 'signIn.html')
    login.html
    
    <!DOCTYPE html>
    <html lang="en">
    <head>
        <meta charset="UTF-8">
        <title>login</title>
    </head>
    <body>
        <form action='/login' method="post">
            <p>ID:<input type="text" name="Id"></p>
            <p>PASSWORD:<input type="password" name="Pwd"></p>
    
            <p><input type="submit" value="submit"></p>
        </form>
    
    </body>
    </html>
    singIn.html
    
    <!DOCTYPE html>
    <html lang="en">
    <head>
        <meta charset="UTF-8">
        <title>login</title>
    </head>
    <body>
        <form action='/signIn' method="post">
            <p>ID:<input type="text" name="Id"></p>
            <p>PASSWORD:<input type="password" name="Pwd"></p>
    
            <p><input type="submit" value="submit"></p>
        </form>
    
    </body>
    </html>
    firstPage.html
    
    <!DOCTYPE html>
    <html lang="en">
    <head>
        <meta charset="UTF-8">
        <title>firstPage</title>
    </head>
    <body>
        <h1>welcome to study kingdom</h1>
        <input type="button" value='log in' onclick="login()">
        <input type="button" value='sign in' onclick="sign_in()">
    
        <script>
            function login() {
                window.location.href = 'http://127.0.0.1:8000/login';  // 点击跳转登录页面
            }
            function sign_in(){
                window.location.href = 'http://127.0.0.1:8000/signIn';   // 点击跳转注册页面
            }
        </script>
    </body>
    </html>

     

    #   数据库操作
    
    
    def change(req):
        if req.method == 'POST':
    
            change_id = req.POST.get('id')
            change_name = req.POST.get('after_name')
            change_email = req.POST.get('after_email')
    
            change_obj = models.UserInfo.objects.get(id=change_id)
            change_obj.name = change_name
            change_obj.email = change_email
            change_obj.save()
    
            return redirect('/userInfoMode/')
        edit_id = req.GET.get('id')
        if edit_id:
            edit_obj = models.UserInfo.objects.get(id=edit_id)
    
            return render(req, 'change.html', {'data_obj': edit_obj})

     3.数据库中多对多数据的查询方式

    {% for book_info in book_obj %}
                <tr>
                    <td>{{ book_info.title }}</td>
                    {% for author in book_info.author.all %}
                        <td>{{ author.name }}</td>
                    {% endfor %}
    
                </tr>
    {% endfor %}

     4.单表查询的下划线的一些方法

    # 数据表结构
    class Book(models.Model):
        id = models.AutoField(primary_key=True)
        title = models.CharField(max_length=64)
        create_date = models.DateField(auto_now_add=True)
        author = models.ManyToManyField(to='Author', related_name='books')
    
    
        models.Book.objects.filter(id__gt=xx, id__lt=xx)
        models.Book.objects.filter(id__in=[1, 2, 3, 4])
        models.Book.objects.filter(id__range=[1, 5])
        models.Book.objects.filter(title__contains='xx')           # 字段中含有该字符串的
        models.Book.objects.filter(title__icontains='xx')         # 字段中含有该字符串的,不区分大小写
        models.Book.objects.filter(title__startswith='xx')        # 由该字符串开始的字段
        models.Book.objects.filter(title__endswith='xx')      # 由该字符串结束的字段
        models.Book.objects.filter(create_date__day='xx')           # 确定是某一天
        models.Book.objects.filter(create_date__month='xx')       # 确定是某一月
        models.Book.objects.filter(create_date__year='xx')      # 确定是某一年

     5.当使用orm语句执行数据库操作的时候,显示相对应的sql语句

    # setting配置
    LOGGING = {
        'version': 1,
        'disable_existing': False,
        'handlers': {
            'console': {
                'level': 'DEBUG',
                'class': 'logging.StreamHandler'
            }
        },
        'loggers': {
            'django.db.backends': {
                'handlers': ['console'],
                'propagate': True,
                'level': 'DEBUG'
            }
        }
    }
    
    
    # django代码
    import os
    import sys
    
    if __name__ == '__main__':
        os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'fatal_version.settings')
        import django
        django.setup()
    
        from app01 import models
    
        ret = models.UserInfo.objects.all()
        print(ret)

     5.ajax计算器

    //   .html
    
    <!DOCTYPE html>
    <html lang="en">
    <head>
        <meta charset="UTF-8">
        <title>Title</title>
        {#    <meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=1, user-scalable=no">#}
        {#    <link rel="stylesheet" href="/static/bootstrap/css/bootstrap.min.css">#}
        {#    <link rel="stylesheet" href="https://cdn.bootcss.com/font-awesome/4.7.0/css/font-awesome.min.css">#}
    </head>
    <body>
        <input type="text" name="first_num" id="num1">+
        <input type="text" name="second_num" id="num2">=
        <input type="text" name="result" id="answer" value={{ res }}>
        <input type="button" id="compute" value="submit">
    <script src="/static/jquery-3.3.1.min.js"></script>
    {#<script src="/static/bootstrap/js/bootstrap.min.js"></script>#}
    <script>
        $('#compute').on('click', function(){
            $.ajax({
                url: '/calculator/',
                type: 'POST',
                data: {"first_num": $('#num1').val(), "second_num": $('#num2').val()},
                success: function(content){
                    $('#answer').val(content);
                }
            })
        })
    </script>
    </body>
    </html>
    #  views.py
    
    
    # ajax提交(计算器)
    def calculator(req):
        if req.method == 'POST':
            first_num = int(req.POST.get('first_num', None))
            second_num = int(req.POST.get('second_num', None))
            result = first_num + second_num
            return HttpResponse(result)
        return render(req, 'calculator.html')

     6.django数据库自定义表名

    # models.py
        class Meta:
            db_table = "xxxx"  # 自定义表名

     

关键字