[英]Is there any way that I can write URL in django using annotations in python
[英]is there any way to dynamically add formclass to the view using url in django?
我想在我的视图中动态传递form_class
,以便单个视图可以完成所有工作。 另外,我也不想使用if条件,因为那将无法达到目的。
urls.py:
url(r'^(?P<form>[\w-]+)/$',BillCycleCreateView.as_view(),name='BillCycle'),
意见:
class BillCycleCreateView(CreateView):
template_name = 'form-view.html'
success_url = '.'
def get_form_class(self):
print(self.kwargs)
x = self.kwargs['form']
print(x)
return x
以下代码引发了str object is not callable
错误。 有什么方法可以修复它或任何其他方法来获得所需的结果? 如何退课?
提前致谢!!
您需要一个if语句,将从URL获得的字符串(在示例中为变量x
)转换为实际的表单类。
您可以执行以下操作:
def get_form_class(self):
if self.kwargs['form'] == 'form_1':
return MyForm_1
elif self.kwargs['form'] == 'form_2':
return MyForm_2
else:
raise Exception('We have an unknown parameter in the url')
建议使用更好的异常消息。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.