html
<form method="post" enctype="multipart/form-data" action="">
{% csrf_token %}
{{ uf.as_p }}# form.as_p 是上传文件的选择器
<input type="submit" value="OK"/>
</form>
views
def reg_index(request):
if request.method == 'POST':
uf = UserForm(request.POST, request.FILES)
if uf.is_valid():
uname = uf.cleaned_data['username']
hImg = uf.cleaned_data['headImg']
u = User()
u.username = uname
u.headImg = hImg
u.save()
request.session['user_info'] = uname
return render(request,'done.html')
else:
uf = UserForm()
return render(request, 'img.html', {'uf': uf})
form:
class UserForm(forms.Form):
username = forms.CharField()
headImg = forms.FileField()