Django文件上传格式:如果request.method ==“ POST”失败

问题描述 投票:0回答:1

因此,我正在尝试将文件上传到我的网站。这是我以前做过的事情,但现在在我看来,表单未通过if request.method=="POST"行。这是我的代码:

settings.py:

...
MEDIA_URL = '/media/'
MEDIA_ROOT = os.path.join(BASE_DIR, 'media/')

urls.py:

urlpatterns=[
    ...
    path('filepost/', views.filepost, name='filepost')
]+ static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT)

models.py

...
class File(models.Model):
    user=models.ForeignKey(get_user_model(), on_delete=models.CASCADE, related_name='files', null=True)
    file=models.FileField(upload_to='files/')

forms.py

...
class FileForm(forms.Form):
    file=forms.FileField(label='')

home.html:

...
<form action="{%url 'filepost'%}" method="post" enctype="multipart/form-data">
     {%csrf_token%}
     {{fileForm}}
     <button type="button">Post File</button>
</form>

views.py:

...
def filepost(request):
    form=FileForm()
    if request.method=='POST':
        print(1)
        form=FileForm(request.POST, request.FILES)
        if form.is_valid():
            file=request.FILES['file']
            newupload=File(user=request.user, file=file)
            newupload.save()
    return redirect('../')

我在视图中有print(1)来检查它是否超过了if request.method=="POST"行,但是它不打印1,所以我猜想这是问题所在。有任何想法吗?谢谢!

python django file post request
1个回答
0
投票

请更正您的看法

def filepost(request):
    if request.method=='POST':
        form=FileForm(request.POST, request.FILES)
        if form.is_valid():
            newupload.save(commit=False)
            newupload.user = request.user
            newupload.save()
    else:
       form=FileForm()
       return redirect('/')
    return render(request, 'template_name.html', { 'form': form }

并在模板{{ form.as_p }}中而不是在{{fileForm}}中调用它,还可以在您的forms.py中使用模型表单

© www.soinside.com 2019 - 2024. All rights reserved.