我尝试接受localhost:8000 /上传文件并遇到此问题
未绑定方法upload_file()必须使用Upload instance作为第一个参数调用(改为获取WSGIRequest实例)
urls.py
from django.conf.urls import include, url
from django.contrib import admin
from upload.views import Upload
urlpatterns = [
url(r'^admin/', include(admin.site.urls)),
url(r'^upload/$', Upload.upload_file),
url(r'^thanks/$', Upload.thanks),
]
views.py
from django.http import HttpResponse
from django.template import RequestContext
from django.shortcuts import render_to_response
from upload.forms import FileForm
from upload.models import upFile
class Upload():
def upload_file(request):
if request.method == "POST":
form = FileForm(request.POST, request.FILES)
if form.is_valid():
form.save()
return HttpResponseRedirect('thanks')
else:
form = FileForm()
return render_to_response('temp1.html', {'form': form}, context_instance = RequestContext(request))
def thanks(request):
return render_to_response('temp2.html')
答案 0 :(得分:1)
您的视图不是从基于Django类的视图继承的:https://docs.djangoproject.com/en/1.8/topics/class-based-views/intro/
from django.views.generic import View
class Upload(View):
def upload_file(self, request):
if request.method == "POST":
form = FileForm(request.POST, request.FILES)
if form.is_valid():
form.save()
return HttpResponseRedirect('thanks')
else:
form = FileForm()
return render_to_response('temp1.html', {'form': form}, context_instance = RequestContext(request))
def thanks(self, request):
return render_to_response('temp2.html')
您需要继承其中一个视图类,否则Django会将您的视图视为普通类,这就是您收到该错误的原因。
您还需要调整urls.py:
urlpatterns = [
url(r'^upload/', Upload.as_view()),
]
在查看了文档和vie的结构之后,我不确定您是否正在为基于类的视图正确构建视图。您可能需要更多地阅读文档并相应地调整您的结构。
我相信你会想要一些看起来更像这样的东西:
class Upload(View):
def get(self, request):
form = FileForm()
return render_to_response('temp1.html', {'form': form}, context_instance = RequestContext(request))
def post(self, request):
form = FileForm(request.POST, request.FILES)
if form.is_valid():
form.save()
return HttpResponseRedirect('thanks')
else:
return render_to_response('temp2.html')
答案 1 :(得分:0)
我不明白为什么你有上传课程。 Python不是Java,没有必要把所有东西都放到类中。将upload_file
和thanks
放在模块级别,并直接在网址模式中引用它们。