Django:从视图中设置字段选择?

时间:2010-08-12 01:16:14

标签: django django-forms

我有一些<selects>我需要填充一些取决于当前登录用户的choices。我不认为这可以(或很容易)从表单类中进行,所以我可以将选项留空并在视图中设置它们吗?或者我应该采取什么方法?

4 个答案:

答案 0 :(得分:5)

不确定这是否是最好的答案,但过去我已经在表单的 init 中设置了选择字段的选项 - 您可能会将您的选择传递给您的构造函数形式...

答案 1 :(得分:2)

您可以在视图中动态构建表单(实际上,我宁愿将代码保留在视图之外的自己的函数中,只是在视图中调用它,但这只是详细信息)

我在一个项目中这样做了:

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并添加您需要的任何字段以及选项,但这是一个基本原则,我将其余部分作为读者练习。< / p>

答案 2 :(得分:1)

考虑到您已将用户作为参数包含在内,我将使用自定义标记解决此问题。

在你的app / templatetags / custom_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/

答案 3 :(得分:0)

Django创建动态表单 - 它有效!!

<强> Forms.py


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))