Learner Learner - 1 year ago 59
Python Question

How to assign dropdown data to a field after importing data from view

I am creating a dropdown in forms.py and to filter data I am getting a variable named

layer_id
. And getting in view like this
layer_id = kwargs['layer_id']
. All things are good but when I assign on end to filed like this
self.fields['apn'].queryset= Field.objects.filter(layer=layer)
. Call goes to
fields
table of database rather then assigning these fields I declared in forms.py. So who can I assign to fields in forms.py

class labelModelForm(forms.ModelForm):
model = Labels_tool_
fields = ['apn', 'owner_name', 'situs_addr_One', 'situs_addr_Two', 'mailing_addr_One', 'mailing_addr_Two']
apn = forms.ModelChoiceField(queryset=Field.objects.values_list('name', flat=True), empty_label="(Choose field)")

def __init__(self, *args, **kwargs):
//getting layer_id from views
layer_id = kwargs['layer_id']
print layer_id
layer=Layer.objects.filter(id=layer_id).first()
x=Field.objects.filter(layer=layer)
//On this step when modify queryset I get error
self.fields['apn'].queryset= Field.objects.filter(layer=layer)

Answer Source
def __init__(self, *args, **kwargs):
    layer_id = kwargs.pop('layer_id', None)
    super(labelModelForm, self).__init__(*args, **kwargs)
    layer=Layer.objects.filter(id=layer_id).first()
    x=Field.objects.filter(layer=layer)
    self.fields['apn'].queryset= Field.objects.filter(layer=layer)

i hope this will help you

change your form to

class labelModelForm(forms.ModelForm):
      apn = forms.ModelChoiceField(Field.objects.values_list('name', flat=True), empty_label="(Choose field)")
    class Meta:
        model = Labels_tool_
        fields = ['apn', 'owner_name', 'situs_addr_One', 'situs_addr_Two', 'mailing_addr_One', 'mailing_addr_Two']
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download