我正在尝试将一些表单变量从 CreateView 传递到 TemplateView,它的作用类似于预览并呈现存储在request.session
. 我希望在新窗口中打开预览。如果没有 ajax 帖子,预览会很好地加载。但是,当我在 ajax 帖子中添加时,窗口打开时没有传递帖子数据。
窗口在没有发布数据的情况下打开。在视图中,form_valid() 被绕过。我究竟做错了什么?
有没有更好的方法来解决这个问题?我应该在 jquery 中捕获提交事件而不是单击按钮吗?
创建视图:
def form_valid(self, form):
if form.is_valid():
if self.request.POST.get('submit'):
self.object = form.save(commit=False)
self.object.profile = self.request.user.get_profile()
self.object.save()
return super(InvoiceCreateView, self).form_valid(form)
elif self.request.POST.get('preview') and self.request.is_ajax():
data = form.cleaned_data
# Obtain form data, redirect only if template is not empty
if data['template'] and data['customer']:
self.request.session['template'] = data['template']
self.request.session['customer'] = data['customer']
return redirect('invoices:invoice_preview')
else:
messages.error(request, u"Unable to preview")
return self.render_to_response(self.get_context_data(form=form))
else:
messages.error(self.request, u"Invoice creation failed")
return self.render_to_response(self.get_context_data(form=form))
js:
$("#submit-id-preview").click(function() {
$.ajax({
type: "POST",
async: false, // opens in tab if available
url: "{% url "invoices:invoice_create" %}",
data: {
csrfmiddlewaretoken: "{{csrf_token}}",
},
success: function() {
window.open("{% url "invoices:invoice_preview" %}", "_blank");
},
error: function() {
alert('ouch'); // failed
},
});
return false;
});
编辑(预览视图):
def get_context_data(self, **kwargs):
context = super(InvoicePreview, self).get_context_data(**kwargs)
try:
context['preview'] = True
context['template'] = self.request.session['template']
context['customer'] = self.request.session['event']
context['preview_message'] = self.request.session['preview_message']
except KeyError:
return Http404 # just throw 404 if cookie fails
return context
Preview 使用会话中传递的变量来渲染一些东西,值得注意的是,在 中template
,css+html 文件引用是根据用户的选择存储和返回的。因此,如果没有 ajax 帖子,预览实际上会正确呈现。而在使用 ajax 时,我得到一个argument of type 'type' is not iterable
.