and*_*ndy 7 python django jquery
(编辑:我得到了很多关于实现的答案(我很感激),但我更关心的是规范语法.这个插件的用户(即Python/Django开发人员 - 不是网站用户)需要指定条件在我正在发明的语法中.所以重新解释这个问题......在编写模型或表单类时...... 原型Python/Django开发人员更喜欢为表单字段指定条件显示逻辑以下哪种语法? )
我正在寻找一些建议用于最pythonic(可读,直接等)的方式来指定比较运算符以供稍后在比较中使用(通过javascript执行).类似的东西(这只是一个想到的例子 - 还有很多其他可能的格式):
comparisons = (('a', '>', 'b'), ('b', '==', 'c'))
Run Code Online (Sandbox Code Playgroud)
稍后将在Javascript中进行评估.
上下文是我正在研究一个Django应用程序(最终作为插件分发),这将要求用户以我选择的任何语法编写比较(因此有关使其成为pythonic的问题).比较将引用表单字段,并最终将转换为javascript条件表单显示.我想一个例子是有序的:
class MyModel(models.Model):
yes_or_no = models.SomeField...choices are yes or no...
why = models.SomeField...text, but only relevant if yes_or_no == yes...
elaborate_even_more = models.SomeField...more text, just here so we can have multiple conditions
#here i am inventing some syntax...open to suggestions!!
why.show_if = ('yes_or_no','==','yes')
elaborate_even_more.show_if = (('yes_or_no','==','yes'),('why','is not','None'))
#(EDIT - help me choose a syntax that is Pythonic and...Djangonic...and that makes your fingers happy to type!)
#another alternative...
conditions = {'why': ('yes_or_no','==','yes'),
'elaborate_even_more': (('yes_or_no','==','yes'),('why','is not','None'))
}
#or another alternative...
"""Showe the field whiche hath the name *why* only under that circumstance
in whiche the field whiche hath the name *yes_or_no* hath the value *yes*,
in strictest equality."""
etc...
Run Code Online (Sandbox Code Playgroud)
(挥手...使用model_form_factory()将MyModel转换为ModelForm ...收集字典中的所有"field.show_if"条件并将其附加到ModelForm作为MyModelForm.conditions或其他东西...)
现在,在模板中的一大块javascript中,MyModelForm.condtions中的每个条件将成为一个函数,用于侦听字段值的更改,并显示或隐藏另一个字段作为响应.基本上(在伪Javascript/Jquery中):
when yes_or_no changes...
if (yes_or_no.value == 'yes'){
$('#div that contains *why* field).show(); }
else {
$('#div that contains *why* field).hide(); }
Run Code Online (Sandbox Code Playgroud)
这里的目标是让最终用户在模型定义中以简单,pythonic的方式指定条件显示逻辑(可能有一个选项来指定表单类的条件,我认为更多是"Djangonic"(? ?),但对于我的用例,他们需要进入模型).然后我的幕后插件将其转换为模板中的Javascript.因此,您无需编写任何Javascript即可获得条件表单显示.由于这将由python/django开发人员掌握,我正在寻找建议以最原生,最舒适的方式来指定这些条件.
这是一个想法:
import operator as op
a, b, c = 10, 7, 7
def f1():
print 10
def f2():
print 20
comparisons = ((a, op.gt, b, f1), (b, op.eq, c, f2))
for lhs, oper, rhs, f in comparisons:
if oper(lhs, rhs):
f()
=> 10
=> 20
Run Code Online (Sandbox Code Playgroud)
通过适当的表示,您可以动态指定比较运算符及其相应的操作 - 作为函数实现。查看操作员模块以查看可用的操作员。
| 归档时间: |
|
| 查看次数: |
137 次 |
| 最近记录: |