Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Celery cannot connect to RabbitMQ server
I am trying to run celery and it is unable to connect to the RabbitMQ server even though I have correctly set the user, vhost and assigned the appropriate tags celery -A proj worker -l info The above command returns the error [2021-09-28 18:05:37,649: ERROR/MainProcess] consumer: Cannot connect to amqp://test:**@12:5672//: timed out. Trying again in 2.00 seconds... (1/100) I have initialized the celery app as follows app = Celery('proj', broker=f'amqp://test:test@12#4@localhost/test_vhost') I believe this is not working because the password test@12#4 has the special characters @ and # in it. How do I get this to work without changing the password. -
Django filter two records and update both at once?
I need to filter two data's and then update each data with different value ! How to do that at once ? x = Tasks.objects.filter(employee=[person1]) y = Tasks.objects.filter(employee=[person2]) Basically am updating count, for instance lets say i have a model named "Employee" and he is assigned to tasks with model named "Task". And whenever admin adds employees to a task - the employee gets to see the count of total task. With this said, i have managed to update the count by "1" when tasks gets added and managed to updated the count by "-1" when its get deleted, but my problem is when tasks gets updated or edited or assigned to another employee ! Now am updating the task using: x.update(total_task=F('total_task') + 1) and again y.update(total_task=F('total_task') - 1) From the above, first i filter each separately and then update separately ! How to combine this in a single query ? -
I am not able to submit the form and put the data in Database in a django website
I am fairly new to jquerry, infact just started learning and using it. I went through some of the questions but none talks about the issue I am facing so here it goes. I have created a website in django. In it i basically make a invoice and put that data into a sql server db and then fetch that data and render it to another html template and then print it from there. earlier i wasnt using a jquerry in the html. that time it worked all fine. now i decided that i will use the jquerry to append rows instead of having a fixed amount of rows. when i started using that it started giving trouble. now my input tag thats set on submit is not submitting the form, or thats what i think is happening. Can someone please help me out here. the following contains my part of the view which is working on this, the html and the urls file. views.py def invoice(request): if request.method == "POST": name_client = request.POST.get('client_name') address_client = request.POST.get('client_address') name_company = request.POST.get('company_name') address_company = request.POST.get('company_address') vessel_name = request.POST.get('vessel_name') po = request.POST.get('po') date = request.POST.get('date') item1 = request.POST.get('product1') cost1 = int(request.POST.get('cost1')) gst1 = … -
django debug toolbar uploaded badly
just starting using Django (first project) and I wanted to install the Django Debug Toolbar. I did exactly as the installation guide in the documentation here said: Django Debug Toolbar Docs- Installation For some reason the page loads like this: The html file that is loaded is a simple but legit one and ill add it here: <html> <body> {% if name %} <h1>Hello {{name}}</h1> {% else %} <h1>Hello World</h1> {% endif %} </body> BTW: Removing the if statements is not working either, also not working on both chrome and firefox. Thanks for the help :) -
Django image is uploaded to server but after showing 500 error without saving image information to db
In my settings `Debug = False Allowed_Host = ['my given host'] STATIC_URL = "/static/" STATIC_ROOT = os.path.join(BASE_DIR, 'static') MEDIA_URL = "/images/" MEDIA_ROOT = os.path.join(BASE_DIR, "static/images") in Project Url urlpatterns += static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT) in /etc/nginx/conf.d location /static/ { root /home/pijush/website/ecomerce; } location /images/ { # media files, uploaded by users client_max_body_size 100M; root /home/pijush/website/ecomerce; # ending slash is required } location / { include proxy_params; proxy_pass http://unix:/run/gunicorn.sock; }` static files are serving perfectly. When Debug is True in localhost image is uploading and saving image info in model, working perfectly but in production after uploading image its showing 500 error. this is my gunicorn status log POST HTTP/1.0" 500 145 "https://nobann.com/profile/" "Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/93.0.4577.82 Safari/537.36" -
Why is unique=True not enforced when using create()?
I have a model with a unique charfield: class EmailTemplate(models.Model): name = models.CharField('Name', max_length=255, help_text=_("e.g: 'welcome_email'"), unique=True) When I create 2 models with the same name in Django's admin interface, I get the expected error: Email Template with this Name already exists.. However, if I do this programmatically I do not: >>> EmailTemplate.objects.create(name='test_1') <EmailTemplate: test_1 > >>> EmailTemplate.objects.create(name='test_1') <EmailTemplate: test_1 > What am I missing? I thought unique was a db-level constraint? -
Get all values from queryset using templates
I am trying to retrieve all the queryset data (names and amount) using templates. views.py def get_expense(request): #expenses = list(Expense.objects.values()) expenses = Expense.objects.values('name' , 'amount') if request.method == 'POST': form = ExpenseForm(request.POST, request.FILES) if form.is_valid(): post = form.save(commit=False) post.save() #print(driver_text) print(type(expenses)) return render(request, 'thanks.html', {'expenses':expenses}) #JsonResponse(expenses, safe=False) # else: form = ExpenseForm() return render(request, 'index.html',{'form':form}) thanks.html: {{ expenses }} I am trying to get all those queryset data listed but instead I am getting: <QuerySet [{'name': 'Home Rent', 'amount': 8000.0}, {'name': 'hjvhjvhv', 'amount': 73.0}, {'name': 'tes', 'amount': 23.0}, {'name': 'dddd', 'amount': 34.0}, {'name': 'qqqqqqqq', 'amount': 56.0}, {'name': 'dddddddddd', 'amount': 34.0}, {'name': 'dddddddddxxxxxxxx', 'amount': 34.0}, {'name': 'dddddddddd', 'amount': 34.0}, {'name': 'dddddddddd', 'amount': 34.0}, {'name': 'dddddddddxxxxxxxx', 'amount': 56.0}, {'name': 'dddddddddxxxxxxxx', 'amount': 56.0}, {'name': 'dddddddddxxxxxxxx', 'amount': 56.0}, {'name': 'dddddddddxxxxxxxx', 'amount': 56.0}, {'name': 'dddddddddxxxxxxxx', 'amount': 56.0}, {'name': 'new', 'amount': 45.0}, {'name': 'new', 'amount': 45.0}, {'name': 'new', 'amount': 45.0}, {'name': 'new', 'amount': 45.0}, {'name': 'new', 'amount': 45.0}, {'name': 'hjvhjvhv', 'amount': 67.0}, '...(remaining elements truncated)...']> I need only the name and amount listed instead of the whole queryset. -
ValueError: Cannot assign "'x'": "x.x" must be a "x" instance
I am trying to create some comments on a venue in my web app but I am mot sure why I am getting this error when I try and pass a venue's id through to make a new comment object models: class mapCafes(models.Model): id = models.BigAutoField(primary_key=True) cafe_name = models.CharField(max_length=200) cafe_address = models.CharField(max_length=200) cafe_long = models.FloatField() cafe_lat = models.FloatField() geolocation = models.PointField(geography=True, blank=True, null=True) venue_type = models.CharField(max_length=200) source = models.CharField(max_length=200) description = models.CharField(max_length=15000) [...] class VenueComments(models.Model): venue = models.ForeignKey(mapCafes, on_delete=models.PROTECT) user = models.ForeignKey(User, on_delete=models.CASCADE) comment = models.CharField(max_length=10000) views def add_venue_comment(request): if request.method == "POST": comment = request.POST.get('comment') venue = request.POST.get('venue_id') new_obj = VenueComments() new_obj.venue = venue new_obj.user = request.user new_obj.comment = comment new_obj.save() return JsonResponse([ new_obj.comment, new_obj.user ], safe=False) -
django api with custom user app authentication
I created a django project tha uses a customUser for authentication, following this blog post. I now would like to attach another app to the project that is a REST API that leverages that authentication. In this new app I create a model for the data that the uses will consume and I add as foreign key in the model the custom user model previously created. #project/api/models.py from django.contrib.postgres.fields import ArrayField from django.db import models from accounts.models import CustomUser class Signal(models.Model): name = models.CharField(max_length=30, blank=True, null=True) data = ArrayField(models.FloatField(), unique=True) threshold = models.FloatField(blank=True, null=True) user = models.ForeignKey(CustomUser, on_delete=models.CASCADE) def __str__(self) -> str: return f"{self.name}" while the project/api/views.py file is from django.template.defaultfilters import pluralize from rest_framework.decorators import api_view from rest_framework.generics import ListCreateAPIView, RetrieveUpdateDestroyAPIView from rest_framework.permissions import IsAuthenticated from rest_framework.request import Request from rest_framework.response import Response from . import serializers from .algorithm.compute_crossing import count_crossing_pos as count_cross from .models import Signal class SignalViewset(ListCreateAPIView): permission_classes = [IsAuthenticated] queryset = Signal.objects.all() serializer_class = serializers.SignalSerializer def get_queryset(self): return super().get_queryset().filter(user=self.request.user) class SignalDetail(RetrieveUpdateDestroyAPIView): permission_classes = [IsAuthenticated] queryset = Signal.objects.all() serializer_class = serializers.SignalSerializer def get_queryset(self): return super().get_queryset().filter(user=self.request.user) @api_view(http_method_names=["POST"]) def send_data(request: Request) -> Response(): """send signal data with threshold in request payload and compute crossing times around given threshold :param … -
how to create Django model field for Transaction Number formate
Transaction Number - unique for each transaction Format - TRN/{COUNT}/{YEAR} Count here should reset to 1 for every year. -
Fetching current user in Django FormView
Im building a listings site and each user is linked to a company. Before the user can post a new listing it must have bought credits. If there are no credits the FormView should show a template with a notification of 0 credits, however if credits > 0 then the actual form with should appear. Im struggling in trying to fetch the current user in the FormView class itself. I know that it can be done via the form_valid method user = self.request.user, but that would mean that the user must first fill the whole form and submit it after checking if he has enough credits. Im tryiing to figure out how to perform the check before the form has been filled and submitted. I couldnt find any resources how can I do something like this: class CreateAd(LoginRequiredMixin, FormView): if currents_user.ad_credits > 0: template_name = 'ads/ad_form.html' form_class = AdForm success_url = '/' else: template_name = 'ads/not_enough_credits.html' form_class = AdForm success_url = '/' -
Django: request.is_ajax() returning False
I'm trying to make the search of 'patient' Dynamic with ajax. Every thing in my code is working well but I don't know wy request.is_ajax() always returns false. I search about it but I didn't find the solution yet, right now my code do the search but with changing of the url and that mean the js dosen't work. I don't know how work well with javascript in Django so please help me. This is my views.py: def index(request): ctx = {} url_parameter = request.GET.get("q") if url_parameter: queryset = Patient.objects.annotate(fullname=Concat('first_name', Value(' '), 'last_name')) patients = queryset.filter(fullname__icontains=url_parameter) #patients = Patient.objects.filter(name__icontains=url_parameter) else: patients = Patient.objects.all() ctx["patients"] = patients print(request.is_ajax()) if request.is_ajax(): html = render_to_string(template_name="patient/patients-results-partial.html",context={"patients": patients}) data_dict = {"html_from_view": html} return JsonResponse(data=data_dict, safe=False) return render(request, "patient/index.html", context=ctx) index.html: {% extends 'base.html' %} {% block content %} <div class="col-md-6 offset-md-4"> {# part added for dynamic search#} {# icon and search-box #} <form class="form-inline"> <i id="search-icon" class="fas fa-search" aria-hidden="true"></i> <input id="patient-input" class="form-control form-control-sm ml-3 w-75" type="text" placeholder="Search" aria-label="Search" name="q"> </form> {# artist-list section #} <div id="replaceable-content" class="col-6"> {% include 'patient/patients-results-partial.html' %} </div> </div> <div class="col-md-6 offset-md-4"> <a href="{% url 'register_patient' %}" class="btn btn-primary">Ajouter un nouveau patient</a> </div> <div class="col-md-6 offset-md-4"> <div class="table-responsive"> <table class="table table-striped … -
Serialization in Django Rest Framework
In Django Rest Framework. I have a program that lets a user post some data. I serialize this input, but with this input I also save it to another model and create some default values for it and return them to the user. But I am getting slightly confused on whether or not I should serialize that model too. class FileExample(APIView): def post(self, request, format=None): serializer = FileExampleSerializer(data=request.data) if serializer.is_valid(): serializer.save() other_model = OtherModel(name=request.FILES['file'].name, type_obj='file') other_model.save() return Response({'url': other_model.url}, status=status.HTTP_201_CREATED) For example OtherModel is my other model object that I create which creates some default values. But I was looking at nested serializers but this did not achieve what I wanted, as it threw an error that it was missing a required value. My question is my code will work like this, but should I be serializing OtherModel as well? -
Django get uploaded images
I have created a model to get images and upload them to upload folder and the link is available in database. But when I call the image in my index.html it does not work settings.py USERFILES_DIRS = os.path.join(BASE_DIR, 'upload') STATIC_URL = '/static/' STATICFILES_DIRS = [ USERFILES_DIRS, os.path.join(BASE_DIR, 'static'), ] models.py class MyShoes(models.Model): title = models.CharField(max_length=50) description = models.CharField(max_length=50) price = models.DecimalField(max_digits=10, decimal_places=2) display_picture = models.ImageField(upload_to='upload', height_field=None,width_field=None, max_length=None) featured = models.BooleanField() views.py def myIndex(request): myShoes = models.MyShoes.objects.all() return render(request,'index.html',{'myshoes':myShoes}) HTML {% for x in myshoes %} <div class="card" style="width: 18rem;"> <img src="{{x.display_picture}}" class="card-img-top" alt="..."> <div class="card-body"> <h5 class="card-title">{{x.title}}</h5> <p class="card-text">{{x.description}}</p> <p class="card-text">{{x.price}}</p> {{x.display_picture}} <a href="" class="btn btn-primary">Go somewhere</a> </div> </div> {%endfor%} here in my HTML i am getting the url 'upload/shoe-1384193-1279x850.jpg' but HTML does show it in img tag -
I need Mutiple fields from both models in an m2m .csv export
I have a working solution for exporting a .csv file from a join of 2 models via a manytomany relationship and my issue is I don't know how to express, in code, how to bring in multiple fields from the model that is being joined. I can add multiple columns from the model that has the m2m field defined but I can only bring in one column from the model that is being referenced. How do I bring in multiple coulmns from both models? models.py class dbmobile(models.Model): Site_Code = models.CharField('Site Code', max_length=20, blank=True, null=True, choices=SITE) Account_Number = models.CharField('Account Number', max_length=20, blank=True, null=True,) Mobile_Number = models.CharField('Mobile_Number', max_length=20, blank=True, null=True,) User_Name = CharField('User Name', max_length=120, blank=True, null=True,) User_id = models.CharField('User Id', max_length=20, blank=True, null=True,) class expense(models.Model): ExcludeTax = models.DecimalField('Exclude Tax', max_length=20, blank=True, null=True, max_digits=10, decimal_places=2) IncludeTax = models.DecimalField('Include Tax', max_length=20, blank=True, null=True, max_digits=10, decimal_places=2) user = models.ManyToManyField(dbmobile, blank=True) Date = models.DateField(default=now) views.py def export_csv(request): response = HttpResponse(content_type='text/csv') response['Content-Disposition'] = 'attachment; filename="file.csv"' employees = expense.objects.all() writer = csv.writer(response) writer.writerow (['Date', 'Tax Included', 'User']) for e in employees: writer.writerow([e.Date, e.IncludeTax, ', '.join([e.User_Name for e in e.user.all()]),]) return response -
Django Polls-App: dynamically change number of choices in create-poll-form
After completing the Django beginner tutorial, I managed to build a create form to create a new poll with multiple choices. Now i want to add a button that adds another text-field for another choice. I'm new to web development and i struggle with passing variables from templates to views. I read here: Passing variable from django template to view, that there are essentially 4 ways to do this. I am currently using option nr. 3 to specify the number of choices displayed, but i am sure that option 1 would be more elegant, hence the number of choices wouldn't be displayed in the url. This is my current code: {% extends "base.html" %} {% block content %} {% load static %} <link rel="stylesheet" type="text/css" href="{% static "polls/style.css" %}"> <form method="POST" enctype="multipart/form-data"> {% csrf_token %} {{ form.as_p }} {{ choice_forms.management_data }} <div class="pollschoice">{{ choice_forms.as_ul }}</div> <a href="{% url "polls:create" nr_of_choices|add:1 %}"><input type="button", value="Add Choice"> </a> <a href="{% url "polls:create" nr_of_choices|add:-1 %}"><input type="button", value="Remove Choice"> </a> <input type="submit", value="Save" /> </form> {% endblock %} def createview(request, nr_of_choices): # initialize forms nr_of_choices = max(nr_of_choices, 1) form = QuestionForm(request.POST or None) choiceFormSet = formset_factory(ChoiceForm, extra=nr_of_choices) choice_forms = choiceFormSet(request.POST or None) # save question … -
Django admin doesn't show model/task changes
I Have a celery task running which calls an API to get some response. If the API call is successful, then the output is stored in redis in order to use it as a dropdown list in the admin page. But, if the API response fails, then I disable the add option in the Django admin page which works fine. The issue: After failing when the API response is successful again, then the admin page doesn't show the dropdown list. Instead it shows an empty box. To make it work again, I have to reload the server manually. Is there a way to reload server automatically when the API response changes? -
Django (Quiz/Exam app) forms for multiple table. Need help to create a form which is
Quiz app which has following models from django.db import models from classroom.models import Subject from django.contrib.auth.models import User # Create your models here. class Exam(models.Model): name = models.CharField(max_length=120) subject = models.ForeignKey(Subject, on_delete=models.CASCADE) number_of_questions = models.IntegerField() required_score_pass =models.IntegerField(default=40,) time = models.IntegerField(help_text="duration of test in minutes") def __str__(self): return f"{self.subject}: {self.name}" def get_questions(self): return self.question_set.all() class Question(models.Model): text = models.TextField() exam = models.ForeignKey(Exam, on_delete=models.CASCADE) def __str__(self): return f"{self.exam.name}: {self.text}" def get_answers(self): return self.answer_set.all() def get_correct_answers(self): for answers in self.get_answers(): if answers.correct: return answers.text class Answer(models.Model): text = models.CharField(max_length=200) correct = models.BooleanField(default=False) question =models.ForeignKey(Question, on_delete=models.CASCADE) def __str__(self): return f" question: {self.question.text}, answer: {self.text}, correct: {self.correct}" class Result(models.Model): exam = models.ForeignKey(Exam, on_delete=models.CASCADE) user = models.ForeignKey(User, on_delete=models.CASCADE) score = models.FloatField() I want to create a form for these models which are depended on each other. Any suggestion/idea for views or template are also welcome. Most of the models needs to save first since they will be need for ForeignKey fields. -
How to use Mailgun's recipient-variables with Django SMTP mail backend?
How can I properly send batch/bulk/mass emails using MailGun in Django using SMTP protocol? What I've tried so far? I am using django.core.mail.backends.smtp.EmailBackend as my EMAIL_BACKEND and this is the code snippet that I have tried to send the emails. from django.core.mail import EmailMultiAlternatives import json to_emails = [ "mail_1@example.com", "mail_2@example.com", "mail_3@example.com", "mail_4@example.com", "jerinpetergeorge@gmail.com", ] mail = EmailMultiAlternatives( subject="Hey - %recipient.name%", body="Hey %recipient.name%,\n\nThis is just a batch email test!!!", from_email="JPG <me@somehost.com>", to=to_emails, ) recipient_variables = { address: {"name": address} for address in to_emails } mail.extra_headers["X-Mailgun-Recipient-Variables"] = json.dumps(recipient_variables) response = mail.send() print(response) and I've got the mail as below, As we can see, the to attribute is filled with all email addresses, which is not what I am expecting. So, how can I tell the Mailgun/Django to parse my variables properly in order to make the emails looks more personal? Notes I prefer to use SMTP protocol I've tried the REST APIs of Mailgun and it was a success (but, I prefer SMTP) I found django-anymail and seems it has the feature. But, It also uses the APIs (correct me if I am wrong) -
Show most frequent tags in Django CreateView
I am trying to show the most frequent tags to select from when adding a post. However, when I added the get_context_data, the form disappeared. class AddPostView(CreateView): model = Post form_class = AddPostForm template_name = 'add_post.html' def get_context_data(self, **kwargs): common_tags = Post.tags.most_common()[:4] context = { 'common_tags': common_tags } return context # gets the user id def form_valid(self, form): form.instance.author = self.request.user return super().form_valid(form) And this is my form class AddPostForm(forms.ModelForm): class Meta: model = Post fields = ('title','summary', 'body', 'header_image', 'category', 'tags') labels = { "title": "العنوان", "tags": "العلامات", "category": "التصنيف", "summary":"الملخص", "body": "المحتوى", "header_image": "الغلاف", } widgets = { 'title': forms.TextInput(attrs={'class':'form-control'}), 'tags': forms.TextInput(attrs={'class':'form-control'}), 'category': forms.Select(choices=choices_list, attrs={'class':'form-control'}), 'summary': forms.TextInput(attrs={'class':'form-control'}), 'header_image': forms.FileInput(attrs={'class':'form-control'}), 'body': forms.Textarea(attrs={'class':'form-control'}), } -
i want a move this logic to django utils file. I tried some code but failed
This is the code. I am using graphene django. I dont want to write logic in graphQL. I want to shift this logic to utils.py file class CreateCareer(graphene.Mutation): _career = graphene.Field(CareerType) class Arguments: input = CareerInput(required=True) def mutate(cls, root, info, input): try: input["from_date"] except: return GraphQLError("Please select from_date") try: input["current_work_here"] is False and not input["to_date"] except: raise Exception("Please select to_date") if input["current_work_here"] is False: if input["from_date"] > input["to_date"]: return GraphQLError("from_date must less than to_date") career = CandidateCareer.objects.create(**input) return CreateCareer(_career=career) -
Can I extend parent's class list attribute on class level?
Suppose, I have the following parent class: class Parent: permissions = ['CanEdit', 'CanCreate'] I need to extend permissions attribute in my child class without changing the initial contents and so that this change would be on the class level, not instance, meaning: print(Parent.permissions) Output: ['CanEdit', 'CanCreate'] And I need the something like this in my child class: class Child(Parent): permissions += ['CanManage'] print(Child.permissions) With the output: ['CanEdit', 'CanCreate', 'CanManage'] Is this even possible to implement? -
Count combination of 2 fields
I would like all the plays of a song per radiostation. class Airplay(Timestamps): song = models.ForeignKey(Song, on_delete=models.CASCADE) radio = models.ForeignKey(Radio, on_delete=models.CASCADE) airedAt = models.DateTimeField(blank=True) I try to calculate the airplay like this Airplay.objects.all().annotate(play_count=Count(Concat('song__id', 'radio__id'), distinct=True)).order_by('play_count') I see several occurrences of a song x station combination. But play_count is always 1. -
Why is this django registration mechanism not working for my custom user model?
I was working on a project where I was implementing a custom user model using django and registration,login for the same. But unfortunately, I guess the registration mechanism doesn't work correctly. How do I know that is, in Admin panel, it shows the new user where while trying to login with the new user, I get "Please enter a correct username and password. Note that both fields may be case-sensitive." . I've spent around 2 days googling,stackoverflowing. But none of them has solved my problem. My Code Models.py: from django.db import models from django.utils import timezone from django.utils.translation import gettext_lazy as _ from django.contrib.auth.models import AbstractBaseUser, PermissionsMixin, BaseUserManager class CustomAccountManager(BaseUserManager): def create_superuser(self, email, username, password, **other_fields): other_fields.setdefault('is_staff', True) other_fields.setdefault('is_superuser', True) other_fields.setdefault('is_active', True) if other_fields.get('is_staff') is not True: raise ValueError('Superuser must be assigned to is_staff=True.') if other_fields.get('is_superuser') is not True: raise ValueError('Superuser must be assigned to is_superuser=True.') return self.create_user(email, username, password, **other_fields) def create_user(self, email, username, password, **other_fields): if not email: raise ValueError(_('You must provide an email address')) email = self.normalize_email(email) user = self.model(email=email, username=username, **other_fields) user.set_password(password) user.save(using=self._db) return user class UserModel(AbstractBaseUser, PermissionsMixin): email = models.EmailField(_('email address'), unique=True) username = models.CharField(max_length=150, unique=True) first_name = models.CharField(max_length=150, blank=True, null=True) last_name = models.CharField(max_length=150, blank=True, … -
Model() got an unexpected keyword argument 'instance'
I am currently trying to get an instance of my model to read from it and print reports based on the model However when trying to reach the URL I get the above error, I assume that the instance variable doesn't work but I don't know why. I have been reading other articles and found that others get this error when they use Form instead of ModelForm, so I don't know if this could be the same thing as that. Please see the below code : Model.py: class SettingsClass(models.Model): Complex = models.CharField(choices=complex_list , max_length = 22 ,default='1' , unique=True) Trial_balance_Year_to_date= models.BooleanField(default = False) tbytd_Include_opening_balances=models.BooleanField(default = False) tbytd_Only_use_main_accounts=models.BooleanField(default = False) tbytd_Print_null_values=models.BooleanField(default = False) tbytd_Print_description=models.BooleanField(default = True) tbytd_Print_account=models.BooleanField(default = True) tbytd_Sort_by_account_name=models.BooleanField(default = True) def __str__(self): return (self.Complex + ' Settings') View.py:: def reportsHome(request): model = SettingsClass.objects.all().order_by('Complex') content ={'model':model } return render(request, 'main/reportsHome.html' , content) def printReports(request , reports_pk): pkForm = get_object_or_404(SettingsClass , pk=reports_pk) form= SettingsClass(instance=pkForm) complexName = form.Complex #CHECKING TRIAL BALANCE SETTINGS if form.Trial_balance_Year_to_date == True: printTrialBalanceYTD = True ### Printing Trial Balance PDF response = HttpResponse(content_type= 'application/pdf') response['Content-Disposition']= 'attachment; filename=TrialBalance' + \ str(datetime.now()) + '.pdf' response['Content-Transfer-Encoding'] = 'binary' #SQL STATEMENT baseSelect = 'SELECT '+ op5 + op4 + ' Debit , …