Jsonresponse not working in CreateView – Django


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…


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:
            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)


class Post(models.Model):
    title = models.CharField(max_length=100)
    culture = models.CharField(max_length=100)


<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" %}

script which handles the autocomplete

  $( function() {
    $( "#nightclub" ).autocomplete({
      source: '{% url 'blog:post-create' %}'

Any help would be grateful!


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:

def get_autocomplete(request):
qs = User.objects.filter(groups__name='nightclub', first_name__icontains=request.GET.get('term'))
titles = list()
for product in qs:
return JsonResponse(titles, safe=False)


path('get-autocomplete/', get_autocomplete, name='get-autocomplete'),


  $( function() {
   $( "#nightclub" ).autocomplete({
      source: '{% url "blog:get-autocomplete" %}'

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

Leave a Reply

(*) Required, Your email will not be published