问题
The problem seems so solvable yet it eludes me. Hope I am able to explain my predicament.
I am trying to include a jQuery autocomplete in a form. The autocomplete itself is working fine. I am now trying to link it to a model which is something like this:
models.py
class SupplierCatchment(models.Model):
supp = models.ForeignKey(Supplier.....)
supp_area = models.ForeignKey(Country, ...)
supp_remarks = models.CharField(max_length=150,...)
For rendering the form, I am using a model form.
Case 1:
In my template I am rendering the fields manually looping through the fields. For the autocomplete field, however I am using html input like this:
Template
.....
{% if field.name == "supp_area" %}
<input type="text" id="supp_area" name="supp_area" placeholder="..."> <!-- My area of concern -->
{% else %}
{{ field }}
....
During processing, the autocomplete field id="supp_area"
picks up the values correctly from the Country
model.
However on saving, I am able to save only the data entered in field supp_remarks
and the field supp_area
remains blank (it is not a required field).
Case 2:
I have tried to force field id
using attrs
in my model form like this (adapted from here):
class CreateSuppAreaForm(forms.ModelForm):
....
class Meta:
model = SupplierCatchment
fields = ('supp_area', 'supp_remarks')
widgets = {
'supp_area': forms.TextInput(attrs={'id': 'country_search', 'placeholder': 'type...'}), # 'id' being used in template autocomplete script
...
...
However, in this case I am getting the following error:
Select a valid choice. That choice is not one of the available choices.
I find it somewhat strange given that both the model field supp_area
and the jQuery autocomplete view are referring to the same FK model Country
.
What is needed to be done so that the input field id="supp_area"
value is saved. I would personally like to use the Case 1.
Edit:
The jQuery Code
<script>
$( "#supp_area" ).autocomplete({
source: "{% url 'country_search' %}",
minLength: 2,
// delay: 20,
});
</script>
The URL
path('country_search/', CountrySearch, name='country_search'),
来源:https://stackoverflow.com/questions/59653139/how-to-render-an-input-field-in-a-template-bound-to-a-model-field-in-django