-3

如何使用 Django 上传文件?

我已按照这些说明上传文件

在这里,我没有收到任何错误,但是当我提交表单时,表单中的其他详细信息已保存到数据库中。但是我上传的文件没有保存在任何地方。

/models.py/

class resmodel(models.Model):
   resume_header = models.CharField(max_length=100)
   upload_resume = models.FileField(upload_to='documents')

/forms.py/

class resmodelForm(ModelForm):
class Meta:
    model = resmodel

/views.py/

def resview(request):
if request.method == "POST":
    form = resmodelForm(request.POST, request.FILES)
    if form.is_valid():
        a = resmodel(resume_header=resume_header, upload_resume = request.FILES['upload_resume'])
        a.save()
        return render_to_response('/profile/save/success/')
else:
    form = resmodelForm()
    return render_to_response('resume.html', {'form': form})
return render_to_response('resume.html')

/resume.html/

<form action="." method="post" >{% csrf_token %}
<table border="0" align="center" cellsapcing="1" cellspadding="1">
<tr>
    <td colspan="2"><h3> Personal Information</h3></td>
</tr>
<tr>
    <td>Resume Header<sub>(250 words max)</sub></td>
    <td><input type="text" name="resume_header"></td>
</tr>

<tr>
    <td>Upload Resume<sub>(.doc/.docx, rtf, pdf, txt)</sub></td>
    <td><input type="file" name="upload_resume" ></td>
</tr>
<tr>
    <td>
        <input type="submit" value="SUBMIT">&nbsp;&nbsp;
        <input type="reset" value="RESET">
    </td>
</tr>
</table>
</form>

/urls.py/

urlpatterns = patterns('', (r'^profile/$', resview),)

/settings.py/ 在设置中我的媒体路径和网址是..

CURRENT_DIR = os.path.dirname(os.path.abspath(__file__))
MEDIA_ROOT = os.path.join(CURRENT_DIR, 'media')
MEDIA_URL = '/var/www/uploadresume/resume/media/'

这是我的代码。如果有,请纠正我的错误?

4

1 回答 1

1

你必须使用form.save()而不是手动保存它

def resview(request):
    if request.method == "POST":
        form = resmodelForm(request.POST, request.FILES)
        if form.is_valid():
            form.save()
            return render_to_response('/profile/save/success/')
    else:
        form = resmodelForm()
    return render_to_response('resume.html')

你忘了把enctype="multipart/form-data"你的<form>

<form action="." method="post" enctype="multipart/form-data">
    {% csrf_token %}
    ..........
</form>
于 2013-04-06T05:15:06.633 回答