• django 快速实现文件上传(四)


    继博客(三)实现的,

    建两个字段,username 用户存放用户名,headImg 用户存放上传文件的路径。

    重新同步数据库:

    提示:

    这个可能是之前已创建了表中的一条记录,之后模型中增加了一个非空的字段,但是原来已经存在的记录没有这个值

    >python manage.py makemigrations
    You are trying to add a non-nullable field 'price_monthly' to product without a default; we can't do that (the database needs something to populate existing rows).
    Please select a fix:
     1) Provide a one-off default now (will be set on all existing rows)
     2) Quit, and let me add a default in models.py
    Select an option:


    好像也不对,唉,放弃了,重新开个项目吧。只有有精力再看


    Django开发的基本套路

    1.创建项目与应用  

       1.django-admin.py startproject mysite2

       2.cd mysite2

       3.python manage.py startapp disk

    2.设计Model(数据库)

       同步model

       py -2 manage.py makemigrations
       py -2 
    manage.py migrate
       py -2 
    manage.py createsuperuser

    3.创建视图
       1.在setting里增加INSTALLED_APPS
       2.创建模板文件夹,添加模板
       3.配置视图
       4.设置url
       5.启动服务


    完善表单提交 

    打开mysite2/disk/templates/register.html 文件:

    复制代码
    <?xml version="1.0" encoding="UTF-8"?> 
    <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
    <html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en" lang="en">
    <head>
        <meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />
        <title></title>
    </head>
    <body>
    <h1>register</h1>
    <form method="post" enctype="multipart/form-data" >
    {{uf.as_p}}
    <input type="submit" value="ok"/>
    </form>
    </body>
    </html>

    打开mysite2/disk/views.py 文件:

    复制代码
    from django.shortcuts import render,render_to_response
    from django import forms
    from django.http import HttpResponse
    # Create your views here.
    
    class UserForm(forms.Form):
        username = forms.CharField()
        headImg = forms.FileField()
    
    def register(request):
        if request.method == "POST":
            uf = UserForm(request.POST,request.FILES)
            if uf.is_valid():
                return HttpResponse('upload ok!')
        else:
            uf = UserForm()
        return render_to_response('register.html',{'uf':uf})

    刷新页面后,提交

    打开mysite2/mysite2/settings.py文件,将下面一行代码注释:

    将数据写入数据库

    在项目的目录下,有用户提交的文件。

     


    查看sqlite数据库/进入sqlite3命令行

    1.该项目的setting

    2.进入sqlite3交互模式进行命令操作

      1、确认sqlite3是否已经安装

      cmd模式下,进入python界面(py -2),import sqlite3

      

      2、

    
    
    
  • 相关阅读:
    C#利用Web Service实现短信发送
    .net辅助工具列表
    Coding4Fun:Rob 的 Image Shrinker
    论坛系统的各种过滤
    javascript 函数定义的方式
    设计模式学习(十二)职责链模式命令模式解释器模式
    典型SQL 语句总结
    ASP.NET2.0 WebControl开发自定义DropDownList
    window.showModalDialog和window.open关闭子页面时刷新父页面
    设计模式学习(十三)迭代器模式中介者模式
  • 原文地址:https://www.cnblogs.com/mogujiang/p/6690259.html
Copyright © 2020-2023  润新知