Passing a kwargs parameter to a ModelForm Field constructor? - django

How can I pass a parameter in to a ModelForm Field constructor?
class ThingSettingsForm(ModelForm):
things = forms.ModelChoiceField(empty_label='--',queryset=self.?????)
def __init__(self, *args, **kwargs):
super(ThingSettingsForm, self).__init__(*args, **kwargs)
if 'instance' in kwargs:
instance = kwargs['instance']
?????? = instance.visible_things
#self.fields['things'] =
#forms.ModelChoiceField(queryset=instance.visible_things)
class Meta:
model = Gallery
fields = (
'title',
'summary',
'things',
)
In the underlying model 'things' is a models.ForeignKey, and the default of showing every possible relation is not appropriate.

If visible_things is a queryset, you can change the queryset attribute of the form field:
self.fields['things'].queryset = instance.visible_things
It really does have to be a queryset, not an arbitrary iterable, but other than that it's easy.

Just add a kwarg if the arg is optional:
myform = ThingSettingsForm(thing=<my instance>)
You'll have to change the init method to pop your new arg first, as super isn't expecting this arg:
def __init__(self, *args, **kwargs):
instance = kwargs.pop('thing', None)
super(ThingSettingsForm, self).__init__(*args, **kwargs)
Or if its required, just add it into the init signature:
def __init__(self, thing, *args, **kwargs):
pass
and call it thus:
myform = ThingSettingsForm(<my instance>)

Related

Add a field value outside form in Django

Whenever I have to add a value to the instance of a form obtained from the context or from the URL I do it in the following way, using form.instance.
class PreguntaForm(forms.ModelForm):
class Meta:
model = Pregunta
fields = ('etiqueta', 'grupo', 'tipo_pregunta', 'opciones', 'mostrar_tabla', 'activo')
def __init__(self, *args, **kwargs):
cuestionario = kwargs.pop('cuestionario', False)
super(PreguntaForm, self).__init__(*args, **kwargs)
self.fields['grupo'].queryset = Grupo.objects.filter(cuestionario=cuestionario)
class PreguntaNueva(InfoPregunta, CreateView):
form_class = PreguntaForm
encabezado = 'Nueva Pregunta'
model = Pregunta
def get_form_kwargs(self):
kwargs = super(PreguntaNueva, self).get_form_kwargs()
kwargs['cuestionario'] = self.dame_cuestionario()
return kwargs
def form_valid(self, form):
form.instance.cuestionario = self.dame_cuestionario()
return super(PreguntaNueva, self).form_valid(form)
The problem that arises now is that I want to perform a check CreateView and EditView. To DRY, I want to do it in the clean method of the model, but the value that I assign to form.instance.cuestionario, is not available within the clean method. How could I do it? This value must not be edited by the user in any case.
Yes it is, you pass it in via get_form_kwargs; you just need to assign it to an instance variable in the form's __init__.
def __init__(self, *args, **kwargs):
self.cuestionario = kwargs.pop('cuestionario', False)
super(PreguntaForm, self).__init__(*args, **kwargs)
self.fields['grupo'].queryset = Grupo.objects.filter(cuestionario=self.cuestionario)
def clean(self):
# do something with self.cuestionario

django object is not iterable with custom instance

I am trying to leave my object itself out of the queryset of possible options. Problem is i get the error: 'Country' object is not iterable
Not sure where i am going wrong.
My view:
def edit_country(request, country_id):
country = get_object_or_404(Country, pk=country_id)
country_form = CountryForm(instance=country)
return render(request, 'create_country.html', {'country_form': country_form})
My form init:
def __init__(self, *args, **kwargs):
super(CountryForm, self).__init__(*args, **kwargs)
if 'instance' in kwargs:
self.fields['likes'].queryset = Country.objects.exclude(kwargs['instance'])
self.fields['hates'].queryset = Country.objects.exclude(kwargs['instance'])
Where do i go wrong?
Change the order of the method, so you pop the kwarg first. You are sending the kwarg to super.
def __init__(self, *args, **kwargs):
instance = kwargs.pop('instance', None)
#all other stuff

Django - Can't remove empty_label from TypedChoiceField

I have field in my model:
TYPES_CHOICES = (
(0, _(u'Worker')),
(1, _(u'Owner')),
)
worker_type = models.PositiveSmallIntegerField(max_length=2, choices=TYPES_CHOICES)
When I use it in ModelForm it has "---------" empty value. It's TypedChoiceField so it hasn't empty_label attribute., so I can't override it in form init method.
Is there any way to remove that "---------"?
That method doesn't work too:
def __init__(self, *args, **kwargs):
super(JobOpinionForm, self).__init__(*args, **kwargs)
if self.fields['worker_type'].choices[0][0] == '':
del self.fields['worker_type'].choices[0]
EDIT:
I managed to make it work in that way:
def __init__(self, *args, **kwargs):
super(JobOpinionForm, self).__init__(*args, **kwargs)
if self.fields['worker_type'].choices[0][0] == '':
worker_choices = self.fields['worker_type'].choices
del worker_choices[0]
self.fields['worker_type'].choices = worker_choices
The empty option for any model field with choices determined within the .formfield() method of the model field class. If you look at the django source code for this method, the line looks like this:
include_blank = self.blank or not (self.has_default() or 'initial' in kwargs)
So, the cleanest way to avoid the empty option is to set a default on your model's field:
worker_type = models.PositiveSmallIntegerField(max_length=2, choices=TYPES_CHOICES,
default=TYPES_CHOICES[0][0])
Otherwise, you're left with manually hacking the .choices attribute of the form field in the form's __init__ method.
self.fields['xxx'].empty_value = None would not work If you field type is TypedChoiceField which do not have empty_label property.
What should we do is to remove first choice:
class JobOpinionForm(forms.ModelForm):
def __init__(self, *args, **kwargs):
super(JobOpinionForm, self).__init__(*args, **kwargs)
for field_name in self.fields:
field = self.fields.get(field_name)
if field and isinstance(field , forms.TypedChoiceField):
field.choices = field.choices[1:]
Try:
def __init__(self, *args, **kwargs):
super(JobOpinionForm, self).__init__(*args, **kwargs)
self.fields['worker_type'].empty_value = None
https://docs.djangoproject.com/en/1.3/ref/forms/fields/#typedchoicefield

Pass parameter to Form in Django

I have a custom form to which I would like to pass a parameter.
Following this example I came up with the following code :
class EpisodeCreateForm(forms.Form):
def __init__(self, *args, **kwargs):
my_arg = kwargs.pop('my_arg')
super(EpisodeCreateForm, self).__init__(*args, **kwargs)
my_field = forms.CharField(initial=my_arg)
But I get the following error:
Exception Value: name 'my_arg' is not defined
How can I get it to recognize the argument in the code of the form ?
You need to set the initial value by referring to the form field instance in __init__. To get access to the form field instance in __init__, put this before the call to super:
self.fields['my_field'].initial=my_arg
And remove initial=my_arg from where you declare my_field because at that point (when class is declared) my_arg is not in scope.
The thing is that my_field is initialized when the class is created, but my_arg is initialized when a new instance is created, far too late for my_field to know its value. What you can do is initialize my_field in __init__ too:
def __init__(self, *args, **kwargs):
my_arg = kwargs.pop('my_arg')
super(EpisodeCreateForm, self).__init__(*args, **kwargs)
if not self.my_field:
self.my_field = my_arg
This code is executed once at import time:
my_field = forms.CharField(initial=my_arg)
and this code is executed on form instance creation:
my_arg = kwargs.pop('my_arg')
super(EpisodeCreateForm, self).__init__(*args, **kwargs)
So this won't work this way. You should set initial value for the field in your __init__ method.
By the way, all this seems unnecessary, why don't use 'initial' keyword in a view?
Considering your comment, I would do this:
class EpisodeCreateForm(forms.Form):
def __init__(self, *args, **kwargs):
self.my_arg = kwargs.pop('my_arg')
kwargs.setdefault('initial', {})['my_field'] = self.my_arg
super(EpisodeCreateForm, self).__init__(*args, **kwargs)
def save(self):
do_something(self.my_arg)
...
super(EpisodeCreateForm, self).save()
my_field = forms.CharField()
Passing initial to the superclass and letting it do the work seems cleaner to me than directly setting it on the field instance.
You simply need to pop your arg before super() and put it in the fields dictionnary after super() :
class EpisodeCreateForm(forms.Form):
my_field = forms.CharField(label='My field:')
def __init__(self, *args, **kwargs):
my_arg = kwargs.pop('my_arg')
super(EpisodeCreateForm, self).__init__(*args, **kwargs)
self.fields['my_arg'].initial = my_arg
Then, simply call
form = EpisodeCreateForm (my_arg=foo)
As an example, say you have a table of Episodes, and you want to show the availables ones in a choices menu, and select the current episode. For that, use a ModelChoiceField:
class EpisodeCreateForm(forms.Form):
available_episode_list = Episode.objects.filter(available=True)
my_field = forms.ModelChoiceField(label='My field:',
queryset=available_episode_list)
def __init__(self, *args, **kwargs):
cur_ep = kwargs.pop('current_episode')
super(EpisodeCreateForm, self).__init__(*args, **kwargs)
self.fields['current_episode'].initial = cur_ep

Django MultiValueField - How to pass choices to ChoiceField?

I have a multivaluefield with a charfield and choicefield. I need to pass choices to the choicefield constructor, however when I try to pass it into my custom multivaluefield I get an error __init__() got an unexpected keyword argument 'choices'.
I know the rest of the code works because when I remove the choices keyword argument from __init__ and super, the multivaluefield displays correctly but without any choices.
This is how I setup my custom multivaluefield:
class InputAndChoice(object):
def __init__(self, text_val='', choice_val=''):
self.text_val=text_val
self.choice_val=choice_val
class InputAndChoiceWidget(widgets.MultiWidget):
def __init__(self, attrs=None):
widget = (widgets.TextInput(),
widgets.Select()
)
super(InputAndChoiceWidget, self).__init__(widget, attrs=attrs)
def decompress(self,value):
if value:
return [value.text_val, value.choice_val]
return [None, None]
class InputAndChoiceField(forms.MultiValueField):
widget = InputAndChoiceWidget
def __init__(self, required=True, widget=None, label=None, initial=None,
help_text=None, choices=None):
field = (
fields.CharField(),
fields.ChoiceField(choices=choices),
)
super(InputAndChoiceField, self).__init__(fields=field, widget=widget,
label=label, initial=initial, help_text=help_text, choices=choices)
And I call it like so:
input_and_choice = InputAndChoiceField(choices=[(1,'first'),(2,'second')])
So how do I pass the choices to my ChoiceField field?
Edit:
I've tried stefanw's suggestion but still no luck. I've used logging.debug to print out the contents of InputAndChoiceField at the end of the init and self.fields[1].choices contains the correct values as per above however it doesnt display any choices in the browser.
I ran into this exact same problem and solved it like this:
class InputAndChoiceWidget(widgets.MultiWidget):
def __init__(self,*args,**kwargs):
myChoices = kwargs.pop("choices")
widgets = (
widgets.TextInput(),
widgets.Select(choices=myChoices)
)
super(InputAndChoiceWidget, self).__init__(widgets,*args,**kwargs)
class InputAndChoiceField(forms.MultiValueField):
widget = InputAndChoiceWidget
def __init__(self,*args,**kwargs):
# you could also use some fn to return the choices;
# the point is, they get set dynamically
myChoices = kwargs.pop("choices",[("default","default choice")])
fields = (
fields.CharField(),
fields.ChoiceField(choices=myChoices),
)
super(InputAndChoiceField,self).__init__(fields,*args,**kwargs)
# here's where the choices get set:
self.widget = InputAndChoiceWidget(choices=myChoices)
Add a "choices" kwarg to the widget's constructor. Then explicitly call the constructor after the field is created.
ModelChoiceField is technically a ChoiceField, but it doesn't actually use any of the ChoiceField's implementations. So, here's how I use it.
class ChoiceInputMultiWidget(MultiWidget):
"""Kindly provide the choices dynamically"""
def __init__(self, attrs=None):
_widget = (
Select(attrs=attrs),
TextInput(attrs=attrs)
)
super().__init__(_widget, attrs)
class ModelChoiceInputField(MultiValueField):
widget = ChoiceInputMultiWidget
def __init__(self, *args, **kwargs):
_fields = (
ModelChoiceField(queryset=Type.objects.all()),
CharField()
)
super().__init__(_fields, *args, **kwargs)
# Use the auto-generated widget.choices by the ModelChoiceField
self.widget.widgets[0].choices = self.fields[0].widget.choices
Have a look at the source of __init__ of forms.MultiValueField:
def __init__(self, fields=(), *args, **kwargs):
super(MultiValueField, self).__init__(*args, **kwargs)
# Set 'required' to False on the individual fields, because the
# required validation will be handled by MultiValueField, not by those
# individual fields.
for f in fields:
f.required = False
self.fields = fields
So I would overwrite the __init__ probably like this:
def __init__(self, *args, **kwargs):
choices = kwargs.pop("choices",[])
super(InputAndChoiceField, self).__init__(*args, **kwargs)
self.fields = (
fields.CharField(),
fields.ChoiceField(choices=choices),
)
You might even want to do super(MultiValueField, self).__init__(*args, **kwargs) instead of super(InputAndChoiceField, self).__init__(*args, **kwargs) because you are setting the fields yourself instead of getting them via parameters.
passing the choices in the widget solved this for me
class InputAndChoiceWidget(widgets.MultiWidget):
def __init__(self, attrs=None):
choices = [('a', 1), ('b', 2)]
widget = (widgets.TextInput(),
widgets.Select(choices=choices)
)
super(InputAndChoiceWidget, self).__init__(widget, attrs=attrs)
class HTML5DateInput(DateInput):
input_type = 'date'
class CustomSelectRangeWidget(forms.MultiWidget):
def __init__(self, attrs=None, choices = ()):
widgets = (Select(attrs=attrs, choices=choices), HTML5DateInput(attrs=attrs), HTML5DateInput(attrs=attrs))
super(CustomSelectRangeWidget, self).__init__(widgets, attrs)
def decompress(self, value):
if value:
return [value.field, value.start, value.stop]
return [None, None, None]
def format_output(self, rendered_widgets):
return '-'.join(rendered_widgets)
class CustomSelectRangeField(forms.MultiValueField):
widget = CustomSelectRangeWidget
def __init__(self, *args, **kwargs):
if kwargs.has_key('choices') :
choices = kwargs.pop('choices')
else:
choices = ()
fields = (
forms.ChoiceField(choices=choices), #field with choices,
# so that clean can be passed
forms.DateField(),
forms.DateField(),
)
super(CustomSelectRangeField, self).__init__(fields=fields, *args, **kwargs)
#initialize widget with choices.
self.widget = CustomSelectRangeWidget(choices=choices)
def compress(self, data_list):
if data_list:
#check if datalist has 3 not null values
if len([v for v in data_list if v not in [None, '']]) == 3:
out_dict = {'field':data_list[0], 'start':data_list[1], 'stop':data_list[2]}
return out_dict
return None