代码之家  ›  专栏  ›  技术社区  ›  mpen

从视图中设置字段选择?

  •  7
  • mpen  · 技术社区  · 15 年前

    我有一些 <selects> choices 这取决于当前登录的用户。我不 认为

    4 回复  |  直到 15 年前
        1
  •  5
  •   Matthew J Morrison    15 年前

    不确定这是否是最佳答案,但在过去,我在 初始化 你可以把你的选择传递给你的窗体的构造器。。。

        2
  •  2
  •   Davor Lucic    15 年前

    我在一个项目中这样做:

    user_choices = [(1, 'something'), (2, 'something_else')]
    fields['choice'] = forms.ChoiceField(
        choices=user_choices,
        widget=forms.RadioSelect,
    )
    MyForm = type('SelectableForm', (forms.BaseForm,), { 'base_fields': fields })
    form = MyForm()
    

    user_choices 根据当前用户的不同,添加您需要的任何字段以及选项,但这是一个基本原则,我将把其余的留给读者练习。

        3
  •  1
  •   juanefren    15 年前

    考虑到您已经将用户作为一个参数,我将使用一个自定义标记来解决这个问题。

    在您的应用程序/模板标签/自定义_tags.py 像这样:

    @register.simple_tag
    def combo(user, another_param):
        objects = get_objects(user, another_param)
        str = '<select name="example" id="id_example">'
        for object in objects:
            str += '<option value="%s">%s</option>' % (object.id, object.name)
        str += '</select>'
        return mark_safe(str)
    

    然后在模板中:

    {% load custom_tags %}
    {% special_select user another_param %}
    

    http://docs.djangoproject.com/en/dev/howto/custom-template-tags/

        4
  •  0
  •   mpen    14 年前

    Django创建动态表单-它工作!!


    class MyForm(forms.Form):
    
             """ Initialize form values from views"""
    
            select=forms.BooleanField(label='',required=False)
    
            field_1=forms.CharField(label='',widget=forms.TextInput(attrs= \
    
                        {'size':'20','readonly':'readonly',}))
    
            field_2=forms.ChoiceField(widget=forms.Select(), \
    
                        choices=((test.id,test.value) for test in test.objects.all()))
    
    
    
            def __init__(self, *args, **kwargs):
    
               super(MyForm, self).__init__(*args, **kwargs)
    
               input=kwargs.get('initial',{})
    
               get_field_1_initial_input_from_views=re.sub("\[|\]|u'|'","",str (input.values()))
    
               # override field_2 choices based on field_1 input
    
               try:
    
                   # filter choices
    
                   self.fields[‘field_2'].choices=((test.id,test.value) for test in test.objects.filter ( --------)))
    
               except:
    
                   pass
    

    Views.py


    def views_function(request,val):
    
            """Dynamically generate input data for formset."""
    
            Initial_data=[]
            initial_data.append({'field_1':data.info})
    
            #Initializing formset
    
            MyFormSet=formset_factory(MyForm,extra=0)
    
            formset=MyFormSet(initial=initial_data)
    
            context={'formset':formset}
    
            if request.method == 'POST':
    
               formset=MyFormSet(request.POST,request.FILES)
    
               if formset.is_valid():
    
                   # You can work with the formset dictionary elements in the views function (or) pass it to
                   #Forms.py script through an instance of MyForm
    
                   return HttpResponse(formset.cleaned_data)
    
           return render_to_response(‘test.html', context,context_instance=RequestContext(request))