[英]Django File Upload form: if request.method==“POST” fails
So I am trying to implement file upload to my website.所以我正在尝试将文件上传到我的网站。 It is something I have done before but right now in my views the form does not pass the
if request.method=="POST"
line.这是我以前做过的事情,但现在在我看来,表单没有通过
if request.method=="POST"
行。 Here is my code:这是我的代码:
settings.py:设置.py:
...
MEDIA_URL = '/media/'
MEDIA_ROOT = os.path.join(BASE_DIR, 'media/')
urls.py:网址.py:
urlpatterns=[
...
path('filepost/', views.filepost, name='filepost')
]+ static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT)
models.py模型.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 forms.py
...
class FileForm(forms.Form):
file=forms.FileField(label='')
home.html:主页.html:
...
<form action="{%url 'filepost'%}" method="post" enctype="multipart/form-data">
{%csrf_token%}
{{fileForm}}
<button type="button">Post File</button>
</form>
views.py:视图.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('../')
I have the print(1) in the views to check if it gets past the if request.method=="POST"
line but it doesn't print 1 so I am guessing that this line is the problem.我在视图中有 print(1) 来检查它是否超过了
if request.method=="POST"
行,但它没有打印 1 所以我猜这行是问题所在。 Any ideas?有任何想法吗? Thanks!
谢谢!
please correct your view请纠正你的看法
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 }
and call it in your template {{ form.as_p }}
instead of {{fileForm}}
, also use model form in your forms.py并在您的模板中调用它
{{ form.as_p }}
而不是{{fileForm}}
,还可以在 forms.py 中使用 model 表单
I figured it out myself.我自己想通了。 I have specified the button type to be button and not submit in home.html.
我已将按钮类型指定为按钮,而不是在 home.html 中提交。 I did not change the rest of the code.
我没有更改代码的rest。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.