简体   繁体   中英

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. Here is my code:

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('../')

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. 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

I figured it out myself. I have specified the button type to be button and not submit in home.html. I did not change the rest of the code.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM