【问题标题】:Django File Upload form: if request.method=="POST" failsDjango 文件上传表单:如果 request.method=="POST" 失败
【发布时间】:2020-05-20 09:13:21
【问题描述】:

所以我正在尝试将文件上传到我的网站。这是我以前做过的事情,但现在在我看来,表单没有通过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】:

    请纠正你的观点

    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 中使用模型表单

    【讨论】:

    • 如果我不想渲染任何东西怎么办?
    • 视图需要渲染才能得到结果,在其他模板中仍然可以通过在表单的action属性中调用url名称来调用它
    • 好吧,我试过了,还是不行。我的意思是它总是会去其他地方而不是因为 request.method=='POST' 总是为我返回 false 。那是我的问题。我的代码几乎与我在另一个项目中发布的代码相同,并且无需渲染即可正常工作。
    【解决方案2】:

    我自己想通了。我已将按钮类型指定为按钮,而不是在 home.html 中提交。我没有更改其余代码。

    【讨论】:

      猜你喜欢
      • 2014-12-07
      • 1970-01-01
      • 1970-01-01
      • 2010-09-29
      • 2012-08-29
      • 2021-05-08
      • 1970-01-01
      • 2021-09-30
      • 1970-01-01
      相关资源
      最近更新 更多