我是当前的web2py用户,但发现我偶尔会回到Django(我开始的地方)。特别是在处理我想要使用web2py中尚不存在的某些特定django应用程序/插件/扩展的项目时。
我不能没有在web2py中存在的一件事,我正在寻找Django的解决方案,是从db表创建html表单然后能够在视图中自定义它们的外观和布局的方法,没有javascript。
我正在寻找的关键事项:
即。
我有一张表A.在web2py中我可以做(在控制器中):
def display_form():
form = SQLFORM(db.table_A)
#Can I do the following in Django? Assign custom CSS to each form field?
form.element(_name='email')['_class'] = = "custom_css_classes, list"
if form.accepts(request.vars, session):
response.flash = 'form accepted'
elif form.errors:
response.flash = 'form has errors'
else:
response.flash = 'please fill out the form'
return dict(form=form)
然后,在我可以做的视图中:
form.custom.start
form.custom.widget.name
form.custom.widget.email
form.custom.widget.form_field_name
...
<div class="span-5 last"><input type="submit" class="register_btn" value="Sign Up"></input></div>
form.custom.end
上面是一个DB表,创建一个HTML表单,然后让我将每个单独的表单字段粘贴到我想要的预制HTML中的任何位置(使用传递的“表单”上的那些“自定义”方法调用)对象。包括我为生成的html表单的每个单独字段分配的自定义css类。
有关上述代码的详细信息,请参阅文档:
http://web2py.com/book/default/chapter/06?search=define_table
http://web2py.com/book/default/chapter/07?search=sqlform#SQLFORM
http://web2py.com/book/default/chapter/05?search=#Server-side-DOM-and-Parsing
http://web2py.com/book/default/chapter/07?search=form.custom
如何在Django中执行上述操作而不会因布局黑客而污染我的javascript。假设在我需要运行应用程序的浏览器中禁用了javascript。此外,我很想使用Django管理员。 Pylons解决方案也欢迎!
非常感谢文章/教程/ howtos的链接。 另外,请使用您在回复中提到的方法制作上述代码的等效结果......
答案 0 :(得分:1)
如果你还没有,请看看Django的ModelForm。我假设你有模型映射到有问题的表。 Vanilla ModelForm
实例将在没有JS的情况下工作。但是ModelForm
s通常是提前定义的,而不是动态构建的。我想他们可以在飞行中创建,但这有点棘手。
答案 1 :(得分:1)
使用ModelForm
并覆盖您想要自定义的任何字段,方法是明确声明它们。
如果您想设置class
和id
等字段属性,则需要执行以下操作:
name = forms.CharField(
widget=forms.TextInput(attrs={'class':'special'}))
如果您有兴趣,可以在fields
课程中指定Meta
序列来更改字段的顺序:
class Meta:
model = YourModel
fields = ('title', 'content')
您可以在此处阅读完整文档: http://docs.djangoproject.com/en/dev/ref/forms/widgets/#django.forms.Widget.attrs