Django: selecting fields from a view?

I have a few <selects> that I need to fill with choices , which depend on the current user. I don’t think it is possible (or easy) to do it from within the form class, so can I just leave the selection empty and set them in the view instead? Or what approach should be taken?

+7
django django-forms
source share
4 answers

I’m not sure if this is the best answer, but in the past I asked the choice of the selection field in the init form - you could pass your options to the constructor of your form ...

+5
source share

You can create your form dynamically in your view (well, actually, I prefer to keep the code outside the view in its own function and just call it in the view, but these are just the details)

I did this in one project:

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

Obviously, you need to create user_choices depending on the current user and add any field that you need and options, but this is the basic principle, I will leave everything else as a reader exercise.

+2
source share

Given that you included the user as a parameter, I would solve this with a special tag.

In your application / templatetags / custom _tags.py is something like this:

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

Then in your template:

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

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

+1
source share

Django creates dynamic forms - it works !!

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)) 
0
source share

All Articles