1

I'm having an issue similar to this one, but the solution outlined there is not working for me.

views.py:

@login_required
def contract(request):
    form = ContractorForm()
    return render(request,'portal/main_form.html',{'form': form })

forms.py

class ContractorForm (forms.ModelForm):
    def _init_(self, *args, **kwargs):
        super(ContractorForm, self).__init__(*args, **kwargs)
        self.fields['phone'].choices= [('123',1235),('256',1256),]

    phone= forms.ChoiceField(choices=())

    class Meta:
        model = Contractor
        fields = ['name','phone']   

    def con_phone(self, user):
        return Phone.objects.filter(contractor__user = user)

The problem I'm having is that the phone field comes out without any options on the select, if I conversely change forms.py slightly it (as shown below), it works as intended

class ContractorForm (forms.ModelForm):
    phone= forms.ChoiceField(choices=[('123',1235),('256',1256),])

    class Meta:
        model = Contractor
        fields = ['name','phone']
    def _init_(self, *args, **kwargs):
        super(ContractorForm, self).__init__(*args, **kwargs)


    def con_phone(self, user):
        return Phone.objects.filter(contractor__user = user)

My problem is I intend to pass the user as an argument to the constructor to then get his phone numbers and add them as options to the form, so I [at least don't think I can] use the declarative code that's working.

I'm pretty sure I'm doing something silly (I'm fairly new to django), any assistance you guys can give me will be very much appreciated

1 Answer 1

1

In the view, you can specify the queryset of the phone field of the form

Assuming your Contractor model has a field called phones, and assuming it is One to Many from the Contractor to Phone, i.e. in Phone you have

contractor = model.ForeignKey(Contractor, related_name='phones')

you can change the phone field in the form to a ModelChoiceField and do something like this in the view

u = request.user
form.fields['phone'].queryset = u.phones.all()
Sign up to request clarification or add additional context in comments.

1 Comment

Thanks, I know I can do the filtering in the view and pass it to the contractor constructor to then give it to the field/attribute from there. My problem is that even if I hard code values and assign them to the field's choice attribute in the constructor I'm still not getting the options inside the select

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.