我的观点是这样的
class RecordView(View):
record_form = RecordForm
record_files = {}
templare = 'acquisition.html'
def get(self, request, *args, **kwargs):
fil = urllib.urlopen('/home/student/wwww.jpg')
self.record_files = {'small_cover': SimpleUploadedFile('hehe.jpg', fil.read())}
rr_form = self.record_form()
return render(request, self.template_name, {'rr_form': rr_form,
})
def post(self, request, *args, **kwargs):
record = RecordForm(request.POST, self.record_files)
record.save()
HttpResponseRedirect('/')
这里我已经在get方法中填充了self.record_files ..但是在我发布数据后,我将self.record_files视为空字典。我在这里感到困惑。我该怎么办呢。
答案 0 :(得分:1)
在get和post之间不维护视图实例的状态,因此在实例上设置record_files
将不会保留它以用于下一个请求。您需要将该逻辑放在dispatch
方法中,或将信息存储在用户的session
中。
class RecordView(View):
record_form = RecordForm
record_files = {}
templare = 'acquisition.html'
# dispatch is called before deciding whether to use get() or post()
# so any instance-level properties that require the request can go here.
# This could even go in __init__().
def dispatch(self, request, *args, **kwargs):
fil = urllib.urlopen('/home/student/wwww.jpg')
self.record_files = {'small_cover': SimpleUploadedFile('hehe.jpg', fil.read())}
return super(RecordView, self).dispatch(request, *args, **kwargs)
def get(self, request, *args, **kwargs):
rr_form = self.record_form()
return render(request, self.template_name, {'rr_form': rr_form,
})
# self.record_files will be available in a get, or a post (or any valid
# method for that matter).
def post(self, request, *args, **kwargs):
record = RecordForm(request.POST, self.record_files)
record.save()
return HttpResponseRedirect('/')
答案 1 :(得分:0)
这正是它的假设。每当你有一个GET请求时,它会调用方法get
,如果它是一个POST请求,它自然会调用post
方法,而不是get
方法。所以这就是你如何解决问题:
from django.views.generic import TemplateView
class RecordView(TemplateView):
record_form = RecordForm
record_files = {}
template_name = 'acquisition.html'
def get_context_data(self, **context):
fil = urllib.urlopen('/home/student/wwww.jpg')
self.record_files = {
'small_cover': SimpleUploadedFile('hehe.jpg', fil.read())
}
context.update({
'record_files': self.record_files,
'rr_form': self.record_form()
})
fil.close()
return super(RecordView, self).get_context_data(**context)
def post(self, request, *args, **kwargs):
context = self.get_context_data()
record_form = self.record_form(request.POST, self.record_files)
if record_form.is_valid():
record_form.save()
## or do a redirect instead, like you had before:
# return HttpResponseRedirect('/')
context['rr_form'] = record_form
return self.render_to_response(context)