zoukankan      html  css  js  c++  java
  • Django表单上传

    任务描述:实现表单提交(上传文件)

    1.项目目录:

    2.源代码:

    regist.html

    <!DOCTYPE html>
    <html lang="en">
    <head>
        <meta charset="UTF-8">
        <title>regist</title>
    </head>
    <body>
    <h3>regist</h3>
    <hr>
    <form method="post" enctype="multipart/form-data">
        {% csrf_token %}
        {{uf.as_p}}
        <input type="submit" value="submit">
    </form>
    </body>
    </html>
    

    views.py

    from django.shortcuts import render
    from django import forms
    import sqlite3
    from . import models
    
    
    class UserForm(forms.Form):
    	username = forms.CharField(max_length=100)
    	headimg = forms.FileField()
    
    
    def insert(user):
    	# 连接数据保存
    	print('insert:')
    	print(user.username)
    	models.User.objects.create(username=user.username, headimg=user.headimg)
    	return True
    
    
    def regist(request):
    	context = {}
    	if request.method == 'POST':
    		uf = UserForm(request.POST, request.FILES)
    		if uf.is_valid():
    			username = uf.cleaned_data['username']
    			headimg = uf.cleaned_data['headimg']
    			user = models.User(username=username, headimg=headimg.name)
    			print(user.username)
    			# save headimg
    			fp = open('upload/' + headimg.name, 'wb')
    			s = headimg.read()
    			fp.write(s)
    			fp.close()
    			if insert(user):
    				return render(request, 'regist_ok.html', context)
    	else:
    		uf = UserForm()
    	context = {'uf': uf}
    	return render(request, 'regist.html', context)

    urls.py

    from django.conf.urls import url
    from django.contrib import admin
    from user import views
    
    urlpatterns = [
    	url(r'^admin/', admin.site.urls),
    	url(r'user/regist/', views.regist),
    ]

    3.admin管理

    from django.contrib import admin
    from . import models
    
    
    # Register your models here.
    
    class UserAdmin(admin.ModelAdmin):
    	# 设置显示的字段
    	list_display = ("username", "headimg")
    
    
    admin.site.register(models.User, UserAdmin)

    4.运行测试

  • 相关阅读:
    lwIP Memory Management
    FreeRTOS Memory Management ( IAR )
    Mastering stack and heap for system reliability
    LwIP buffer management, memory configuration options
    FreeRTOS API
    FreeRTOS Customisation -- FreeRTOSConfig.h
    FreeRTOS介绍与移植
    FreeRTOS
    LWIP轻量级TCPIP协议栈的移植
    Wifi模块的工作原理
  • 原文地址:https://www.cnblogs.com/jasonhaven/p/7487366.html
Copyright © 2011-2022 走看看