class form(forms.ModelForm):
def __init__(self, *args, **kwargs):
user = kwargs.pop('user')
u = User.objects.get(user=user)
super(form, self).__init__(*args, **kwargs)
self.fields['phone'].queryset = Phone.objects.filter(user=u)
class Meta:
model = MyModel
fields = ["name", "description", , "phone"]
This form pre-populates the field phones with phones that belong to the currently logged in user. I got the template to display using {{ form.as_p }}, but I dont know how to manually display the fields with the pre-populated phone names to be chosen, in an html template.
I tried the snippet below as part of the bigger form, but it did not work.
<select multiple="multiple" id="id_phone" name="phone" required>
{% for p in phone %}
<option value="{{ p.id }}">{{ p.name }}</option>
{% endfor %}
</select>
Also, how can I allow a user to choose multiple phones at once with this pre-population method. I tried to use ModelMultipleChoiceField but it did not work.