有一个过滤器可以添加以形成django_crispy_form功能。所有以字符串分隔的参数除以“,”。
# -*- coding: utf-8 -*-
from crispy_forms.helper import FormHelper
from crispy_forms.layout import Submit
from django.core.urlresolvers import reverse
from django.template import Library
register = Library()
#args=[url_name, submit_button_text, optional_<pk>]
@register.filter
def with_submit(form, args):
sargs = args.split(',')
action, name = sargs[:2]
if len(sargs) > 2:
args = sargs[2:]
else:
args = None
helper = FormHelper()
helper.form_method = 'POST'
if args:
#there exception throwed every time if len of args > 2
helper.form_action = reverse(action, int(args[0]))
else:
helper.form_action = reverse(action)
helper.add_input(Submit(action, name, css_class='btn btn-primary'))
form.helper = helper
return form
当我使用没有第三个可选参数的过滤器时 - 它工作正常,但当我添加第三个&lt; pk&gt;争论 - 它崩溃并说:
The included URLconf '1' does not appear to have any patterns in it. If you see valid patterns in the file then the issue is probably caused by a circular import.
我不知道应该在哪里找到循环导入。
答案 0 :(得分:2)
reverse
方法的签名是:
reverse(viewname, urlconf=None, args=None, kwargs=None, current_app=None)
因此,int(args[0])
的第二个参数将作为urlconf
传入,这将导致异常。你需要使用
reverse(action, args=int(args[0]))
每当你编写模板标签或过滤器时,你必须非常小心,你的代码尽可能简单和健壮。自定义标记和过滤器是django应用程序中最难调试的部分。
考虑这一行:
action, name = sargs[:2]
如果ValueError
中没有正好两项,则此行会引发sargs[:2]
。您应该在执行此声明之前先进行检查。