标签:images blog style doctype conf size com write Enctype
任务描述:实现表单提交(上传文件)
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 # Create your views here. class UserForm(forms.Form): username = forms.CharField(max_length=100) headimg = forms.FileField() 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‘] print(username, headimg) # save headimg fp = open(‘upload/‘ + headimg.name, ‘wb‘) s = headimg.read() fp.write(s) fp.close() 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), ]
标签:images blog style doctype conf size com write Enctype
原文地址:http://www.cnblogs.com/jasonhaven/p/7487366.html