Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Celery: Global SoftTimeLimitExceeded Handler function
I want to actually execute a function whenever a celery task exceeds it's allotted global soft time limit. I tried using on_faiure but it won't work as it works only upon FAILED tasks. Any suggestions? Thank You -
Django Beginner Forms, not able to get loop forms
I have a model name Fightmma and a model named Fightmmacard. Commentform works for Fightcard but not for Fightmma. Each fightcard is made of fights. When I comment on any fight, the last fight on the card gets the comment. My Commentform looks for the content type and the id. I am not able to pass the correct fight id to the Commentform properly. In my views it loop though the fights but the id is stored for the last fight only. My python isn't that great but I've been trying for 12 hours All help appreciated. models.py from __future__ import unicode_literals from django.db import models from django.core.urlresolvers import reverse from datetime import date from django.contrib.auth.models import User #Blog author or commenter from django.contrib.contenttypes.fields import GenericForeignKey from django.contrib.contenttypes.models import ContentType from django.contrib.contenttypes.fields import GenericRelation class CommentManager(models.Manager): def filter_by_instance(self, instance): content_type = ContentType.objects.get_for_model(instance.__class__) obj_id = instance.id qs = super(CommentManager, self).filter(content_type=content_type, object_id= obj_id) return qs class Comment(models.Model): author = models.ForeignKey(User) body = models.TextField(blank=True) post_date = models.DateTimeField(auto_now_add=True) content_type = models.ForeignKey(ContentType) object_id = models.PositiveIntegerField() content_object = GenericForeignKey() objects = CommentManager() class Meta: ordering = ["-post_date"] def __str__(self): """ String for representing the Model object. """ len_title=75 if len(self.body)>len_title: titlestring=self.body[:len_title] + '...' else: titlestring=self.body return … -
Customize Users inside Django Admin
I want to add some fields in Users section, apart from the predefined ones. I want to add a section called "Objectives" and also another called "Tests". How can I do this? -
Alternative to path() in Django 1.11
I have the following code in my URLs.py from django.conf.urls import url, include, path from django.contrib import admin urlpatterns = [ path('moraimono/', include('moraimono.urls')), path('admin/', admin.site.urls), however I found that path() is only included in Django 2.0 and I am using Django 1.11b1. How can I modify this code to make it work in Django 1.11b1 -
Djangae AppEngine misbehaves with IAP
Everything works fine when I use the Djangae appengine with Datastore (Django with datastore support) back-end but when I enable the Google Identity Aware Protocol (Google IAP) everything starts failing. When I checked the logs, It says that there was an IntegrityError in djangae_gaedatastoreuser on the field email_lower IntegrityError: Unique constraint violation for kind djangae_gaedatastoreuser on fields: email_lower The datastore kind has two empty entries in the email_lower field. Even the google.appengine.api.users module starts misbehaving. On first attempt to login, I can login to the AppEngine normally but I cannot logout of the appengine as a google account user, I see that I have logged out of my Google account(that's great but). When I try logging in, I see that no authentication was required to login (Google Sign In). When I login from another browser instance, It shows DatabaseError: save with update_fields did not affect any rows. Can someone please explain why this is happening and what I must do to avoid this. -
How to modify python source code using ubuntu on putty?
I am now running Ubuntu using putty, and try to modify a Django project using virtualenv. But I don't know how to open the source code. Please how to open source code and modify Thank you -
Django: Is it possible to run django without Nginx, gunicorn?
What I want to do is to run my django project on my desktop(Ubuntu 16.04) computer at my home. I have a Wi-Fi-router and use port-forwarding function to access other computer at my home by ssh. It also supports one free DDNS so I have a my own domain. Let say domain name is THIS_IS_MY_DOMAIN This is my idea : Run django on my desktop Set DEBUG=False, ALLOWED_HOST=["*",] in settings.py Run django by python super_crawler/manage.py runserver 0.0.0.0:8002 Port-forwarding on my Router : 8002(external) -> 8002(internal) When I run my django application, it shows like this in terminal: python manage.py runserver 0.0.0.0:8002 Performing system checks... System check identified no issues (0 silenced). January 19, 2018 - 17:38:03 Django version 1.11.8, using settings 'config.settings.production' Starting development server at http://0.0.0.0:8002/ Quit the server with CONTROL-C. Now I access some pages via other computer's browser with other network(from outside), and it shows like this: THIS_IS_MY_DOMAIN:8002/ => Not Found. The requested URL / was not found on this server. THIS_IS_MY_DOMAIN:8002/admin/ => Server Error (500) On my desktop, Nginx was off. I wonder whether I can run django ON MY DESKTOP in any other way. Must I use nginx, gunicorn? Edit Actually if I set DEBUG=True, … -
code in save_model executed on second save, not first
i defined a save_model in my UserAdmin to change object level permissions for users. class UserAdmin(BaseUserAdmin): def save_model(self, request, obj, form, change): obj.save() allprojects = Project.objects.all() projects = obj.workingproject.all() remove_perm("view_project", obj, allprojects) assign_perm("view_project", obj, projects) obj.save() remove_perm and assign_perm are shortcuts from django-guardian, workingproject is a M2M field of user. The problem: when selecting different projects and saving the permissions are not changed, but pressing the save button a second time makes the changes as wanted. What am i doing wrong? -
pika.exceptions.ConnectionClosed - asgi_rabbitmq + django + pika
I am getting this issue in my django project. this is the traceback: Traceback (most recent call last): File "/usr/local/lib/python3.6/site-packages/channels/worker.py", line 119, in run consumer(message, **kwargs) File "/usr/local/lib/python3.6/site-packages/channels/handler.py", line 360, in __call__ message.reply_channel.send(reply_message, immediately=True) File "/usr/local/lib/python3.6/site-packages/channels/channel.py", line 44, in send self.channel_layer.send(self.name, content) File "/usr/local/lib/python3.6/site-packages/asgi_rabbitmq/core.py", line 812, in send return future.result() File "/usr/local/lib/python3.6/concurrent/futures/_base.py", line 432, in result return self.__get_result() File "/usr/local/lib/python3.6/concurrent/futures/_base.py", line 384, in __get_result raise self._exception File "/usr/local/lib/python3.6/site-packages/channels/worker.py", line 119, in run consumer(message, **kwargs) File "/usr/local/lib/python3.6/site-packages/channels/handler.py", line 360, in __call__ message.reply_channel.send(reply_message, immediately=True) File "/usr/local/lib/python3.6/site-packages/channels/channel.py", line 44, in send self.channel_layer.send(self.name, content) File "/usr/local/lib/python3.6/site-packages/asgi_rabbitmq/core.py", line 812, in send return future.result() File "/usr/local/lib/python3.6/concurrent/futures/_base.py", line 432, in result return self.__get_result() File "/usr/local/lib/python3.6/concurrent/futures/_base.py", line 384, in __get_result raise self._exception File "/usr/local/lib/python3.6/site-packages/channels/worker.py", line 119, in run consumer(message, **kwargs) File "/build/apps/core/decorators.py", line 74, in inner return func(message, user=user, *args, **kwargs) File "/build/apps/core/consumers.py", line 110, in ws_message handler(action, message, user) File "/build/apps/core/consumers.py", line 35, in subscribe_handler Group('games').add(message.reply_channel) File "/usr/local/lib/python3.6/site-packages/channels/channel.py", line 70, in add self.channel_layer.group_add(self.name, channel) File "/usr/local/lib/python3.6/site-packages/asgi_rabbitmq/core.py", line 839, in group_add return future.result() File "/usr/local/lib/python3.6/concurrent/futures/_base.py", line 432, in result return self.__get_result() File "/usr/local/lib/python3.6/concurrent/futures/_base.py", line 384, in __get_result raise self._exception pika.exceptions.ConnectionClosed and this is what I use: asgi-rabbitmq==0.5.5 pika==0.11.2 and this is the log from rabbitmq: =WARNING REPORT==== 19-Jan-2018::09:35:40 … -
Django: Structure to import file
I have a general question about project structure in Django. I have several apps on my website. Let's say App A & App B I have now an API code which I want to import in both apps. I couldn't find a page answering me this question so I want to ask you here. Where in the project folder should I store this SOMEAPI.py file to import it in both app? -
Get multiple querysets for a particular month in Django MonthArchiveView?
The date range parameter seems to be added to the default queryset of model. I want querysets for multiple models returned. Would this have to be done in context data and with having to manually acquire the daterange? Surely there is a way to return multiple querysets for the selected range. Maybe there is generic way to apply such filtering to an existing queryset? What I am doing currently: I get the main queryset in get_queryset def get_queryset(self): entries = Entry.objects.filter(user=self.request.user) Then to get paid holidays in the get_context_data I acquire the date range in a terrible way (I think) def get_context_data(self, **kwargs): #jump through hoops to get the date range context_data = super().get_context_data(**kwargs) current_month_date = date(int(self.get_year()), int(self.get_month()), 1) current_month_datetime = datetime.combine(current_month_date, datetime.min.time()) start_month_date = self._get_current_month(current_month_datetime).date() end_month_date = get_last_day_of_month(current_month_date) context_data['total_working_days'] = PaidHoliday.calculate_total_days( start_month_date, end_month_date ) -
Error 1054 from database when I am trying to access model in admin panel
So I was trying to modify my models a bit and now I can't get rid of this error. I tried to delete all my data, but it doesn't help. I think it has to do with my database, but before, everything used to work fine. I get this error: (1054, "Unknown column 'courses_course.course_category_id' in 'field list'") And here are my models: class StudyProgramme(models.Model): department = models.ForeignKey('Department', on_delete=models.CASCADE) name = models.CharField(max_length=50) studies_type = models.IntegerField(choices=((0, "Bachelor Studies"), (1, "Master Studies"), (2, "PhD Studies"), (3, "Integrated Studies"))) duration = models.PositiveSmallIntegerField(validators=[MaxValueValidator(99)]) class Meta: verbose_name = "Study Programme" verbose_name_plural = 'Study Programmes' def __str__(self): return self.name class Course(models.Model): study_programme = models.ForeignKey('StudyProgramme', on_delete=models.CASCADE) course_category = models.ForeignKey('CourseCategory', on_delete=models.CASCADE, default='', related_name='categories') name = models.CharField(max_length=50) ects = models.PositiveSmallIntegerField(validators=[MaxValueValidator(99)]) description = models.TextField() year = models.PositiveSmallIntegerField(validators=[MaxValueValidator(99)]) semester = models.IntegerField(choices=((1, "1"), (2, "2"), ), default=None) slug = models.SlugField(max_length=140, unique=True) def __str__(self): return self.name def _get_unique_slug(self): slug = slugify(self.name) unique_slug = slug num = 1 while Course.objects.filter(slug=unique_slug).exists(): unique_slug = '{}-{}'.format(slug, num) num += 1 return unique_slug def save(self, *args, **kwargs): if not self.slug: self.slug = self._get_unique_slug() super().save() class CourseCategory(models.Model): course_category = models.CharField(max_length=50, unique=True) def __str__(self): return self.course_category class Lecture(models.Model): course = models.ForeignKey('Course', on_delete=models.CASCADE, default='', related_name='lectures') lecture_title = models.CharField(max_length=100) content = models.TextField() link … -
django - Custom redirect after login
In my app I try to redirect after submitting a form, but it seems to does not work. Here is my urls.py from django.conf.urls import url from po_contest_app import views urlpatterns = [ # url(r'^admin/', admin.site.urls), url(r'^$', views.home, name='home'), url(r'^signup/$', views.graduate_signup, name='signup'), url(r'^signup/success/$', views.signup_success, name='signup_success') ] and views.py. The actual problem is in graduate_signup view. After receiving POST request I want to create a User and then save additional info about it. For that purpose I use User Profile approach as described here: def graduate_signup(request): if request.method == 'POST': form = GraduateSignUpForm(request.POST) print('POST has been received') if form.is_valid(): user = form.save() user.refresh_from_db() # load the profile instance created by the signal user.graduate.birth_date = form.cleaned_data.get('birth_date') user.save() print('user is signed up') raw_password = form.cleaned_data.get('password1') user = authenticate(username=user.username, password=raw_password) login(request, user) print('user is signed in') return redirect('signup_success') else: print('form has some errors') print(form.errors) else: form = GraduateSignUpForm() return render(request, 'graduate_signup.html', {'form': form}) def signup_success(request): return render(request, 'signup_finished.html') After submitting form in browser, I can see logs in Django console: System check identified no issues (0 silenced). January 19, 2018 - 08:05:32 Django version 1.11.7, using settings 'po_contest.settings' Starting development server at http://127.0.0.1:8000/ Quit the server with CONTROL-C. [19/Jan/2018 08:05:34] "GET / HTTP/1.1" 200 … -
How to access excel data in django response for testing?
I have used xlwt for export some data to the client in django. Now i am testing the function and hence i want to verify that the data in response are matching with expected result. How to read the excel data from the response object. The excel data is added to response something like w.save(response) and how to retrieve this data with the response in response=self.client.get(reverse("create"))? -
How catch callback after new page was loaded?
I use pagination on scroll by Django EL(Endless) Pagination library in my project. Question: Is there any way to catch callback that will fire at the end of the request cycle, after new items have been appended to the container?! I need to refresh one script which don't work for added items. Do you have any ideas? -
How to insert seperate python scripts in django
i have created a webscraper in python and now i want to insert this file into my views.py and execute them using the html button create on html page. my scrper name is maharera.py and it is saved in same folder where i have saved views.py My views.py looks like this: from django.shortcuts import render from django.conf.urls import url from django.conf.urls import include from django.http import HttpResponse # Create your views here. def index(request): first = {"here":"will enter more details"} return render(request, "files/first-page.html", context=first) #return HttpResponse("<em>Rera details will be patched here</em>") After inserting it in views.y i want to execute that file using html button i create. How can i do that? -
Attribute Error - Where to start
i'm still a newb at django slowly figuring it out. Although ive run into this error and i dont really know where to start debugging it since the trace back doesnt tell me the location. I think i have to look at the views.py or models.py and then figure out where the nonetype is with the filter on it but after that, idk. Any insight would be appreciated. Request Method: GET Request URL: http://127.0.0.1:8000/questions/by/test1/3/ Django Version: 1.11 Python Version: 3.5.0 Installed Applications: ['django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'bootstrap3', 'accounts', 'posts', 'groups', 'questions', 'django_extensions'] Installed Middleware: ['django.middleware.security.SecurityMiddleware', 'django.contrib.sessions.middleware.SessionMiddleware', 'django.middleware.common.CommonMiddleware', 'django.middleware.csrf.CsrfViewMiddleware', 'django.contrib.auth.middleware.AuthenticationMiddleware', 'django.contrib.messages.middleware.MessageMiddleware', 'django.middleware.clickjacking.XFrameOptionsMiddleware'] Traceback: File "/Users/chrismaltez/anaconda3/envs/SimpleSocialEnv/lib/python3.5/site-packages/django/core/handlers/exception.py" in inner 41. response = get_response(request) File "/Users/chrismaltez/anaconda3/envs/SimpleSocialEnv/lib/python3.5/site-packages/django/core/handlers/base.py" in _get_response 187. response = self.process_exception_by_middleware(e, request) File "/Users/chrismaltez/anaconda3/envs/SimpleSocialEnv/lib/python3.5/site-packages/django/core/handlers/base.py" in _get_response 185. response = wrapped_callback(request, *callback_args, **callback_kwargs) File "/Users/chrismaltez/anaconda3/envs/SimpleSocialEnv/lib/python3.5/site-packages/django/views/generic/base.py" in view 68. return self.dispatch(request, *args, **kwargs) File "/Users/chrismaltez/anaconda3/envs/SimpleSocialEnv/lib/python3.5/site-packages/django/views/generic/base.py" in dispatch 88. return handler(request, *args, **kwargs) File "/Users/chrismaltez/anaconda3/envs/SimpleSocialEnv/lib/python3.5/site-packages/django/views/generic/detail.py" in get 115. self.object = self.get_object() File "/Users/chrismaltez/anaconda3/envs/SimpleSocialEnv/lib/python3.5/site-packages/django/views/generic/detail.py" in get_object 38. queryset = queryset.filter(pk=pk) Exception Type: AttributeError at /questions/by/test1/3/ Exception Value: 'NoneType' object has no attribute 'filter' Here is my views.py gist for questions: class QuestionDetail(generic.DetailView): model = models.Question def get_queryset(self): queryset = super().get_queryset() class UserQuestions(generic.ListView): model = models.Question … -
Issues with django-allauth 0.34.0 with django 2.0, how do i update my package
i have problems using django-allauth in my project, like viewing/editing the socialaccount. im getting AttributeError at /en/admin/socialaccount/socialaccount/2/change/ 'JSONField' object has no attribute '_get_val_from_obj' Request Method: GET Request URL: http://localhost:8000/en/admin/socialaccount/socialaccount/2/change/ Django Version: 2.0.1 Exception Type: AttributeError Exception Value: 'JSONField' object has no attribute '_get_val_from_obj' i tried getting the latest version but still get 0.34.0 pip install django-allauth --upgrade i've reviewed the github code and it looks like it's already fixed. https://github.com/pennersr/django-allauth/pull/1878 how do i fix this? or do i need to wait for someone to update the installer? The latest version in https://pypi.python.org/pypi/django-allauth is version 0.34.0 - last updated - Oct 29, 2017 -
Authenticate users in sleekxmpp
I am accepting a username in an html page and sending the name as a post to Django which in turn connects to the xmpp server. I need to authenticate the user and take action accordingly. Right now, I do not have a problem with the users already created but I am not able to handle non-authenticated users. I am getting the following error - INFO Negotiating TLS INFO Using SSL version: TLS 1.0 INFO Authentication failed: not-authorized INFO Authentication failed: not-authorized ERROR No appropriate login method. INFO Waiting for from server ERROR Error reading from XML stream. -
Customize show_more tag in django-endless-pagination?
I use pagination on scroll by Django EL(Endless) Pagination library in my project. By default show_more tag show loading word. I want customize it. I use next code but it work incorrect. It show me 9 icons and at the end don't disappear. I am little bit confused. How to fix it? settings.py: EL_PAGINATION_LOADING = """<i class='fa fa-cog fa-spin fa-3x fa-fw text-info text-justify endless_loading'>""" -
Error: BadZipFile: File is not a zip file when install django-libsass
I create a virtual env with python3. I install django and some packages. It works. But when install django-libsass, It raise an error BadZipFile: File is not a zip: Collecting django-libsass Exception: Traceback (most recent call last): File "/home/ubuntu/new_env/lib/python3.5/site-packages/pip/basecommand.py", line 215, in main status = self.run(options, args) File "/home/ubuntu/new_env/lib/python3.5/site-packages/pip/commands/install.py", line 335, in run wb.build(autobuilding=True) File "/home/ubuntu/new_env/lib/python3.5/site-packages/pip/wheel.py", line 749, in build self.requirement_set.prepare_files(self.finder) File "/home/ubuntu/new_env/lib/python3.5/site-packages/pip/req/req_set.py", line 380, in prepare_files ignore_dependencies=self.ignore_dependencies)) File "/home/ubuntu/new_env/lib/python3.5/site-packages/pip/req/req_set.py", line 620, in _prepare_file session=self.session, hashes=hashes) File "/home/ubuntu/new_env/lib/python3.5/site-packages/pip/download.py", line 809, in unpack_url unpack_file_url(link, location, download_dir, hashes=hashes) File "/home/ubuntu/new_env/lib/python3.5/site-packages/pip/download.py", line 715, in unpack_file_url unpack_file(from_path, location, content_type, link) File "/home/ubuntu/new_env/lib/python3.5/site-packages/pip/utils/__init__.py", line 599, in unpack_file flatten=not filename.endswith('.whl') File "/home/ubuntu/new_env/lib/python3.5/site-packages/pip/utils/__init__.py", line 484, in unzip_file zip = zipfile.ZipFile(zipfp, allowZip64=True) File "/usr/lib/python3.5/zipfile.py", line 1026, in __init__ self._RealGetContents() File "/usr/lib/python3.5/zipfile.py", line 1093, in _RealGetContents raise BadZipFile("File is not a zip file") zipfile.BadZipFile: File is not a zip file I don't know why, anyone help me! Thanks! -
How to write testcases in python-django testing?
Consider a code below, dev=request.POST['device'] stat=request.POST['type'] For the front i have used two drop down options. <select name="device" id="dev"> <option value="device1">device1</option> <option value="device2">device2</option> </select> <select name="type" id="typ"> <option value="auto">Automatic</option> <option value="manual">Manual</option> </select> Can you please tell me how to write white box test cases for the above python code. Please find my testcases below. def test_post_device_keyerror(self): postdata={'type':'manual'} self.client.login(username='vishnu',password='vishnu@12345') with self.assertRaises(MultiValueDictKeyError): response=self.client.post(reverse("create"),postdata) def test_post_type_keyerror(self): postdata={'device':'device1'} self.client.login(username='vishnu',password='vishnu@12345') with self.assertRaises(MultiValueDictKeyError): response=self.client.post(reverse("create"),postdata) def test_post_valid_data(self): postdata={'device':'device1','type':'manual'} self.client.login(username='vishnu',password='vishnu@12345') response=self.client.post(reverse("create"),postdata) self.assertEqual(response.status_code,200) Is this test cases enough? or whether my sequence of tests is wrong? -
django import-export work with django smart-selected
i want to create function export and import model from xls my model.py class LegalDocumentField(models.Model): name = models.CharField(max_length=255, default="default" class LegalDocumentType(models.Model): linhvuc = models.ForeignKey(LegalDocumentField, on_delete=models.CASCADE) name = models.CharField(max_length=255, default="default") class LegalDocument(models.Model): linhvuc = models.ForeignKey(LegalDocumentField, on_delete=models.CASCADE, verbose_name="Lĩnh vực") loai = ChainedForeignKey( LegalDocumentType, chained_field="linhvuc", chained_model_field="linhvuc", show_all=False, auto_choose=True, sort=True,) LegalDocument model use django smart-selected format and now i want to import-export LegalDocument model in admin i have already tried that: in admin.py @admin.register(LegalDocument) class LegalDocAdmin(ImportExportModelAdmin): pass my xls after exported exported xls file but when i import from this file it have error: "LegalDocument.loai" must be a "LegalDocumentType" instance. Please save me thanks -
Django 'python manage.py runserver' has from config import* error
I have an error when i use django. Traceback (most recent call last): File "manage.py", line 15, in <module> execute_from_command_line(sys.argv) File "/Users/ghk/djangoprojects/myvenv/lib/python3.6/site-packages/django/core/management/__init__.py", line 364, in execute_from_command_line utility.execute() File "/Users/ghk/djangoprojects/myvenv/lib/python3.6/site-packages/django/core/management/__init__.py", line 308, in execute settings.INSTALLED_APPS File "/Users/ghk/djangoprojects/myvenv/lib/python3.6/site-packages/django/conf/__init__.py", line 56, in __getattr__ self._setup(name) File "/Users/ghk/djangoprojects/myvenv/lib/python3.6/site-packages/django/conf/__init__.py", line 41, in _setup self._wrapped = Settings(settings_module) File "/Users/ghk/djangoprojects/myvenv/lib/python3.6/site-packages/django/conf/__init__.py", line 110, in __init__ mod = importlib.import_module(self.SETTINGS_MODULE) File "/Library/Frameworks/Python.framework/Versions/3.6/lib/python3.6/importlib/__init__.py", line 126, in import_module return _bootstrap._gcd_import(name[level:], package, level) File "<frozen importlib._bootstrap>", line 994, in _gcd_import File "<frozen importlib._bootstrap>", line 971, in _find_and_load File "<frozen importlib._bootstrap>", line 955, in _find_and_load_unlocked File "<frozen importlib._bootstrap>", line 665, in _load_unlocked File "<frozen importlib._bootstrap_external>", line 678, in exec_module File "<frozen importlib._bootstrap>", line 219, in _call_with_frames_removed File "/Users/ghk/djangoprojects/lab-in-the-wild/labinthewild/settings.py", line 18, in <module> from config import * ModuleNotFoundError: No module named 'config' If I command 'python manage.py runserver', it show this error. -
Serializing User model
I have the following code that should return me all the Users that are registered in my site, but for some reason it just returned me the last signed user, I need all the users in my JSON. from django.shortcuts import render, redirect import json from django.http import HttpResponse from rest_framework.response import Response from rest_framework.views import APIView from profiles.serializers import ProfileSerializer from django.contrib.auth.models import User from rest_framework.decorators import api_view class ProfilesAPI(APIView): serializer = ProfileSerializer def get(self, request, format=None): users = User.objects.all() response = self.serializer(users, many=True) for j in range(0,len(response.data)): dictionary = response.data[j] myresponse = "" for i, (val, v) in enumerate(dictionary.items()): myresponse = [{"text":v} for v in dictionary.values()] print(myresponse) return HttpResponse(json.dumps({'messages': myresponse}), content_type='application/json') and throws me this, even I have more than one user registered. My JSON