Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Django Python Check if the project is followed
I'm currently working on a website that allows you to follow and unfollow projects. On the project page, there is a follow button, and if you click that button, you are now following the team, and the button should turn into unfollow afterwards. Is a template tag that looks like {% if user.is_authenticated %} a good way to determine if the project is followed? Would I need to create a template tag and put it around my divs? <div class="progress-stats"> <a href="{% url 'teams:follow' team.id %}">Follow </a> </div> <div class="progress-stats"> <a href="{% url 'teams:unfollow' team.id %}">Unfollow </a> </div> -
Django Admin Cannot connect to mysql (2002, "Can't connect to local MySQL server through socket '/var/run/mysqld/mysqld.sock' (111)")
An Issue I am consistently facing on ubuntu 14.04 production server and surfaced probably when we shifted from django 1.7 to 1.10 (or maybe due to changing the version of mysql-connector etc). Most of the things related to mysql is working fine but lately, I am frequently getting this error "MySQL gone away" and "2002 Can't connect to local MySQL server through socket". An Specification is: When i go to django admin things run fine but whenever i try to access objects in few particular models, It doesn't work saying (2002, "Can't connect to local MySQL server through socket '/var/run/mysqld/mysqld.sock' (111)"). I must emphasise that it happens only in django-admin and that too in accessing objects of particular(specific) models only. What can be the underlying issue and what steps should i try? -
Django cookies are not getting saved on browser
I am making an application with react and Django. When i login with django i set token in cookie but Django response cookies are not set in browser. I trying to debug it hard but could not. Don't know where i m doing wrong. Request URL:http://localhost:8000/login/ Request Method:POST Status Code:200 OK Remote Address:127.0.0.1:8000 Response Headers Access-Control-Allow-Credentials:true Access-Control-Allow-Origin:http://localhost:3000 Content-Type:application/json Date:Sun, 12 Feb 2017 13:32:30 GMT Server:WSGIServer/0.1 Python/2.7.10 Set-Cookie:token=97547ba32cb8abcfe81b28c47ee5e3b8087b54ac; Path=/ Set-Cookie:sessionid=6twm2h9mad6q8k4w637ww25zt6l0ck2d; expires=Sun, 26-Feb-2017 13:32:30 GMT; httponly; Max-Age=1209600; Path=/ Vary:Cookie X-Frame-Options:SAMEORIGIN Request Headers Accept:application/json, text/plain, */* Accept-Encoding:gzip, deflate, br Accept-Language:en-GB,en-US;q=0.8,en;q=0.6 Authorization:Token undefined Connection:keep-alive Content-Length:41 Content-Type:application/json;charset=UTF-8 Host:localhost:8000 Origin:http://localhost:3000 Referer:http://localhost:3000/ User-Agent:Mozilla/5.0 (Macintosh; Intel Mac OS X 10_12_0) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/56.0.2924.87 Safari/537.36 settings.py """ Django settings for server project. Generated by 'django-admin startproject' using Django 1.8. For more information on this file, see https://docs.djangoproject.com/en/1.8/topics/settings/ For the full list of settings and their values, see https://docs.djangoproject.com/en/1.8/ref/settings/ """ # Build paths inside the project like this: os.path.join(BASE_DIR, ...) import os BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__))) # Quick-start development settings - unsuitable for production # See https://docs.djangoproject.com/en/1.8/howto/deployment/checklist/ # SECURITY WARNING: keep the secret key used in production secret! SECRET_KEY = '83vwkomf5s1y_!jt#=_dlgv!v0t38yl!a80h#r0buor70$0y7=' # SECURITY WARNING: don't run with debug turned on in production! DEBUG = True ALLOWED_HOSTS = [] # … -
django don't allow a user to access a page
views.py class DashboardNewProfile(LoginRequiredMixin, CreateView): form_class = ProfileForm model = Profile queryset = Profile.objects.all() template_name = 'profile/profile_create.html' def _usercheck(self): u = self.request.user qs = Profile.objects.all().filter(u) if qs is None: return HttpResponseRedirect('/profile/create/') else: return HttpResponseRedirect('/profile/view/') def get_form_kwargs(self): kwargs = super(DashboardNewProfile, self).get_form_kwargs() kwargs.update({'user': self.request.user}) kwargs.update({'slug': self.request.user.username}) return kwargs How do i do the following? If the logged in user already has a profile associated with a profile object in the database. i dont want the user to access the URL ('/profile/created/') insted i want the user to be automatically redirected to another url ('/profile/view') -
Docker Django could not connect to server: Connection refused
I'm new to Docker, and I'm trying to put my Django rest API in a container with Nginx, Gunicorn and Postgres, using docker-compose and docker-machine. Following this tutorial: https://realpython.com/blog/python/django-development-with-docker-compose-and-machine/ Most of my code is the same as the tutorial's (https://github.com/realpython/dockerizing-django). with some minor name changes. this my docker-compose.yml (I changed the gunicorn command to runserver for debugging purposes) web: restart: always build: ./web expose: - "8000" links: - postgres:postgres - redis:redis volumes: - /usr/src/app - /usr/src/app/static env_file: .env environment: DEBUG: 'true' command: /usr/local/bin/python manage.py runserver nginx: restart: always build: ./nginx/ ports: - "80:80" volumes: - /www/static volumes_from: - web links: - web:web postgres: restart: always image: postgres:latest ports: - "5432:5432" volumes: - pgdata:/var/lib/postgresql/data/ redis: restart: always image: redis:latest ports: - "6379:6379" volumes: - redisdata:/data And this is in my settings.py of Django: DATABASES = { 'default': { 'ENGINE': 'django.db.backends.postgresql_psycopg2', 'NAME': 'postgres', 'USER': 'postgres', 'PASSWORD': 'postgres', 'HOST': 'postgres', 'PORT': '5432', } } Nginx and postgres (and redis) are up and running, however my django server wont start, by this error: web_1 | django.db.utils.OperationalError: could not connect to server: Connection refused web_1 | Is the server running on host "localhost" (::1) and accepting web_1 | TCP/IP connections on port 5432? web_1 | … -
Mezzanine blog next/previous post filter
I'm trying to make a website with 2 separate mezzanine blogs. I think Mezzanine does not offer this behaviour but a possible turnaround is to separate the content by category for each blog. My question is: Is possible to extend this behaviour to filter the content by category also when using the previous/next buttons to navigate through blog posts. Currently if I go to /blog/category/1 the content listed shows only posts from the category 1. But when clicking on the previous/next buttons the previous/next blog post gets shown regardless of the category.. I would like to stay on that specific category also when using this navigation through blog posts... any ideas? {% block blog_post_previous_next %} <ul class="pager"> {% with blog_post.get_previous_by_publish_date as previous %} {% if previous %} <li class="previous"> <a href="{{ previous.get_absolute_url }}"><i class="fa fa-chevron-left"></i> {{ previous }}</a> </li> {% endif %} {% endwith %} {% with blog_post.get_next_by_publish_date as next %} {% if next %} <li class="next"> <a href="{{ next.get_absolute_url }}">{{ next }} <i class="fa fa-chevron-right"></i> {% endif %} {% endwith %} </ul> {% endblock %} -
Custom User Groups with Role within each
New to Django (1.10.5), and I'm not very clear on how I'd go about a custom User structure and model. I've read and tried this answer and this answer to no avail I'm hoping to accomplish the following: User Director 1 User Division Manager 1A Senior User 1A1 User 1A1-1 User 1A1-2 Senior User 1A2 User 1A2-1 User 1A2-2 User Division Manager 1B Senior User 1B1 User 1B1-1 User 1B1-2 Senior User 1B2 User 1B2-1 User 1B2-2 User Director can: Import / Add (upload) Primary Form A. Edit Primary Form A, B, C format and content of any user. Delete Template Form A, B, C (which removes it from access to lower tier). View ANY OTHER GROUP Completed Form A, B, C. Create User, Senior User, or Division User Manager Edit (promote / demote) any of the above roles except admin and self Edit (transfer) any Senior or User to another Division and rename a Division (i.e. Division A to Division D) User Division Manager can: Edit contents of Form A, B, and C in any group below their level, within their division only. View completed Form A, B, C of any user in any group below their level, within … -
Python Django : item title does not show
I've been working todo application. I get itemsfrom db and do for loop with button which can delete each item in the main.html. I just found that text does not shows but only button shows. Now I have 5 items and there are 5 buttons so I guess it does work, but I wander why item's title and writer does not shows. models.py from datetime import datetime from django.db import models class Article(models.Model): no = models.AutoField(primary_key=True) title = models.CharField(max_length=50) content = models.CharField(max_length=300) writer = models.CharField(max_length=50) is_visible = models.BooleanField() created_date = models.DateTimeField(editable=False, default=datetime.now()) views.py def home(request): items = Article.objects.filter(is_visible=True) return render(request, 'blog/home.html', {'items': items}) home.html {% for title in items %} <div class="item-block"> <p class="item">{{ item.title }} | {{ item.writer }}</p> <form action="{% url 'blog:delete' %}" method="post"> {% csrf_token %} <p><input type="hidden" name="id" value="{{ item.id }}"> <button class="submit-button btn btn-default btn-xs" type="submit">삭제</button></p> </form> </div> {% endfor %} -
CASE WHEN expressions in django and casting in aggregate functions
When I'm trying to do sth like this: data = [Table.objects.filter(nr=form.cleaned_data['id']).aggregate( avg = Avg(Case(When(Q(floatColumn__lt=250)&Q(floatColumn__gt=-250))))] The error appears: function avg(text) does not exist Could I do sth like manual casting in sql ? ROUND(AVG(CASE WHEN residual<250 THEN residual else null end)::numeric,2) Hope you will help me ! Thanks in advance -
i get an error when i run this command python manage.py makemigrations blog in python django in models.py
i get an error when i run this command python manage.py makemigrations blog in python django in models.py from django.db import models from django.utils import timezone class Post(models.Model): author = models.ForeignKey('auth.User') title = models.CharField(max_length=200) text = models.TextField() created_date = models.DateTimeField( default=timezone.now) published_date = models.DateTimeField( blank=True, null=True) def publish(self): self.published_date = timezone.now() self.save() def __str__(self): return self.title class Comment(models.Model): post = models.ForeignKey('blog.Post', related_name='comments') author = models.CharField(max_length=200) text = models.TextField() created_date = models.DateTimeField(default=timezone.now) approved_comment = models.BooleanField(default=False) def approve(self): self.approved_comment = True self.save()`enter code here` def __str__(self): return self.text -
Sitemap and object with multiple urls
The normal way sitemap is done in Django is: from django.contrib.sitemaps import Sitemap from schools.models import School class SchoolSitemap(Sitemap): changefreq = "weekly" priority = 0.6 def items(self): return School.objects.filter(status = 2) and then in the model of School we define: def get_absolute_url(self): return reverse('schools:school_about', kwargs={'school_id': self.pk}) In such implementation I have one About link for one school in sitemap.xml The problem is that my schools has multiple pages: About, Teachers, Pupils and others and I would like all of the to be rendered is sitemap.xml What is the best approach to do it? -
krajee bootstrap-fileinput with django framework
I am trying to use this, krajee bootstrap-fileinput library with Django python framework. I need to pass csrf_token via headers to submit the file via ajax to the server. Where should I put csrf_token? In general, I used to pass as a header in ajax method in jquery. Now I don't understand where should I have to include csrf_token. Do I have to put in fileinput? -
Python django error Required argument 'year 'not found
I am getting this error every time. I google it but cannot find any solution. It is related to user model in django. I saw datetime fix everywhere but the error is coming from django model inside. How to solve it? Applying users.0002_auto_20170212_1420...Traceback (most recent call last): File "manage.py", line 10, in <module> execute_from_command_line(sys.argv) File "C:\Python27\lib\site-packages\django\core\management\__init__.py", line 367, in execute_from_command_line utility.execute() File "C:\Python27\lib\site-packages\django\core\management\__init__.py", line 359, in execute self.fetch_command(subcommand).run_from_argv(self.argv) File "C:\Python27\lib\site-packages\django\core\management\base.py", line 294, in run_from_argv self.execute(*args, **cmd_options) File "C:\Python27\lib\site-packages\django\core\management\base.py", line 345, in execute output = self.handle(*args, **options) File "C:\Python27\lib\site-packages\django\core\management\commands\migrate.py", line 204, in handle fake_initial=fake_initial, File "C:\Python27\lib\site-packages\django\db\migrations\executor.py", line 115, in migrate state = self._migrate_all_forwards(state, plan, full_plan, fake=fake, fake_initial=fake_initial) File "C:\Python27\lib\site-packages\django\db\migrations\executor.py", line 145, in _migrate_all_forwards state = self.apply_migration(state, migration, fake=fake, fake_initial=fake_initial) File "C:\Python27\lib\site-packages\django\db\migrations\executor.py", line 244, in apply_migration state = migration.apply(state, schema_editor) File "C:\Python27\lib\site-packages\django\db\migrations\migration.py", line 129, in apply operation.database_forwards(self.app_label, schema_editor, old_state, project_state) File "C:\Python27\lib\site-packages\django\db\migrations\operations\fields.py", line 84, in database_forwards field, File "C:\Python27\lib\site-packages\django\db\backends\mysql\schema.py", line 43, in add_field super(DatabaseSchemaEditor, self).add_field(model, field) File "C:\Python27\lib\site-packages\django\db\backends\base\schema.py", line 395, in add_field definition, params = self.column_sql(model, field, include_default=True) File "C:\Python27\lib\site-packages\django\db\backends\base\schema.py", line 147, in column_sql default_value = self.effective_default(field) File "C:\Python27\lib\site-packages\django\db\backends\base\schema.py", line 199, in effective_default default = field.get_default() File "C:\Python27\lib\site-packages\django\db\models\fields\__init__.py", line 769, in get_default return self.default() TypeError: Required argument 'year' (pos 1) not found -
AttributeError: 'module' object has no attribute 'views'
I got an error, url(r'^media/(?P.*)$',django.views.static.serve, {'document_root': settings.MEDIA_ROOT}) AttributeError: 'module' object has no attribute 'views' . It happened in urls.py(of my app's child app).I wrote in it like from django.conf import settings from django.conf.urls import include, url from django.conf.urls.static import static from django.contrib import admin urlpatterns = [ url(r'^admin/', admin.site.urls), url(r'^accounts/', include('accounts.urls')), url(r'^api/', include('UserToken.urls')), url(r'^accounts/', include('accounts.urls', namespace='accounts')), url(r'^ResultJSON/', include('ResultJSON.urls')), url(r'^api/1.0/', include('accounts.api_urls', namespace='api')), url(r'^api/1.0/login/', include('accounts.apitoken_urls', namespace='apilogin')), ] +static(settings.MEDIA_URL,document_root=settings.MEDIA_ROOT) When I added +static(settings.MEDIA_URL ~ before ,my app worked well. So,I didn't know how I can fix this. Now I am making Serializer when users logged in my app. -
Using a "full" django development server like xampp with Angular2
after looking for many days and 200 tabs later I still do not know about a more powerful django development server that is available to use that is almost the same as xampp. I have tried to get django to work with xampp, but all the tutorials are at least 5 years old, and all use python2.7 still. So that looked like it was a dead end... I want to combine django (backend) and Angular2 (frontend) for my site, and have a medium sized database that I want to run all my queries against and make sure everything works, and the lightweight django internal server is just not what I think I need. I used xampp and php for a while, which was very nice, but seeing that I know Python, I thought it would be better to get to know Python (and django) even better than to learn another language like php just for the backend. To tell the truth I am more confused now after spending all this time trying to figure out what I need, but in the end I want to use Angular2 with Django and want to run it all from my local server first … -
Can someone help me implement multiple file uplaods
was wondering if anyone could help me implement this into my project! Django Docs on how to upload more than one file Here is my views.py: class PostCreate(TemplateView): form_class = PostForm def post(self, request, *args, **kwargs): template_name = "post_form.html" if not request.user.is_authenticated: return(redirect("posts:post_timeline")) form = self.form_class(request.POST or None, request.FILES or None) if form.is_valid() and request.POST: instance = form.save() return(HttpResponseRedirect(instance.get_absolute_url())) context = { "form": form, } return render(request, "post_form.html", context) Here is my models.py: def upload_location(instance, filename): try: id_ = Post.objects.all().latest('id').id + 1 except ObjectDoesNotExist: id_ = "first_post" return ("{}/{}".format(id_, filename)) class Post(models.Model): post_title = models.CharField(max_length = 120) post_content = models.TextField() last_updated = models.DateTimeField(auto_now=True, auto_now_add=False) post_date = models.DateTimeField(auto_now=False, auto_now_add=True) post_image = models.FileField(upload_to=upload_location, null=True, blank=True) def __unicode__(self): return self.post_title def __str__(self): return self.post_title def get_absolute_url(self): return reverse("posts:post_display", kwargs= {'post_id': self.id}) And here is my forms.py: from django import forms from .models import Post class PostForm(forms.ModelForm): post_image = forms.FileField(widget=forms.ClearableFileInput(attrs={'multiple': True})) class Meta: model = Post fields = ["post_title", "post_content", "post_image"] Any help would be great and I appreciate it! Thanks, Will -
Request ModelForm instance from Django template
I'm stuck with a pretty basic task, but since I'm new to Django i'd love some advice on how to be more Django-esque? I have a pretty basic Campaign model and a ModelForm based on it: class Campaign(models.Model): def __str__(self): return self.name project = models.ForeignKey(Project, on_delete=models.CASCADE) name = models.CharField(max_length=200) start_date = models.DateField(default=now) end_date = models.DateField(blank=True, null=True) date_created = models.DateTimeField(default=now) project = models.ForeignKey(Project) status = models.CharField( max_length=1, choices=STATUS_CHOICES, default=ACTIVE ) class CampaignForm(forms.ModelForm): class Meta: model = Campaign fields = '__all__' I'm presenting the existing campaigns as a table in a template: {% for campaign in all_campaigns %} <tr> <td>{{ forloop.counter }}</td> <td>{{ campaign.name }}</td> <td>{{ campaign.get_status_display }}</td> <td>{{ campaign.start_date }}</td> <td>{{ campaign.end_date }}</td> </tr> {% endfor %} I want to make each row editable. User could click an edit button and the table fields are replaced by relevant inputs that are pre-filled with the campaign data that the user is trying to edit. I could loop through the ModelForm fields and include them in another table row that is initially hidden, use a hidden input for the campaing_id the user is trying to edit and rewrite the post method in the view...and use javascript to get initial campaign data and populate … -
Django: move all previously uploaded media files to new location and rename
So, I'm using Django (1.10) and I've got a few hundred uploaded (media) files. I want to move and rename all the files, because I want to slightly change the folder structure. In my models.py, I do have a perfectly working save() method that saves the files in the correct location, but it only works on new files. I want to move all already-existing files. I hoped that by just calling the save method on all the objects, it would automatically move and rename the files, but that didn't do anything (like I kinda expected). Is there an easy way to do this? I have the feeling I'm overlooking a really straight-forward solution... -
How solve"no python application found check your startup logs" error for Django + uWSGI + nginx stack
I user Django 1.10 with uWSGI and nginx on ubuntu 16.04 and deploy my app with ansible. My project have not default structure, but quite common ( thank Two scoopce for this :). I use split dev and production settings and config folder instead 'name' project folder. It's looks like this: |-- config | |-- __init__.py | |-- settings | | |-- __init__.py | | |-- base.py | | `-- dev.py | |-- urls.py | |-- wsgi_dev.py | `-- wsgi_production.py |-- manage.py `-- requirements.txt My production.py genarate from ansible with security encrypt and locate in config/settings. With this config i get "no python application found check your startup logs". Uwsgi don't see my application. ( {{ }} it's jinja2 syntax for ansible ) /etc/uwsgi/sites/{{ project_name }} [uwsgi] chdir = {{ django_root }} home = /home/{{ project_user }}/venvs/{{ project_name }} module = config.wsgi_production:application master = true processes = 5 socket = /run/uwsgi/{{ project_name }}.sock chown-socket = {{ project_user }}:www-data chmod-socket = 660 vacuum = true -
I try to push my site to Heroku, but I got these errors.
I tried to push this to Heroku site, I can run it locally without any problems so far. But when I pushed it to Heroku, I got these errors. I don't understand these errors, I tried to search the internet for these errors code. unfortunately, I couldn't find anything about it. If you know something about this please help me find a solution for this. Thanks. This is a error that I got when I tried to link to my page in Heroku domain. Environment: Request Method: GET Request URL: https://pawkanstyleblog.herokuapp.com/ Django Version: 1.10.5 Python Version: 3.5.2 Installed Applications: ['django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'web.firstpage', 'django_ajax'] 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'] Template error: In template /app/web/firstpage/templates/firstpage/index.html, error at line 47 relation "firstpage_project" does not exist LINE 1: ..."."create_date", "firstpage_project"."image" FROM "firstpage... ^ 37 : </h1> 38 : <h1 class="text-center hidden-md-up" >PROJECTS</h1> 39 : <i class="fa fa-grav fa-5x pl-4 hidden-sm-down" aria-hidden="true" ></i> 40 : </div> 41 : <div class="row"> 42 : <div class="col-md-12 pt-4"> 43 : <div class="card-columns"> 44 : 45 : {% load tz %} 46 : 47 : {% for project in projects %} 48 : 49 : <a href="{% url 'firstpage:detail' project.pk %}"> … -
How to extend Django CMS template?
I want to use a base template and then extend partial views. extends not working as it is not showing base markup at all. -
How to insert data in mysql db using sqlalchemy from django framework?
I am new in django framework and I am trying to make an api for "register" where i want to insert data into db after execution but unable to do so . I am trying to create the object of auth_user and trying to do session.add(auth_user_object) but it is not giving any error and even not adding datato mysql db. please help me. what is best approach to do so. -
Would you recommend Python or NodeJS for creating real-time web service?
I want to create a web application, which is real-time in nature (dashboard). I am seeking suggestions regarding what stack should I choose for the project in order to maintain it in long run, considering the time and complexity of maintaining the project, maintaining API. Here are some of my requirements: Realtime updates on dashboard about recent events. Proper API for the service. Focus on the problem, rather than handling configurations and tweaking. The problem : I am confused about my choices, and find it hard to take decision that would help me in long run. Here are some things I have figured out after research: Both Python and NodeJS have frameworks (SocketIO, Greenlets, Twisted, etc.) for websockets. However, the support for asynchronous processing is better in JavaScript. Callback hell may suck. In fact, you cannot expect the return value of a function for all calls are asynchronous (there are Promises). However, one has to follow decent programming practices. Python gives you more control over the code and is easier to maintain. Javascript for me has been notorious for surprises, breaking things after few updates. The community is moving fast, but that may be too fast for enterprise level applications. … -
How do I use Django Dynamic Formset and Select2 together in the same page?
I have successfully used Django Dynamic Formset and Select2 separately. However, when I am using select2 and adding more forms in my formset dynamically, the added forms wouldn't work for the dropdowns. I click on them but the dropdowns wouldn't open. <script type="text/javascript"> $(function() { $('.trt').formset(); }); $('select').select2(); </script> How can I edit the above code so that select2 works for my added forms? -
django group by aggregation on different choice field
i have following table, Account(models.Model): name = models.CharField(max_length=60) account_type = models.CharField(choices=ACCOUNT_TYPE, max_length=30) Ledger(models.Model): account = models.ForeignKey(Account, related_name='ledger') balance = models.DecimalField(max_digits=15, decimal_places=4, default=0.00) balance_date = models.DateField(default=datetime.date.today) In mention , Account types are , ACCOUNT_TYPE = ( (0, 'Asset'), (1, 'Liabilities'), (2, 'Equity'), (3, 'Income'), (4, 'Expense') ) i want to get total balance of all Income and Expense type account within a date range, i have tried so, if request.method == 'GET': start_date = request.GET.get('start_date') end_date = request.GET.get('end_date') accounts = Account.objects.filter(Q(account_type=3) | Q(account_type=4)) income = Ledger.objects.filter( account__in=accounts, balance_date__gte=start_date, balance_date__lte=end_date ).aggregate(Sum('balance')) serializer = LedgerSerializer(income, many=True) print serializer.data return Response(serializer.data}) but its returning a empty querydict, i am assuring that i have data within the date range i am passing, if i remove the aggregation part from the above query , its return all the Income and Expense data without having total balance, which is logical but when i add aggregation part, its returns [OrderDict()] i am relatively new in django orm.