Reputation: 31
I'm trying to work out how to have suggestions in a text field using Django (1.11). I've been going through the documentation of autocomplete-light but so far I've not been able to figure out my use case. The documentation on that package is not easy to understand for a total noob :)
I want a text field that gives suggestions as you type, were the suggestions come from the database.
E.g. if it's a list of food items the user types in 'C' and it suggest Chicken and Crisps as they have been entered by someone earlier. I also want the user to be able to enter Cheese even though it hasn't been entered before.
The suggestion "algorithm" just has to check if what has been entered matches the first characters of already existing items.
Here is a boiled down version of the django project:
urls.py
from django.conf.urls import url
from django.contrib import admin
from testapp.views import TestView
urlpatterns = [
url(r'^admin/', admin.site.urls),
url(r'$',TestView.as_view())
]
models.py
from django.db import models
class TestModel(models.Model):
name = models.CharField(max_length=120)
def __str__(self):
return self.name
forms.py
from django import forms
from .models import TestModel
class TestFormClass(forms.ModelForm):
class Meta:
model = TestModel
fields = ('__all__')
views.py
from django.shortcuts import render
from django.views.generic import CreateView
from .forms import TestFormClass
class TestView(CreateView):
form_class = TestFormClass
template_name = 'template.html'
success_url = "/"
template.html
<html>
<header><title>This is title</title></header>
<body>
Enter something <br>
{% block content %}
<form method="post">
{% csrf_token %}
{{ form.as_p }}
<input type="submit" value="Submit" />
</form>
{% endblock %}
</body>
</html>
I'm hoping someone has a relatively simple solution to add the this code, at the moment I'm not worried about authentication or anything, just looking for a basic solution.
Upvotes: 0
Views: 4218