我希望有一个表单接受输入并使用CBV将其附加到网址。例如,如果我输入5,它应该做一些处理(查询/自定义功能)并重定向到/ order / 5 / details /显示订单号5的详细信息。在/ order / 5 / details /如果我按计划,它应该路由到/ order / 5 / schedule等等。
基本上,我的问题是 - 如何使用CBV实现这一目标? CBV只与物体联系在一起吗?
这是我到目前为止所做的:
#order/forms.py
from django import forms
class OrderForm(forms.Form):
order_id = forms.IntegerField()
#order/views.py
class OrderFormView(FormView):
# form to enter Id
form_class = OrderForm
success_url = '/order/detail/'
template_name = 'order/order_form.html'
@method_decorator(login_required(login_url='/order/login/'))
def dispatch(self, request, *args, **kwargs):
return super(OrderFormView, self).dispatch(request, *args, **kwargs)
def form_valid(self, form):
order_id = self.request.POST['order_id'] # this or get method?
return HttpResponseRedirect(self.get_success_url(), {'order_id': order_id})
def form_invalid(self, form):
return self.render_to_response(self.get_context_data(form=form))
def get_context_data(self, **kwargs):
context = super(OrderFormView, self).get_context_data(**kwargs)
context['name'] = self.request.user.username
return context
class OrderDetailView(TemplateView):
template_name = 'order/order_detail.html'
@method_decorator(login_required(login_url='/order/login'))
def dispatch(self, request, *args, **kwargs):
return super(OrderDetailView, self).dispatch(request, *args, **kwargs)
def get(self, request, *args, **kwargs):
context = self.get_context_data(**kwargs)
return self.render_to_response(context)
def get_context_data(self, **kwargs):
context = super(OrderDetailView, self).get_context_data(**kwargs)
context['name'] = self.request.user.username
return context
#urls
url(r'^order/$', OrderFormView.as_view(), name='order-form'),
url(r'^order/(?P<order_id>\d+)/orderdetails/$', tasks.views.TaskDetailView.as_view(), name='tasks-detail'),
答案 0 :(得分:0)
我无法看到这与基于类的视图有什么关系。
无论您的代码在哪里,都可以使用reverse
函数计算网址。所以你可以这样做:
redirect_url = reverse('tasks-details', kwargs={'order_id': 5})
您可以从任何想要进行重定向的地方return redirect(redirect_url)
。
答案 1 :(得分:0)
使用@Daniel的答案,您可以覆盖get_success_url
方法并将所需的变量传递到所需的视图。然后,您可以返回相应的页面(详细信息或计划):
# code snippet
# views.py
def get_success_url(self):
order_num = self.kwargs['order_num']
page_name = self.kwargs['page_name']
return HttpResponseRedirect(reverse('tasks-details', args=(order_num, page_name,)))
# urls.py
urlpatterns = patterns('',
url(
regex=r'^order/(?P<order_num>[\d]+)/(?P<page_name>[\w]+)$',
view= login_required(OrderView.as_view()),
name='tasks-details'
),
)