Django表单上传

Posted Jasonhaven.D

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了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.运行测试

以上是关于Django表单上传的主要内容,如果未能解决你的问题,请参考以下文章

在Django中读取使用html表单上传的Excel文件

Django保存带有图像文件问题的表单

如何从 django 中的内联表单接收上传的文件?

使用 Django 模型表单上传图像

Django 从表单上传重定向

Django:无法将上传的图像绑定到表单 ImageField()