This should be the last learning module for Django. And then you need to go into the project to practice.
There are two ways to upload a Django file, one is the traditional IO-flow based operation, and one is encapsulated as an object-based operation.
But either way, you need to first create a directory of uploaded files,
Operation based on Io flow
The configuration in the URLs, based on the submission of the form in learning Notes (v) blog/param/(? P<ID>\D{2})
The modified post method is as follows:
Def post (req): If Req.method = ' post ': form = UserForm (req. Post,req. FILES) if Form.is_valid (): Print Form.cleaned_data & nbsp print form.cleaned_data[' name '] Print form.cl eaned_data[' Userimag '].name print form.cleaned_data[' Userimag '].size & nbsp #way 1 s = form.cleaned_data[' Userimag '].read () &nbs P fb = File ('./djangotest/upload/' +form.cleaned_data[' userimag '].name, ' WB ') & nbsp Fb.write (s) Fb.close () & nbsp return HttpResponse (' OK ') ELSE: return HttpResponse (' Failed ') else: form = userform () return render_to_response (' param.html ', {' form ': Form})
The corresponding param.html are as follows:
<! DOCTYPE html>
Second, object-based storage:
First, in the configuration settings file
Media_root = './djangotest/'
The goal is to let the path of subsequent uploads be relative to the path of the project itself, without having to write dead
Add a new models:
Class Files (models. Model):
name = models. Charfield (max_length=300)
f = models. Filefield (upload_to= ' upload/')
def __unicode__ (self): return
Self.name
Synchronizing databases
To modify the Post method:
Def post (req): If Req.method = ' post ': form = UserForm (req. Post,req. FILES) if Form.is_valid (): Print Form.cleaned_data & nbsp print form.cleaned_data[' name '] Print form.cl eaned_data[' Userimag '].name print form.cleaned_data[' Userimag '].size & nbsp #way 1 s = form.cleaned_data[' Userimag '].read () &nbs P fb = File ('./djangotest/upload/' +form.cleaned_data[' userimag '].name, ' WB ') & nbsp Fb.write (s) Fb.close () & nbsp #way2 f = Files (name=form . cleaned_data[' Userimag '].name,f=form.cleaned_data[' Userimag ']) F.save () & nbsp return HttpResponse (' OK ') else: &NBSP ; Return HttpResponse (' Failed ') else: form = userform () &NBSP ; return render_to_response (' param.html ', {' form ': Form})
The corresponding param.html are as follows:
<! DOCTYPE html>