thanks for looking at my problem:
How do I display the text in the form textbox, but retrieve the ID on posting the form.
Everything works as expected with Autocomplete, expect for correctly displaying the reps name.
When I try this below I can post the form, using the PK, but the pk number is displayed rather than the reps name. I want to see the reps name in the text box
view.py
rep_json = {}
rep_json['id'] = item.pk
rep_json['label'] = f'{item.rep_first_name} {item.rep_last_name}'
rep_json['value'] = item.pk
I have tried various combinations to get this to work, but when I can display the text in the textbox, the validation fails on the pk.
The field being autocompleted is foreign key, hence the validation failure.
sandbox.html
<script>
$(function() {
$("#autoc").autocomplete({
source: "/autocomplete/",
minLength: 2,
});
});
</script>
<form method="post">
{% csrf_token %}
{{ form }}
<input type="submit" value="Submit">
</form>
forms.py
class sales_form2(forms.ModelForm):
class Meta:
model = sales
fields = (
'position',
'rep',
'comm' )
widgets = { 'rep': forms.TextInput(attrs={'style':'width:100px','data-url':'autocomplete/','id':'autoc'})}
views.py - Autocomplete
def sandbox_complete(request):
if request.is_ajax():
q = request.GET.get('term', '')
theReps = reps.objects.filter(Q(rep_first_name__icontains = q)|Q(rep_last_name__icontains=q))
results = []
for item in theReps:
rep_json = {}
rep_json['id'] = item.pk
rep_json['label'] = f'{item.rep_first_name} {item.rep_last_name}'
rep_json['value'] = item.pk
results.append(rep_json)
data = json.dumps(results)
else:
data = 'fail'
mimetype = 'application/json'
return HttpResponse(data, mimetype)
Any pointers would be appreciated, even what I could search on next, as I've seem to have exhausted the internet on this one.
Many thanks Graham