Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Django:[ODBC Driver 17 for SQL Server][SQL Server]Login failed for user 'test'. (18456)
I used Django to connect to SQL Server 2016 and I started executing Python3" manage.py Runserver 8000 terminal prompt: django.db.utils .InterfaceError: ('28000', "[28000] [Microsoft][ODBC Driver 17 for SQL Server][SQL Server]Login failed for user 'test'. (18456) (SQLDriverConnect)")” enter image description here I don't know where the problem is。 This is my database configuration: DATABASES = { 'default': { 'ENGINE': 'sql_server.pyodbc', 'NAME':'testDB',#db name 'USER':'test',#db longin user 'PASSWORD':'test#2021',#db longin pwd 'HOST': '10.32.9.51',#db host 'PORT': '1433',#port,default1433 'OPTIONS': {#odbc driver 'provider': 'SQLOLEDB', # Have also tried 'SQLCLI11' and 'SQLOLEDB' 'driver': 'ODBC Driver 17 for SQL Server', 'MARS_Connection': True, }, } } But I use pyodbc to connect to the database and query. At this time, the query is successful。 import pyodbc try: conn = pyodbc.connect('DRIVER={ODBC Driver 17 for SQL Server};SERVER=10.32.9.51;PORT=1433;DATABASE= testDB;UID=test;PWD=test#2021') cursor=conn.cursor() cursor.execute("select getdate()") row=cursor.fetchone() while row: print("sqlserver date:%s"%(row[0])) row=cursor.fetchone() print(row) conn.close() except Exception as e: print("DB Error") print("DB Error:"+str(e)) enter image description here System environment: System:Centos 7 python: 3.7.9、 Django:2.1.15、 django-mssql:1.8、 django-pyodbc:1.1.3、 django-pyodbc-azure:2.1.0.0、 django-sqlserver:1.11、 djangorestframework:3.12.2、 pip:21.0.1、 pymssql:2.1.5、 PyMySQL:1.0.2、 pyodbc:4.0.30、 sql server configure: enter image description here enter image description here enter image description here -
Django admin list_display is not displaying model method return item
I'm not able to get the list_display of admin to show the information from a model method, but the same method displays fine in the fieldsets on the change page. I think I've fixed all my mistakes that are present in other questions/answers on this topic, but I just can't seem to figure out what I've done. Any help will be much appreciated. Admin: class StudentAdminConfig(admin.ModelAdmin): list_dispaly = ('name', 'get_total_funds') fieldsets=( (None, {'fields': ('name', 'get_total_funds')}), ) readonly_fields = ('get_total_funds',) admin.site.register(Student, StudentAdminConfig) Models: class Student(models.Model): name = models.CharField(max_length=255) def get_total_funds(self): events = self.get_funds_events() total = float(0) for event in events: if event.income: total += float(event.amount) else: total -= float(event.amount) return f'${total:.2f}' get_total_funds.short_description = "Total Funds" def get_funds_events(self): return FundsEvent.objects.filter(students_attended=self) def __str__(self): return self.name The annoying thing about this list_display issue is that it's not giving any errors I can traceback, it's just displaying the page with no column for the "Total Funds". Also, I've sunk so much time into this and it's not even that vital of a feature, just a convenience for me, as I'm literally the only one who will ever look at this display on this particular project, but I'm invested enough that I really want to figure … -
How to access Django admin page without is_superuser property?
I want to know how to access the admin page with the is_admin property instead of the is_superuser property of django. here is my code is_superuser = True # django default is_admin = True # my custom property def create_superuser(self, email, username, password): user = self.create_user( email = self.normalize_email(email), username = username, password = password ) user.is_active = True user.is_staff = True user.is_superuser = True -> i want to change -> is_admin = True user.save(using=self._db) return user Changing is_superuser to is_admin prevents access to the admin page. How can I access the admin page with the is_admin property? -
How to get objects who contain all of the tags in a query with Django Taggit?
I'm trying to get all objects that are tagged with all of the query parameters that I send. For example, if the query is tags=tag1,tag2, I need to get all objects that are tagged with both tag1 and tag2. tags = Final_Content.objects.filter(tags__name__in=self.request.query_params.get('tags').split(",")).distinct() However, this doesn't work as the in condition is satisfied even if only tag is present. -
Database connection object is not callable exception thrown with Python Django SQL Alchemy database pooling. Why?
What I'm trying to achieve Create a database connection pool in Django. The connection pool is connected to a PostgreSQL database by using SQLAlchemy's connection pooling with django-postgrespool2. Thrown exception 'psycopg2.extensions.connection' object is not callable is thrown when running the following line of code poolConnection = dbPool.connect(). Printing the dbPool object and type displays <sqlalchemy.pool.impl.QueuePool object at 0x00000171832A72B0> <class 'sqlalchemy.pool.impl.QueuePool'> Code Database helper class which creates the connection to the PostgreSQL database and creates the connection pool: import psycopg2 from sqlalchemy import pool import traceback dbPool = None class DbPoolHelper: def ensurePoolCreated(self): global dbPool if dbPool != None: return self.createPool() def dbConnect(self): dbConnection = psycopg2.connect(user="...", password="...", dbname="...", host="...",port="...") return dbConnection def createPool(self): dbConnection = self.dbConnect() global dbPool dbPool = pool.QueuePool(dbConnection, max_overflow=10, pool_size=5) def execute(self, sql, sqlParams): try: global dbPool self.ensurePoolCreated() poolConnection = dbPool.connect() cursor = poolConnection.cursor() cursor.execute(sql, sqlParams) poolConnection.commit() result = cursor.fetchall() cursor.close() poolConnection.close() return result except Exception as e: print(e) return e The code using the DbPoolHelper to fetch some data by using the execute method and giving some sql and sql params as arguments: def poolTest(): sql = "SELECT * FROM sysproductcontainers;" sqlParams = () db = DbPoolHelper() result = db.execute(sql, sqlParams) Question Why does the code throw … -
How to send a key value with an empty list in a django RequestFactory? or drf APIRequestFactory?
I have a method that I must not change, that expects a request as a QueryDict. It does some logic with a parameter that receives like this: request.POST.getlist("process") So, I need to send a fake request with all the data and that key value. I need to send that value as an empty list, like this: <QueryDict: {'process': [], 'foo': 'bar'}> So I tried with django RequestFactory like this: from django.test.client import RequestFactory rf = RequestFactory() request = rf.post('/submit/', {'foo': 'bar', 'process':[]}) But I got: print(request.POST) <QueryDict: {u'foo': [u'bar']}> Also with drf APIRequestFactory like this: from rest_framework.test import APIRequestFactory rf = APIRequestFactory() request = rf.post('/submit/', {'foo': 'bar', 'process':[]}) I got: print(request.POST) <QueryDict: {u'foo': [u'bar']}> I expect to get: <QueryDict: {u'foo': [u'bar'], 'process':[]}> Important: process value must be [] and not [[]]: <QueryDict: {u'foo': [u'bar'], 'process':[[]]}> # I dont want this (It doesn't matter if foo value is a list, but I need process as []) So, It's possible to get an empty list in a fake request with django RequestFactory? or drf APIRequestFactory? Thanks for any help -
How to get the data out of that special json?
I want to make it short. I want to do a table, which contains data from a django api stream via angular. Im using the http get method from angular to do so, and it works absolutely fine with the following examples: https://jsonplaceholder.typicode.com While this cant be extracted. Even when i go into results with sth like results: { id: any; } I cant provide a link because its changing sometimes at the moment (thats not the reason why i cant parse it into my table) Im new to Front end and programming in generally so please be precisely and comprehensive, i just want a solution and never wanna see frontend again at anytime :D. Can there be any difference between those jsons, that i cant see or google? I think, its pointless giving the code for the get request, because its actually working but just in case: import { Injectable } from '@angular/core'; import { HttpClient } from '@angular/common/http'; import { Observable } from 'rxjs'; import { Tutorial } from '../models/tutorial.model'; const baseUrl = 'https://jsonplaceholder.typicode.com/users'; @Injectable({ providedIn: 'root' }) export class TutorialService { constructor(private http: HttpClient) { } getAll(): Observable<Tutorial[]> { return this.http.get<Tutorial[]>(baseUrl); } I really wanna get this … -
Why can't I render my editform but I can render my addform?
I keep getting this Error when I attempt to render the editform.html. Reverse for 'edit' with arguments '('',)' not found. 1 pattern(s) tried: ['contacts/edit/(?P<cur_id>[0-9]+)/$'] I'm not sure what I'm doing wrong, I was able to render my addform.html without an issue, but this editform is being pesky. I feel like I need to pass something somewhere but I'm not completely sure where or what. urls.py from django.urls import path from . import views app_name = 'contacts' urlpatterns = [ path('', views.index, name='index'), path('list/', views.list, name='list'), path('add/', views.add, name='add'), path('edit/<int:cur_id>/', views.edit, name='edit'), path('delete/<int:cur_id>/', views.delete, name='delete'), ] views.py from django.shortcuts import render, redirect from django.http import HttpResponse, HttpRequest from django.template import loader from .models import Contact def index(request): return HttpResponse("Hello, world. You're at the contacts app.") def list(request): contacts_list = Contact.objects.all() return render(request, 'index.html', {'contact_list':contacts_list}) def add(request): if request.method == 'POST': new_contact = Contact( firstname = request.POST['firstname'], lastname = request.POST['lastname'], age = request.POST['age'], phone = request.POST['phone'], email = request.POST['email'], gender = request.POST['gender'], ) new_contact.save() return redirect('/contacts/list/') return render(request, 'addform.html') def edit(request, cur_id): return render(request, 'editform.html') def delete(request, cur_id): pass editform.html <html> <head> <title> Contacts App </title> {% load static %} <script src="{% static '/contacts.js'%}"></script> {% load static %} <link rel='stylesheet' type='text/css' href="{% … -
Check if a user leaves a view function
Lets say I have a realArray and a tempArray. I want to add all the data in the tempArray into the realArray if a user clicks something that would cause them to leave the view they are currently on. This could be closing the browser, searching something in their browser, clicking a bookmark, or clicking a different link within the website. Any thoughts would be appreciated:) -
Page not found (404) django.contrib.admin.options.add_view
On the production server, when I try to edit/create an object then saving fails, returning Page not found (404).This only occurs for POST requests, GET requests (loading the page) work fine. Django is deployed via cPanel and WSGI, DEBUG is False (though it does not work even when it's set to True) Request Method: POST Request URL: https://example.com/admin/[APP Name]/[Model]/add/ Raised by: django.contrib.admin.options.add_view Using the URLconf defined in General.urls, Django tried these URL patterns, in this order: admin/ [name='home'] stores/ [name='allstore'] site/<slug:slug>/ [name='store'] code/<slug:slug>/ [name='cate'] category/ [name='category'] deals/ [name='api'] offer/ [name='offer'] ^media/(?P<path>.*)$ The current path, Hotel/slider/add/, didn't match any of these.``` **setting.py** DATABASES = { 'default': { 'ENGINE': 'django.db.backends.sqlite3', 'NAME': BASE_DIR / 'db.sqlite3', } } **I will try a different Database But showing the same erorr** Mysql Postgresql STATIC_URL = '/static/' STATIC_ROOT = '/home/username/domainname.com/static' MEDIA_URL = "/media/" MEDIA_ROOT = "/home/username/domainname.com/media" -
What are the benefits of having multiple front-ends?
TL;DR When should a project have multiple front-ends? I'm unsure if we should extend our existing front-end or make another one with additional functionalities. We have an Ionic-React app that interfaces with a Django back-end. We've reached a point where we need the following: An admin front-end (with some admin-level permissions). Think support desk, account overview, and analytics. A desktop app (with limited permission). Think account overview, but with less permission than the mobile app. Would it be better to merge these 2 solutions into our main mobile app (and use ionic to generate a PWA) or should we have a dedicated solutions for these? Disadvantage of merging: The app will be heavy. Ionic is known to be slow (and sometimes buggy). User permission will be quirky. Admin and desktop app have the most overlap in functionality, so it would keep the code much cleaner. 2nd front-end could double as landing page. Advantages of merging: Less code to maintain, less front-ends to deploy. I honestly can't think of another advantage for this. This might be really messy... Which solution do you think would work best? As you can tell, I want separate apps, but I have a project manager to … -
NOT NULL constraint failed: products_order.user_id when trying to save serializer django rest frame work
django rest framework gives me this error when i am trying to perform a post request to create a new order even though i specified the usr value in my serializer.save method. here is my view class OrderListCreateAPI(generics.ListCreateAPIView): serializer_class = OrderSerializer permission_classes = [IsOwner] def get_queryset(self): user = self.request.user return Order.objects.filter(user= user) def perform_update(self, serializer): instance = serializer.save(user = self.request.user) order = Order.objects.get(id = instance['id'].value) order.item.quantity -= order.quantity order.save() my models.py payment_methods = ((1,'credit card'),(2, 'cash'),(3, 'paypal')) class Product(models.Model): title = models.CharField(max_length=100) description = models.TextField() image = models.ImageField(upload_to = 'images/', height_field=300, width_field=300) price = models.IntegerField() quantity = models.IntegerField() seller = models.ForeignKey(User, on_delete=models.CASCADE, related_name='products') date = models.DateTimeField(auto_now_add=True) def __str__(self): return self.title class Order(models.Model): item = models.ForeignKey(Product, on_delete= models.CASCADE, related_name='orders') user = models.ForeignKey(User, on_delete=models.CASCADE, related_name='orders') quantity = models.IntegerField() payment_options = models.CharField(choices=payment_methods, max_length=50) Delivery = models.CharField(max_length=200) my serializers class ProductSerializer(serializers.ModelSerializer): class Meta: model = Product fields = ['id', 'title', 'description','image', 'price', 'quantity', 'seller', 'date'] read_only_fields = ['date', 'seller'] class OrderSerializer(serializers.ModelSerializer): class Meta: model = Order fields = '__all__' read_only_fields = ['user'] -
Django Multiple Files Upload
I would like to upload multiples files in my model in Django. I am struggling on the HTML part. I would like to include it part of my detail view without having to create a special view to upload the files. When I click on the button, it open the file upload, I select them but they don`t seem to be attached to the model. Any ideas please? models.py class Quote(models.Model): name = models.CharField(max_length=30) class Attachment(models.Model): quote = models.ForeignKey(Quote, on_delete=models.CASCADE, blank=True, null=True) name = models.CharField(max_length=30) file = models.FileField(upload_to='quotes/%Y/%m/%d',blank=True, null=True) def __str__(self): return self.name forms.py class AttachmentForm(forms.ModelForm): class Meta: model = Attachment fields = ('file', ) widgets = { 'file': ClearableFileInput(attrs={'multiple': True}), } # widget is important to upload multiple files views.py @login_required(login_url="/login/") def add_attachment(request, quote_id): form = AttachmentForm(request.POST or None, request.FILES or None) quote = get_object_or_404(Quote, pk=quote_id) if form.is_valid(): quotes_attachments = quote.attachment_set.all() attachment = form.save(commit=False) attachment.quote = quote attachment.attachments = request.FILES['attachments'] file_type = attachment.attachments.url.split('.')[-1] file_type = file_type.lower() attachment.save() return render(request, 'quotes/quote_detail.html', {'quote': quote}) context = { 'quote': quote, 'form': form, } return render(request, 'quotes/quote_detail.html', context) quote_detail.html <div class="card-block"> <form action="/static/assets/plugins/fileupload/js/file-upload.php" method="post" class="dropzone" enctype="multipart/form-data" > <div class="fallback"> <input name="file" type="file" multiple style="display: none;" data-url="{% url 'projects:add_attachment' quote.id %}" data-form-data='{"csrfmiddlewaretoken": "{{ csrf_token … -
How to safely remove a column from a Pandas dataframe in a web environment(Django)?
I am building an interactive data science dashboard and I encounter a situation where deleting a column doesn't result in the predicted behavior: if action == 'COLUMN_REMOVE': name = payload['name'] print('#\t', name) df = df.drop(columns=[name], axis=1) df.to_csv(document.path.path) The original column set is something like this: [a, b, c, d, <name>] After running the code snippet above inside a Django request view, the column is not being deleted but the resulting dataframe has renamed it/added a new column with the name (Unnamed: 0.0) [a, b, c, d, Unnamed: 0.0] Is the way I am deleting the data frame correct? I tried multiple ways (e.g., del df[name]) but it produces equivalent results. -
Need help I want correct explanation for that, Class and Inherit
class MovieSerializer(serializers.ModelSerializer): #MovieSerializer = it's a class name #serializers = it's a Inherit #ModelSerializer = ???? please help me -
Djago dependent dropdown list using AJAX jQuery not working in Template
im doing a django dependent form and it works for my create view but not in update view. I tink the problem is the jQuery cdn library, i think its a conflict with the bootstrap cdn. The AJax call does not fire. Any idea maybe there is a simpler way to do dependent forms in django? If you have a solution i gladly want your help thx Theo Models view: class Profession(models.Model): name = models.CharField(max_length=30) profession_icon = models.ImageField(_("profession icon"), upload_to='profession_icon/%Y/%m/%d/', height_field=None, width_field=None, max_length=None, blank=True, validators=[validate_image_file_extension]) def __str__(self): return self.name class Professioncategory(models.Model): profession = models.ForeignKey(Profession, on_delete=models.CASCADE) name = models.CharField(max_length=30) def __str__(self): return self.name class Skills(models.Model): user = models.ForeignKey(User, on_delete=models.CASCADE) active = models.BooleanField(_('Active'), default=True) profession = models.ForeignKey(Profession, on_delete=models.SET_NULL, null=True) professioncategory = models.ForeignKey(Professioncategory, on_delete=models.SET_NULL, null=True) posted_on = models.DateTimeField(_('Registrerad'), auto_now_add=True) updated_on = models.DateTimeField(_('last updated'), auto_now=True) years_of_exp = models.CharField(_('years of experiance'), max_length=20, choices=YEARS_OF_EXP, null=True, blank=True) def __str__(self): return self.user.email def get_absolute_url(self): return reverse("users:detail", kwargs={"user_id": self.user.id}) def geticon(self): return self.profession.profession_icon Forms.py class SkillsForm(forms.ModelForm): class Meta: model = Skills fields = ['profession','professioncategory', 'years_of_exp','active'] def __init__(self, *args, **kwargs): super().__init__(*args, **kwargs) self.fields['professioncategory'].queryset = Professioncategory.objects.none() if 'profession' in self.data: try: profession_id = int(self.data.get('profession')) self.fields['professioncategory'].queryset = Professioncategory.objects.filter(profession_id=profession_id).order_by('name') except (ValueError, TypeError): pass # invalid input from the client; ignore and fallback to … -
Django media_url is not correct for filefield
I have a DRF project with a model like this: class MyModel(models.Model): id = models.UUIDField(default=uuid4, primary_key=True, unique=True) output_file = models.FileField(null=True, blank=True, max_length=200) geometry = models.PolygonField() created_at = models.DateTimeField(auto_now_add=True) in this model, output_file is a file that after processing in the server, is saved by application ( user does not directly upload a file for this field ). This file is saved somewhere in the MEDIA_ROOT. My MEDIA_ROOT = "/var/www/media/" and MEDIA_URL="/media/" and file is saved for example in "/var/www/media/items/file.txt". When I serialize this model I get the following result as the response json: { "id": "b2544986-4cfd-****-b349-defd3db****", "output_file": "/media/var/www/media/items/file.txt", "geometry": "something", "created_at": "2021-03-08T19:55:42.068976+03:30" } As you see, I'm getting redundant /media/ in the beginning of the URL. I mean the URL must be: /media/items/file.txt But I get: /media/var/www/media/items/file.txt. What is my problem and how can I fix it? Thanks for your help :D -
Save video on Django server using recordRTC
I am following this blog to save video using RecordRTC. But this is in PHP. I tried to write an equivalent function in python. I am able to get the file name, but I don't know where it is stored. This is django script. @csrf_exempt def upload_video(request): print('upload_audio') if request.is_ajax(): req=request.POST.get('video-filename') print(req) return HttpResponse('video received') print(req) give me a file name, but it I don't know where it is located. Here is PHP script written in blog <?php // upload directory $filePath = 'uploads/' . $_POST['video-filename']; // path to ~/tmp directory $tempName = $_FILES['video-blob']['tmp_name']; // move file from ~/tmp to "uploads" directory if (!move_uploaded_file($tempName, $filePath)) { // failure report echo 'Problem saving file: '.$tempName; die(); } // success report echo 'success'; ?> -
What is the correct way to handle multiple parameter queries for filtering in Django?
I need to implement a search functionality on my app which will have multiple parameters. What is the correct way to do the filtering in Django? Should I check if every parameter is present in the URL or is there another way? For example: country=US&state=NV&city=NewYork&date=2020-12-12&tags=... Not all of them need to be present in the URL so I'm not sure on how to check which ones are present and to filter with them. -
Django: push real time data to client
I am building a multi-page live blogging app with Post and Comment models and I am trying to create a real time (filtered) feed of posts using Django's template system. I'm using Postgresql for the database. When a new post is created (for example when the post_save signal is triggered) I want the post object to be added/pushed to the feed in the page the user is on in real time. Also when a post is liked or commented I want to increase the like and comment count for each post object in real time. I have Googled thoroughly for an answer and looked at Django Channels, Celery, Websocket and SSE but almost all of the examples and answers are about chat applications. What is the best way of achieving this? What capacity issues do I have to manage (a large number of users will be viewing a large number of post objects which will be added and updated in real time in different feeds)? -
How can i send email ( django )
I have a form in index page and i have 12 inputs in forms , so if user submits the form i need all 12 inputs in body of my email . I tried different methods and tried searching on google and youtube but could not find the solution. My urls.py code from django.contrib import admin from django.urls import path, include from . import views urlpatterns = [ path('', views.index,name='index'), path('about/', views.about,name='about'), path('contact/', views.contact,name='contact'), ] my views.py code from django.shortcuts import render from django.http import HttpResponse from django.core.mail import send_mail # Create your views here. def index(request): def form(request): if request.method == "POST": year = request.POST['year'] make = request.POST['make'] part = request.POST['part'] engine = request.POST['engine'] transmission = request.POST['transmission'] name = request.POST['name'] email = request.POST['email'] phone = request.POST['phone'] state = request.POST['state'] zipcode = request.POST['zipcode'] address = request.POST['address'] form = "Year: " + year + "Make: " + make + "Part: " + part + "Engine: " + engine + "transmission: " + transmission + "Name: " + name + "Email: " + email + "Phone: " + phone + "State: " + state + "Zipcode: " + zipcode + "Address: " + address send_mail( 'Mail from carparts', form, 'arshadkhanak05@gmail.com.', ['arshadkhanak05@gmail.com'], fail_silently=False, … -
How to deploy multiple services from the same Django project to Google App Engine?
Google App Engine allows developers to deploy multiple services from the same project structure. But I couldn't realize how it would to deploy them from an unique Django project. I'm already aware about How to deploy a Django project on Google App Engine, as well as How to deploy multiple Services with Google App Engine and how GAE expect a dispath.yaml to serve multiple services from a same deploy. In their description, the dispath.yaml should point to each service root, where service's app.yaml will be placed. However, I don't intend to have multiple Django projects in the file structure. I was expecting to be able to select each set of Django apps I want to be served in each App Engine service Someone thinks a manner to achieve it? Or there's another way of reuse same django project settings to reach it? -
Distribute tasks evenly which communicates via serial port, making sure that every celery worker is connected to a different serial port?
I have 10 IoT devices connected to the server, and I send/receive data via serial. I have 2 different types of tasks that gets executed via API call.. I might receive 1000 requests and I need to distribute them on these 10 devices, 1 worker per device, because of the Serial protocol limitations. Some of these devices are for task 1 and some are for task 2. I can create a queue per device and solve it, but the problem is if we plug in more devices later, it's gonna be a bit troublesome. I'd rather just assign the right task to the right device, and make sure it's executed one at a time. Any idea what I can do here? -
How do I solve a skel is not defined at skel-layers-min.js django framework error
Hello there my fellow devs, I am a backend beginner django developer and I used a premade template from Htmlup.com. I have changed all the links to {'static "{file location}"'}. When I run it on localhost it gives me this error: **init.js:15 Uncaught TypeError: {(intermediate value)} is not a function at init.js:15** I have tried adding: **var helios_settings = { //other settings here skel: {prefix: "{% static '/css' %}" }, // other settings here }** to the init.js file but it's still not working. Please what do I do? -
django canvas filter data and make the union of arrays filtered
I have a django canvas web app The user can draw on canvas and the drawing is saved in json as coordinates my model is as follows class Drawing(models.Model): drawingJSONText = models.TextField(null=True) project = models.CharField(max_length=250) drawingJSONTEXT contains the coordinates project contains the name of project i need to filter the data based on a specific project and i need to make a union of coordinates (drawingJSONText) filtered based on criteria Right now the code is able to filter and union two data based on their id def load(request): """ Function to load the drawing with drawingID if it exists.""" try: #filterdata = Drawing.objects.filter(project=a) drawingJSONData1 = json.loads(Drawing.objects.get(id=1).drawingJSONText) drawingJSONData2 = json.loads(Drawing.objects.get(id=2).drawingJSONText) drawingJSONData = dict() drawingJSONData["points"] = drawingJSONData1["points"] + drawingJSONData1["points"] drawingJSONData["lines"] = drawingJSONData1["lines"] + drawingJSONData2["lines"] drawingJSONData = json.dumps(drawingJSONData) # Sending context with appropriate information context = { "loadIntoJavascript": True, "JSONData": drawingJSONData } # Editing response headers and returning the same response = modifiedResponseHeaders(render(request, 'MainCanvas/index.html', context)) return response I need it to filter the data dynamically such that all data which has project name= a are filtered and added into drawingjsonData and displayed on canvas