Issue
I’m trying to get all the users who has the group ‘decoration’ into a form field by using JsonResponse to get the list in realtime when the user start to type in the field.
The problem here is that I’m not getting any data in the form as a Jsonresponse. If I make a print of "titles", is getting the correct data, but is not bringing the data to the form…
views.py
class PostCreateView(LoginRequiredMixin, CreateView):
model = Post
fields = ['...']
def get_form(self, form_class=None):
form = super().get_form(form_class)
if 'term' in self.request.GET:
qs = User.objects.filter(groups__name='decoration', username__icontains=self.request.GET.get('term'))
titles = list()
for product in qs:
titles.append(product.username)
return JsonResponse(titles, safe=False)
return form
def form_valid(self, form):
form.instance.author = self.request.user
return redirect(reverse('blog:post-detail', kwargs={'pk': obj.id}))
def form_invalid(self, form):
messages.error(self.request, self.error_message)
form.instance.thumb.checked = True
return super().form_invalid(form)
models.py
class Post(models.Model):
title = models.CharField(max_length=100)
culture = models.CharField(max_length=100)
.HTML
<div class="form-group">
<label>Some text</label>
{% render_field form.culture class="form-control form-st text-body" style="box-shadow: none;font-size:1.5rem;" id="nightclub" placeholder='...' autocomplete="off" %}
</div>
script which handles the autocomplete
<script>
$( function() {
$( "#nightclub" ).autocomplete({
source: '{% url 'blog:post-create' %}'
});
});
</script>
Any help would be grateful!
Solution
So, I found the solution to this. I was doing wrong in defining a get_from() inside the createview class, I need to call the function from outside the class.
So, the result will be:
views.py
@csrf_exempt
def get_autocomplete(request):
qs = User.objects.filter(groups__name='nightclub', first_name__icontains=request.GET.get('term'))
titles = list()
for product in qs:
titles.append(product.first_name)
return JsonResponse(titles, safe=False)
urls:
path('get-autocomplete/', get_autocomplete, name='get-autocomplete'),
html:
<script>
$( function() {
$( "#nightclub" ).autocomplete({
source: '{% url "blog:get-autocomplete" %}'
});
});
</script>
Answered By – Khris Vandal
This Answer collected from stackoverflow, is licensed under cc by-sa 2.5 , cc by-sa 3.0 and cc by-sa 4.0