Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Django - is it possible to include two templates with different styles?
I created a template on my Django app, it uses it's own CSS files and its own style. Now i would like to add on top of this template my own navbar that i'm using on the rest of the app. The problem is that the navbar has its own styles, and the template has its style too, so mixing them messes up both the navbar and the rest of the template. I thought that using include instead of extends would fix my problem, but the i problem is that when i try with template.html {% include 'navbar.html' %} ... the two parts will still collide. Is there any way to import an element in a template without applying all the styles of the element to the rest of the template in Django? Or is mine a CSS problem and i should solve it there? Any kind of advice is appreciated. -
Django CSS HTML Not Applying
I am new to Django and am currently trying to customize the aesthetics of my polling app. I cannot get my style sheet to apply to my polling app. Specifically, I am looking to change the fonts/color of the questions/h1 tag as well as adding in a background image. The background remains white, and the links do not reflect the style.css file. Any ideas what I am doing wrong? polls/style.css li a { color: red; font-family: 'Lobster'; } body { padding-left: 15px; background-image: white url({%static 'C:\Users\xxxx\Python\Price Tracking\Django\mysite\polls\static\polls\images\sample123.jpg'%}) repeat; } index.html <head> <title>Polling</title> <link href="//fonts.googleapis.com/css?family=Lobster&subset=latin,latin-ext" rel="stylesheet" type="text/css"> <link rel="stylesheet" href="{% static 'polls/style.css' %}"> </head> <body> <div> <h1><a href="https://www.google.com">Welcome to the polling app!</a></h1> </div> <!-- Question List --> {% if latest_question_list %} <ul> {% for question in latest_question_list %} <li><a href="{% url 'polls:detail' question.id %}">{{ question.question_text }}</a></li> {% endfor %} </ul> {% else %} <p>No polls are available.</p> {% endif %} </body> -
One-to-One and One-to-Many relation to the same model with same reverse accessor
I have an order model with a one to many relation to a OrderDate Model. Now I want have an additional field on order named 'chosen_date' with a one to one relation to the same OrderDate Model. The Problem is that my relations at OrderDate both have the name 'order', which clashes. How can I solve this problem without adding a new field like 'Order_2' on the OrderDate Model? Here are my models: class Order(TimeStampedModel): chosen_date = models.OneToOneField('OrderDate', on_delete=models.CASCADE, blank=True, null=True) class OrderDate(TimeStampedModel): order = models.ForeignKey(Order, related_name='dates', on_delete=models.CASCADE) date = models.DateField() morning = models.BooleanField(default=False) noon = models.BooleanField(default=False) evening = models.BooleanField(default=False) -
Image doesn't load fully at first, only after refresh
I made a django application which is online at: https://www.casualspotter.com/. On my homepage I have a carousel with multiple images. The problem I'm having is that for some reason the images don't load fully. After refreshing the page the images do load fully. The carousel code: <div class="carousel carousel-slider" id="demo-carousel-content" data-indicators="true" > <a class="carousel-item" href="/cp_company"> <img class='carouselitem' src="{% static 'images/cp_company.jpg' %}"> <h2 class="bottom-left">C.P. COMPANY</h2> </a> <a class="carousel-item" href="/stone_island"> <img class='carouselitem' src="{% static 'images/stone_island.jpg' %}"> <h2 class="bottom-left">STONE ISLAND</h2> </a> <a class="carousel-item" href="/ma_strum"> <img class='carouselitem' src="{% static 'images/mastrum.jpg' %}"> <h2 class="bottom-left">MA.STRUM</h2> </a> <a class="carousel-item" href="/barbour"> <img class='carouselitem' src="{% static 'images/barbour_lookbook.jpg' %}"> <h2 class="bottom-left">BARBOUR</h2> </a> <a class="carousel-item" href="/lacoste"> <img class='carouselitem' src="{% static 'images/lacoste_banner.jpg' %}"> <h2 class="bottom-left">LACOSTE</h2> </a> <a class="carousel-item" href="/perry"> <img class='carouselitem' src="{% static 'images/perry_banner.jpg' %}"> <h2 class="bottom-left">FRED PERRY</h2> </a> <a class="carousel-item" href="/paul_shark"> <img class='carouselitem' src="{% static 'images/paul_shark_banner.jpg' %}"> <h2 class="bottom-left">PAUL & SHARK</h2> </a> <a class="carousel-item" href="/napa"> <img class='carouselitem' src="{% static 'images/napa_banner.jpg_large' %}"> <h2 class="bottom-left">NAPAPIJRI</h2> </a> <a class="carousel-item" href="/tnf"> <img class='carouselitem' src="{% static 'images/tnf_banner.jpg' %}"> <h2 class="bottom-left">THE NORTH FACE</h2> </a> </div> CSS: img.carouselitem{ height: auto; } Thanks in advance! -
Order of Operations Django Templates
I have a float variable mynumber in Django templates, and I need to round it to the nearest integer without third party filters, so I'm following this logic: int(mynumber - 0.5) + 1 In Django templates I can do this: {{ mynumber|add:"-0.5"|add:"1" }} But the problem, as you can see, is that there is no order of operations, so I get a different number than the expected, how can I solve this? I haven't found a way of putting parenthesis, and also I need to convert to integer after the first operation. -
How can I make this Function Based View work?
views.py from django.views.generic.detail import DetailView from django.shortcuts import redirect from django.urls import reverse from django.contrib.auth.decorators import login_required class RoomDetail(DetailView): """ RoomDetail Definition """ model = models.Room ........ #omitted ........ @login_required def delete_room(request, room_pk): user = request.user user_pk = user.pk try: room = models.Room.objects.get(pk=room_pk) if room.host.pk != user.pk: messages.error(request, "Can't delete the Room") else: room.delete() messages.success(request, "Room Deleted") return redirect(reverse("users:profile", kwargs={"pk": user_pk})) except models.Room.DoesNotExist: return redirect(reverse("core:home")) users/urls.py from django.urls import path from . import views app_name = "users" urlpatterns = [ ....... #omitted ....... path("<int:pk>/", views.UserProfileView.as_view(), name="profile"), ] html ........ <-- omitted --> ........ <div class="mt-1 mb-3 sm:my-0 w-full sm:w-1/3"> {% if room.host == user %} <a href="{% url 'rooms:edit' room.pk %}" class="btn-link block mb-3 bg-green-500">Edit Room</a> <a href="{% url 'rooms:delete' room.pk %}" class="btn-link block">Delete Room</a> <div class="w-full text-center"> <span class="font-extrabold mx-auto mt-px text-yellow-600" >WARNING!!! THIS ACTION IS NOT RETRIEVABLE!!</span> </div> {% endif %} </div> ........... <-- omitted --> ........... In the code above, I've tried to make "Delete Room" anchor function, whose function is deleting room and redirect users to their profile, if they are the owner of the room. But clicking that "Delete Room' didn't function as I expected, just turning back the error below to me. And I … -
Django’s command-line utility | manage.py: command not found
I'm new to Django and trying to use manage.py instead of django-admin command as Django's documentation mentioned (https://docs.djangoproject.com/en/3.1/ref/django-admin/) so from what I learned, I can use these interchangeably. $ django-admin <command> [options] $ manage.py <command> [options] $ python -m django <command> [options] So my problem is when I use manage.py , the terminal says: manage.py: command not found Where is the problem? -
Image is not updating in Django
Please help me. I am trying to update the profile in which username and email are updated but the image dose not. My code is.... profile.html {% extends "blog/base.html" %} {% load crispy_forms_tags %} {% block content %} <div class="content-section"> <div class="media"> <img class="rounded-circle account-img" src="{{ user.profile.image.url }}"> <div class="media-body"> <h2 class="account-heading">{{ user.username }}</h2> <p class="text-secondary">{{ user.email }}</p> </div> </div> <form method="POST" enctype="multipart/form-data"> {% csrf_token %} <fieldset class="form-group"> <legend class="border-bottom mb-4">Profile Info</legend> {{ u_form|crispy }} {{ p_form|crispy }} </fieldset> <br> <div class="form-group"> <button class="btn btn-outline-info" type="submit">Update</button> </div> </form> </div> {% endblock content%} -
Django tag on template
My code: {% if request.user.is_staff %} {% extends "base.html" %} {% load crispy_forms_tags %} {% block content %} <div class="content-section"> <form method="POST"> {% csrf_token %} <fieldset class="form-group"> <legend class="border-bottom mb-4"> Create A Post </legend> {{ form|crispy }} </fieldset> <div class="form-group"> <button class="btn btn-outline-info" type="submit"> Post </button> </div> </form> </div> {% endblock content %} {% else %} <head> <meta http-equiv="refresh" content="5; url=/" /> </head> <body> <h1>Restricted Access To Staff!</h1> <p>You will be redirected to the home page in 5 seconds</p> </body> {% endif %} The Error: I can't figure out why it is not working, could it be something to do with the {% if request.user.is_staff %} bit? -
Change "python manage.py" to "./manage.py"
I want to short python manage.py to ./manage.py. Maybe simple question but could not find an answer for this (maybe googled wrongly). I saw step by step method in one of the answers for questions about django but I did not memorize that. Tried to search answers to questions on stackoverflow that I have been entered but no result. Any help would be appreciated. -
How to check witch user is logged in with django?
Hi there I am currently working on a website, and I wanted to know how do I check witch user is logged in. Just to clarify I am using the django build in models from django.contrib.auth.models import User to do my login, logout etc. What I don't know how to do is check witch user is logged in, I know the method if user.is_authenticated: # Other code goes here But this method only checks weather the user is logged in not witch user is logged in? can anyone tell me the solution to this problem, thank you in advance. -
Displaying / Testing outputs are correct. Sanity Check
I am still learning Django and slowly improving but I have a few questions, I have my whole model below: from django.db import models from datetime import datetime, timedelta # Create your models here. year_choice = [ ('year1','1-Year'), ('year3','3-Year') ] weeksinyear = 52 hours = 6.5 current_year = datetime.year class AdminData(models.Model): year1 = models.IntegerField() year3 = models.IntegerField() @property def day_rate_year1(self): return self.year1 / weeksinyear / hours class Price(models.Model): name = models.CharField(max_length=100) contract = models.CharField(max_length=5, choices=year_choice) start_date = models.DateField(default=datetime.now) end_date = models.DateField(default=datetime(2021,3,31)) def __str__(self): return self.name The main concern for me at the moment is trying to understand if my function def day_rate_year1(self): is working correctly, if someone could point me in the right direction to understand either how I display this as a string value in a template or test in the shell to see if the value pulls through as the values for year1 and year3 can change based on user input. I am trying to work out the day rate so I can then use the start and end dates and work out the number of days between the two to calculate a price which is then displayed to the user which can again change depending on the … -
TypeError and NoReverseMatch in django
When i go to /projects i get NoReverseMatch at /projects/ Reverse for 'detail' not found. 'detail' is not a valid view function or pattern name. when i go to /projects/some number i get TypeError at /projects/1/ 'Project' object is not iterable path main migrations templates detail.html home.html proceed.html project.html __init_.py admin.py apps.py models.py tests.py views.py portfolio __init_.py asgi.py settings.py urls.py wsgi.py db.sqlite3 manage.py views.py from django.shortcuts import render, get_object_or_404 from .models import Project # Create your views here. def home(request): return render(request, "home/home.html") def project(request): projects = Project.objects.all() return render(request, "home/project.html", {'projects':projects }) def detail(request, project_id): oof = get_object_or_404(Project, pk=project_id) return render(request, 'home/detail.html', {'projectss': oof}) detail.html <!DOCTYPE html> <html> <head> <meta charset="utf-8"> <meta name="viewport" content="width=device-width, initial-scale=1"> <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/4.7.0/css/font-awesome.min.css" type="text/css"> <link rel="stylesheet" href="https://static.pingendo.com/bootstrap/bootstrap-4.3.1.css"> </head> <body > <div class="py-5" style=" background-image: linear-gradient(to bottom, rgb(0, 0, 0), rgb(0, 0, 0)); background-position: center center; background-size: 100%; background-repeat: repeat;"> <div class="container"> <div class="row"> <div class="text-center mx-auto col-md-12"> <h1 class="text-light">Proceed to external site</h1> </div> </div> </div> </div> <div class="py-5 text-center" style=" background-image: linear-gradient(to bottom, rgb(0, 0, 0), rgb(0, 0, 0)); background-position: top left; background-size: 100%; background-repeat: repeat;"> <div class="container"> <div class="row"> {% for project in projectss %} <div class="mx-auto col-lg-5 col-md-7 col-10"> <h1 class="text-white mb-5">{project.title}</h1> … -
How do I use POST request and filter() for field lookup and return a dataset through an html page?
I want to get the values of attributes 'skill_required' and 'desired_level' from a user, filter the DB according to these values and send the matching rows of data through the html page 'emptracker.html' Problem is, I can't figure out how to send this data through the html template emptracker. The code for the view page is below: def emptracker(request): if request.method == 'POST': skill_required = request.POST['skill_required'], desired_level = request.POST['desired_level'] from app8.models import empskillmapping orgdata = empskillmapping.objects.filter(skill_required = skill_required).filter(desired_level = desired_level) **return render(request, 'emptracker.html',{'data': orgdata})** I encounter an error here saying that orgdata is out of scope, I just can't figure out how to render this data. emphasized text class empskillmapping(models.Model): skill_required = models.CharField(max_length=20) desired_level = models.ForeignKey(level,on_delete=models.CASCADE,default="", editable= True) department_id = models.ForeignKey(department,on_delete=models.CASCADE,default="", editable= True) This is the model I want to search. -
Django internationalization does not work
Hello guys it's me again and for this question i scruwed so bad. I've started to do django's internationalization and it doesn't work i couldn't find anything about my problem here is my codes: settings.py: MIDDLEWARE = [ ... 'django.contrib.sessions.middleware.SessionMiddleware', 'django.middleware.locale.LocaleMiddleware', 'django.middleware.common.CommonMiddleware', ... ] LANGUAGE_CODE = 'tr' TIME_ZONE = 'Europe/Istanbul' USE_I18N = True USE_L10N = True USE_TZ = True LOCAL_PATHS = { os.path.join(BASE_DIR, 'locale') } urls.py from django.contrib import admin from django.urls import path from django.urls.conf import include from product import views from django.conf.urls.i18n import i18n_patterns from django.conf import settings from django.conf.urls.static import static urlpatterns = [ path('admin/', admin.site.urls), ] urlpatterns += i18n_patterns( path('', views.index, name="index"), ... path('about/', views.about,name="about-en"), ... prefix_default_language = False, )+ static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT) views.py def about(request): abouts = Hakkimizda.objects.first() return render(request,"about.html",{"abouts":abouts}) about.html (i just did this for see how it work but it didn't work) <h2> {% translate "denseme" %}</h2> django.po ... #: .\templates\about.html:5 .\templates\about.html:11 msgid "denseme" msgstr "abc" -
Django Import CSV KeyError
I'm getting this error. I can't figure out why. This has worked fine before. I don't recall making any changes that would cause this to happen. When I try to upload a .csv to my database: KeyError at /upload/ .....\views.py line 112, in post objs = [ <------ line 112 .....\views.py line 114, in listcomp description=row['description'], <-------- line 114 Here is my view class UploadView(View): def get(self, request): template_name = 'crmapp/upload.html' return render(request, template_name) def post(self, request): user = request.user # get the current login user details paramFile = io.TextIOWrapper(request.FILES['uploadfile'].file) portfolio1 = csv.DictReader(paramFile) list_of_dict = list(portfolio1) objs = [ Product( description=row['description'], costprice=row['costprice'], retailprice=row['retailprice'], barcode=row['barcode'], ) for row in list_of_dict ] try: msg = Product.objects.bulk_create(objs) returnmsg = {"status_code": 200} print('imported successfully') except Exception as e: print('Error While Importing Data: ', e) returnmsg = {"status_code": 500} return JsonResponse(returnmsg) models.py class Product(models.Model): description = models.CharField(max_length=30) costprice = models.FloatField(null=True, max_length=99, blank=True) retailprice = models.FloatField(null=True, max_length=99, blank=True) barcode = models.CharField(null=True, max_length=99, unique=True, blank=True) image = DefaultStaticImageField(null=True, blank=True,default='images/item_gC0XXrx.png') supplier = models.ForeignKey(Supplier, on_delete=models.CASCADE, null=False, blank=False) and this is the template upload.html <form method="post" enctype="multipart/form-data"> {% csrf_token %} <input type="file" name="uploadfile"> <hr> <br> <button type="submit" class='btn btn-success'>Upload</button> </form> -
django rest frame work with react using webpack
i successfully connected DRF to react after seeing the posting. https://www.valentinog.com/blog/drf/ but real-time screen update is not possible when the server is run in development mode by typing the phrase. "webpack --mode development ./src/index.js --output-path ./static/frontend/main.js" -
How can I record form responses in Django
I'm attempting to record an answer to a basic y/n question and send it from HTML to a Django view. This is my html code: form.html <form method="POST"> {% csrf_token %} <div id="drinks"> <a class="prev" onclick="plusSlides(-1)">&#10094;</a> <a class="next" onclick="plusSlides(1)">&#10095;</a> <label> <div class="mySlides" style="display: block;"> <img src="{{ prof_pic }}" alt="image alt text" width="100" height="100"/> <div> <select name="dance_or_no" required> <option value = "" disabled="disabled" selected="selected">Ques.</option> <option value = "yes">Yes :)</option> <option value = "no">No :(</option> </select> </div> </div> </label> </div> <input type="submit" value="Submit" class="drink-it"> </form> Once the user submits this form it gets sent to auth in views.py def auth(request): if request.method == 'POST': dance_or_no = request.POST.get('dance_or_no', False) request.session['dance_or_no'] = dance_or_no print('authenticated!!') return redirect(client.generate_auth_url()) def callback(request): dance_or_no = request.session.get('dance_or_no) This route authenticates the user, which is mandatory for the website to work. So the form answers are also directed here. I am attempting to record the answer and create a session cookie to send to another view. But this dance_or_no value always gets a None value. I have done this in flask. And it worked this way, but now when I'm migrating to Django I can't seem to understand the way one can save an option form and send it from one … -
Django/PostgreSQL Project unable to run due to 'missing' libssl file
I'm trying to set up a local version of a web project made with Django and PostgreSQL. However, when I'm trying to 'run' it (makemigrations, runserver..) I get the following errors: ImportError: dlopen(/Users/my_username/Library/Python/3.8/lib/python/site-packages/psycopg2/_psycopg.cpython-38-darwin.so, 2): Library not loaded: libssl.1.1.dylib Referenced from: /Users/my_username/Library/Python/3.8/lib/python/site-packages/psycopg2/_psycopg.cpython-38-darwin.so Reason: image not found During handling of the above exception, another exception occurred: raise ImproperlyConfigured("Error loading psycopg2 module: %s" % e) django.core.exceptions.ImproperlyConfigured: Error loading psycopg2 module: dlopen(/Users/quentinbackaert/Library/Python/3.8/lib/python/site-packages/psycopg2/_psycopg.cpython-38-darwin.so, 2): Library not loaded: libssl.1.1.dylib Referenced from: /Users/quentinbackaert/Library/Python/3.8/lib/python/site-packages/psycopg2/_psycopg.cpython-38-darwin.so Reason: image not found I haven't included the full Traceback for readability reasons, but if needed I'll include it. Openssl, PostgreSQL and the psycopg2 module seems to be installed properly. I did the following command: ls /usr/lib | grep "ssl" libboringssl.dylib libssl.0.9.7.dylib libssl.0.9.8.dylib libssl.35.dylib libssl.43.dylib libssl.44.dylib libssl.46.dylib libssl.dylib So i think the file in the proper version (1.1) is missing or not in the right place. I checked several other posts with the same issues, but wasn't able to solve the problem. I'm pretty new to this so I'm a bit confused on what I should do. I'm on MacOS Catalina. -
Exception while using threading library in Django
I have been experiencing some issues while using basic threading in Django Here is my script from threading import Thread def run_threads(msg1, msg2): class Hello(Thread): def run(self): for i in range(500): print(msg1) class Hi(Thread): def run(self): for i in range(500): print(msg2) t1 = Hello() t2 = Hi() t1.start() t2.start() t1.join() t2.join() print("Here") But upon running, it is giving me following error somethingException in thread Exception in threading.excepthook:Exception ignored in thread started byException ignored in sys.unraisablehookis cookingException in thread Exception in threading.excepthook:E xception ignored in thread started byException ignored in sys.unraisablehookHere But if I run it in Python3 console without Django, it works alright. Any help would be highly appreciated Information on my system: Python: 3.8 Django: (3, 1, 4, 'final', 0) -
Django migrate AttributeError: 'str' object has no attribute '_meta'
After doing some extensive changes in the DB schema, I ran makemigrations. It created migrations successfully. But then migrate failed with: AttributeError: 'str' object has no attribute '_meta' This is the code that I changed. I split up the Many to Many model for Hardskills from one through table to 2 different through table for users and jobs. Initial class Hardskills(models.Model): user = models.ManyToManyField(User, related_name="user_hs",through="HardskillsProfile") job = models.ManyToManyField(Job, related_name="job_hs",through="HardskillsProfile") hardskills = models.CharField(max_length=100, db_index=True) def __str__(self): return self.hardskills class HardskillsProfile(models.Model): """Through Model for Many to Many relationship for user/jobs and hardskills""" user = models.ForeignKey(User, on_delete=models.CASCADE, related_name="user",null=True) job = models.ForeignKey(Job, on_delete=models.CASCADE, related_name="job",null=True) hardskills = models.ForeignKey(Hardskills, on_delete=models.CASCADE) Final after changes from attributes.models import Category from django.contrib.auth.models import User from content.models import Job from django.db import models class Hardskills(models.Model): user = models.ManyToManyField(User, related_name="user_hs",through="UserHardskillsProfile") job = models.ManyToManyField(Job, related_name="job_hs",through="JobHardskillsProfile") hardskills = models.CharField(max_length=100, db_index=True) def __str__(self): return self.hardskills class UserHardskillsProfile(models.Model): """Through Model for Many to Many relationship for user and hardskills""" user = models.ForeignKey(User, on_delete=models.CASCADE, related_name="user",null=True) hardskills = models.ForeignKey(Hardskills, on_delete=models.CASCADE) class JobHardskillsProfile(models.Model): """Through Model for Many to Many relationship for user/jobs and hardskills""" job = models.ForeignKey(Job, on_delete=models.CASCADE, related_name="job",null=True) hardskills = models.ForeignKey(Hardskills, on_delete=models.CASCADE) Error Logs Operations to perform: Synchronize unmigrated apps: messages, rest_framework, staticfiles Apply all migrations: accounts, … -
How can I get kwargs values in redirected view
I'm trying to send user to "payment view" after user register. here is what i try: ''' def dispatch(): ...... #user registration code ... #then i want to send email to redirected page new_user_email =form.cleaned_data.get('email') print("user registration complete") else: message = form.errors messages.error(request, message) print('form not verified '+ str(form.errors)) return redirect(reverse('account:payment'),kwargs = {'email': new_user_email}) ''' url: ''' path('payment/', views.PaymentView.as_view(), name = 'payment'), ''' and after go to payment view i want to get email in this view. ''' class PaymentView(TemplateView): ''' For Payment related information and proceed to get new subscription. ''' template_name = 'home/payment.html' def get_context_data(self,*args, **kwarg): context = super().get_context_data(*args, **kwarg) .... # here i need email # context['email'] = return context ''' how can i do it? -
Creating API for existing Django project
I have made a project using Django and haven't written any APIs for that yet. But, Now I want to write the APIs for the same (for maybe React or mobile app) and I'm wondering do I have to rewrite all the complex views to create the APIs. I'm new with this, what should be the approach to create APIs for the existing Django code? -
Does rest_framework.test library generate an external database?
The question pretty much sums itself up, when running tests Djangos testing framework generates an external database and then deletes it when tests are completed, my question is: Does DRFs testing framework do the same or does it run tests against existing database? -
filter multiple date rannge and use them precisely django
This is my models class AccountTransactions(models.Model): advertiser_id = models.ForeignKey('Advertisers', on_delete=models.CASCADE,null=True, db_column='advertiser_id', related_name='transactions') amount = models.DecimalField(max_digits=13, decimal_places=4, blank=True, null=True) description = models.CharField(max_length=100, blank=True, null=True) open_balance = models.DecimalField(max_digits=13, decimal_places=4) balance = models.DecimalField(max_digits=13, decimal_places=4) appnexus_charges = models.DecimalField(max_digits=13, decimal_places=4, blank=True, null=True) commision = models.DecimalField(max_digits=13, decimal_places=4, blank=True, null=True) transaction_date = models.DateTimeField() topup_transaction_id = models.CharField(max_length=100, blank=True, null=True) tnc_accepted_flag = models.IntegerField(blank=True, null=True) What i want to do is : 1)find balance for starting date of current month and ending date of current month 2)find balance for starting date of previous month and ending date of previous month I have written code for the same but there are two issues with the code: 1)Multiple times firing query i.e one for current month and one for other month. 2)I am filtering using start_date and end_date and then checking balance between the date range, but if there is no entry for that month in database it will output 0 but my api should output last transaction value in entry. My code: class AdvertiserAccountViewset(viewsets.ViewSet): """ Account transaction details of advertiser""" def retrieve(self, request, pk=None, format=None): start_date = request.query_params.get('start_date') end_date = request.query_params.get('end_date') res_data = {} res_data["advertiser_name"] = adv_name first_date_month = str(datetime.date.today())[:-2] + "01" today = datetime.date.today() first = today.replace(day=1) pre_first_date = str(first …