Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
how to add multiple dict inside a list in python 3 with same key?
how to add multiple dict in python which is inside a list something like in this i need to add the amount from same person so where email id is same i want to add the amount. how can we do this i tried merging dic but i am getting duplicate responce. { "payment_type_details": [ { "email": "revati.sukumar@gmail.com", "first_name": "Revati ", "mode_of_payment": "offline", "payment_credited_on": "2019-10-16T11:03:23.511297", "paid_amount": 200000.0 }, { "email": "revati.sukumar@gmail.com", "first_name": "Revati ", "mode_of_payment": "offline", "payment_credited_on": "2019-10-16T11:03:23.511297", "paid_amount": 10049.99 }, { "email": "pradhan.sangita123@gmail.com", "first_name": "Sangita ", "mode_of_payment": "offline", "payment_credited_on": "2019-10-16T11:03:23.511297", "paid_amount": 128388.99 }, { "email": "pradhan.sangita123@gmail.com", "first_name": "Sangita", "mode_of_payment": "offline", "payment_credited_on": "2019-10-16T11:03:23.511297", "paid_amount": 100250.85 }, ] } -
Django - Heavy database usage
Let's say you are building a SAAS application system in which every user will use the database heavily, for example, a hospital management system. Should you have separate databases for each user? And how do you implement this in Django? -
Object of type 'bytes' is not JSON serializable while calling an api
I'm trying to save a form which involves an API call but its throwing me an error that Object of type 'bytes' is not JSON serializable. when I call data=json.dump(dump) it throws the following error def getAttributes(self, jsonObj=False): attributes = vars(self) data = {var: value for var, value in attributes.items() if not var.startswith('_')} print(data, "data") if jsonObj: import json data = json.dumps(data) return data p.s.: In print data statement it is returning me a dict. -
Python: Passing an object instance from one function to another?
I'm having trouble with passing a value from one script to another, trying to take it a step at a time but the big picture would be to print the value obj1.get_predval to my Django view and wait for the users' input. active_learner.obj1.get_predval in my beta.py script doesn't work, it just prints out the initial value which makes sense because it's not running the main.py but I'm not sure how I'd pass the value of obj1.set_predval(machine_prediction) from main.py. It properly outputs the obj1.get_predval in the main.py script. I'm assuming I have a fundamental misunderstanding, for now, all I'm trying to return is the value of obj1.get_predval in function beta.py, when it gets to the line return value and wait for user input then continue. main.py script below obj1 = MachinePred() def main(): model = load_model('model_new.h5') DATAFILE = "c_user_model_data100000.csv" dataset = loadtxt(DATAFILE, delimiter=",") X_pool, Y = dataset[:, 0:5], dataset[:, 5:] sc_x, sc_y = StandardScaler(), StandardScaler() X_pool, Y = sc_x.fit_transform(X_pool), sc_y.fit_transform(Y) learner = ActiveLearner( estimator = model, query_strategy = uncertainty_sampling ) for i in range(3): query_idx, query_inst = learner.query(X_pool) print("The machine queried:\n{}\nat index {}".format( sc_x.inverse_transform(query_inst), query_idx ) ) machine_prediction = learner.predict(X_pool[query_idx]) obj1.set_predval(machine_prediction) print("predvalue:", (obj1.get_predval())) ratings = [] cc_factor = ["delay", "speed", "missing_words", … -
using django permissions.IsAuthenticatedOrReadOnly with token authentication
I have this Django API view that I want to allow authorized and unauthorized users access it, I have set Django token-authentication as the default authentication class, however, whenever I try to access the view as unauthenticated user,I get error Unauthorized: which is weird coz am doinf a get request in the view my code is here @api_view(['GET']) @permission_classes([permissions.IsAuthenticatedOrReadOnly]) def all_Search(request): print(request.headers) src = request.GET.get('q') my settings for rest framework is REST_FRAMEWORK = { 'DEFAULT_AUTHENTICATION_CLASSES': [ 'rest_framework.authentication.TokenAuthentication', 'rest_framework.authentication.SessionAuthentication', ] } is there a way to work around this? will appreciate any help, thanks -
How to suppress warning message in django unit test
I'm trying to write some unit test cases for django (Restful API backend), While executing, I'm seeing below (403 Forbidden), which is expected, since the test is to hit a 403 endpoint. Is there a way to suppress that. I have already tried python -W error but no luck. (venv) python manage.py test System check identified no issues (0 silenced). [16/Nov/2019 11:15:26] WARNING [http://log.py:228 ] Forbidden: /api/test_enter ------------------------------------------------------------------------------ Ran 1 test in 0.021s OK How to suppress warning message in #python #django #unittest. Any thoughts would be very very helpful. Thanks. a fellow developer. :) -
Create session but has error 'Confirm form submission'
so i try to make a login function with session so if people logout , they cannot back to the page before but everytime i try to back (that has session or not) it always give me an error Confirm Form Resubmission This webpage requires data that you entered earlier in order to be properly displayed. You can send this data again, but by doing so you will repeat any action this page previously performed. i dont know wheres the problem , but here's the code def login_view(request): if request.method == 'POST': form = AuthenticationForm(data=request.POST) if form.is_valid(): username = form.cleaned_data.get('username') password = form.cleaned_data.get('password') guest = User.objects.get(username=username) role = guest.role user = authenticate(username=username, password=password) if user is not None: if role == 'Business Analyst': login(request, user) request.session['username'] = username return render(request,'index.html',{"username":username}) #return redirect('/home') elif role == 'Admin': login(request, user) request.session['username'] = username return redirect('/manageuser/') elif role == 'Manager': login(request, user) request.session['username'] = username return redirect('/approvallist/') elif role == 'Segment Manager': login(request, user) request.session['username'] = username return redirect('/approvallist/') else: messages.error(request, "Invalid username or password!") else: messages.error(request, "Invalid username or password!") form = AuthenticationForm() return render(request,"login.html",{"form":form}) #page when you success login def index_view(request): if request.session.has_key('username'): username = request.session['username'] return render(request,'index.html',{"username":username}) else: return redirect('/') … -
Getting validation error field can not be null, even if null=True in model
I've a foreign key in my model and this field can be null. status = models.ForeignKey(Status, on_delete=models.SET_NULL, null=True, blank=True, related_name="status") When i send a request with this field as null i get validation error saying [ { "status": [ "This field may not be null." ] } ] Even though I have set null=True I'm not sure why it's throwing me that validation error? Can anyone please help me with this. -
How to create a validation check that ensures the right-formatted directory path is stored and if it contains a file extension in Django?
I have a template that allows a user to store a pathname of a directory in my model (the directory should be available/exist in the server for a website or seen in a local machine). Before saving the path to the model, I need to ensure whether if the right format for the directory is being saved. Example: var/www/html/media/product or C:\Users\Danny\Desktop\folder. There shouldn't be any irregular strings, expressions or invalid format seen in the path like var/www/html/media/product\pic/... Moreover, I want to stop users if they want to save a specific directory path that contains a file extension. Example: var/www/html/media/product/file.<'file extension'> ('file.png', top.txt', 'random.jpg', etc...) How can this be done in my views.py code? Currently, this is what I did so far: views.py: def dashboard(request): if request.method == 'POST': form = PathForm(request.POST) if form.is_valid(): path = form.cleaned_data['path'] #CharField that stores the path name in model from form. #Two checks required. Need to see if it is a valid directory path format or if the path contains a general path directory. Not specific files (like images, text, csv file) should be seen in the path. #if file path contains a file extension at end. This is tedious since I need include all … -
Django: Get last record by ID [many-to-one relationship]
I'm trying to get the last record in one table connected to another one using many-to-one relationship in django models. Here's my django models: class DataCollecttion(models.Model): default_name = models.CharField(max_length=100) class NameHistory(models.Model): old_name = models.CharField(max_length=100) collection_data = models.ForeignKey(DataCollection, on_delete=models.CASCADE, null=True) Here I created a sample data for DataCollection table: And here's the sample data for NameHistory table: What I want here is to filter or get the last record in NameHistory in each collection_data_id (the records inside the red rectangle) and display it in my views. So in short I want to get these lines and how can I do it in ORM Query: sample3 test2 data1 -
A mistake on django "'django.forms.models' has no attribute 'Model'
[whats appears on the terminal ][1] i cant solve this error when i write the comand python manage.py makemigrations polls [1]: https://i.stack.imgur.com/brkOJ.png python manage.py makemigrations polls -
How do i host a django website via filezilla?
I am trying to host a django website via filezilla using a2hosting server.Steps i followed are given below 1. Uploaded my website from local host to remote site via filezilla. 2. Install all django requirements via putty. 3. Add allowed host as "mydomain". 4.Run server using the command "python3 manage.py runserver myip:8000 now i can access my website.But the problem is after stop running the server.It shows "404 Not Found Nginx/1.10.3 (Ubuntu)" error message. How do i resolve this issue? -
Static Files not saving on S3 bucket using cookiecutter-django
I'm trying to deploy my project on Heroku. I ran heroku run python3 manage.py collectstatic after deploying it. I have this on config/base.py STATIC_ROOT = str(ROOT_DIR("staticfiles")) STATIC_URL = "/static/" STATICFILES_DIRS = [str(APPS_DIR.path("static"))] STATICFILES_FINDERS = [ "django.contrib.staticfiles.finders.FileSystemFinder", "django.contrib.staticfiles.finders.AppDirectoriesFinder", ] This is on the config/production.py BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__))) INSTALLED_APPS += ["storages"] # noqa F405 AWS_ACCESS_KEY_ID = env("DJANGO_AWS_ACCESS_KEY_ID") AWS_SECRET_ACCESS_KEY = env("DJANGO_AWS_SECRET_ACCESS_KEY") AWS_STORAGE_BUCKET_NAME = env("DJANGO_AWS_STORAGE_BUCKET_NAME") AWS_QUERYSTRING_AUTH = False _AWS_EXPIRY = 60 * 60 * 24 * 7 AWS_S3_OBJECT_PARAMETERS = { "CacheControl": f"max-age={_AWS_EXPIRY}, s-maxage={_AWS_EXPIRY}, must-revalidate" } AWS_DEFAULT_ACL = None AWS_S3_REGION_NAME = env("DJANGO_AWS_S3_REGION_NAME", default=None) STATICFILES_STORAGE = "whitenoise.storage.CompressedManifestStaticFilesStorage" from storages.backends.s3boto3 import S3Boto3Storage # noqa E402 class StaticRootS3Boto3Storage(S3Boto3Storage): location = "static" default_acl = "public-read" class MediaRootS3Boto3Storage(S3Boto3Storage): location = "media" file_overwrite = False DEFAULT_FILE_STORAGE = "config.settings.production.MediaRootS3Boto3Storage" MEDIA_URL = f"https://{AWS_STORAGE_BUCKET_NAME}.s3.amazonaws.com/media/" These are my heroku env variables I generated this using cookiecutter-django. Everything works fine on my localhost but when I deploy it to heroku, it doesn't save the static files. -
I keep getting below error when starting django server. Below is a full trace of the error. Please let me know what could fix this issue
(env) C:\Users\LENOVO\Desktop\SD\backend>python manage.py runserver Watching for file changes with StatReloader Exception in thread django-main-thread: Traceback (most recent call last): File "C:\Users\LENOVO\AppData\Local\Programs\Python\Python38-32\lib\threading.py", line 932, in _bootstrap_inner self.run() File "C:\Users\LENOVO\AppData\Local\Programs\Python\Python38-32\lib\threading.py", line 870, in run self._target(*self._args, **self._kwargs) File "C:\Users\LENOVO\Desktop\SD\backend\env\lib\site-packages\django\utils\autoreload.py", line 54, in wrapper fn(*args, **kwargs) File "C:\Users\LENOVO\Desktop\SD\backend\env\lib\site-packages\django\core\management\commands\runserver.py", line 109, in inner_run autoreload.raise_last_exception() File "C:\Users\LENOVO\Desktop\SD\backend\env\lib\site-packages\django\utils\autoreload.py", line 77, in raise_last_exception raise _exception[1] File "C:\Users\LENOVO\Desktop\SD\backend\env\lib\site-packages\django\core\management\__init__.py", line 337, in execute autoreload.check_errors(django.setup)() File "C:\Users\LENOVO\Desktop\SD\backend\env\lib\site-packages\django\utils\autoreload.py", line 54, in wrapper fn(*args, **kwargs) File "C:\Users\LENOVO\Desktop\SD\backend\env\lib\site-packages\django\__init__.py", line 24, in setup apps.populate(settings.INSTALLED_APPS) File "C:\Users\LENOVO\Desktop\SD\backend\env\lib\site-packages\django\apps\registry.py", line 91, in populate app_config = AppConfig.create(entry) File "C:\Users\LENOVO\Desktop\SD\backend\env\lib\site-packages\django\apps\config.py", line 116, in create mod = import_module(mod_path) File "C:\Users\LENOVO\AppData\Local\Programs\Python\Python38-32\lib\importlib\__init__.py", line 127, in import_module return _bootstrap._gcd_import(name[level:], package, level) File "<frozen importlib._bootstrap>", line 1014, in _gcd_import File "<frozen importlib._bootstrap>", line 991, in _find_and_load File "<frozen importlib._bootstrap>", line 975, in _find_and_load_unlocked File "<frozen importlib._bootstrap>", line 671, in _load_unlocked File "<frozen importlib._bootstrap_external>", line 783, in exec_module File "<frozen importlib._bootstrap>", line 219, in _call_with_frames_removed File "C:\Users\LENOVO\Desktop\SD\backend\env\lib\site-packages\channels\apps.py", line 6, in <module> import daphne.server File "C:\Users\LENOVO\Desktop\SD\backend\env\lib\site-packages\daphne\server.py", line 18, in asyncioreactor.install() File "C:\Users\LENOVO\Desktop\SD\backend\env\lib\site-packages\twisted\internet\asyncioreactor.py", line 320, in install reactor = AsyncioSelectorReactor(eventloop) File "C:\Users\LENOVO\Desktop\SD\backend\env\lib\site-packages\twisted\internet\asyncioreactor.py", line 69, in init super().init() File "C:\Users\LENOVO\Desktop\SD\backend\env\lib\site-packages\twisted\internet\base.py", line 571, in init self.installWaker() File "C:\Users\LENOVO\Desktop\SD\backend\env\lib\site-packages\twisted\internet\posixbase.py", line 286, in installWaker self.addReader(self.waker) File "C:\Users\LENOVO\Desktop\SD\backend\env\lib\site-packages\twisted\internet\asyncioreactor.py", line 151, in addReader self._asyncioEventloop.add_reader(fd, … -
Define a path for a file in python script on heroku
I have a text file in a folder inside of my app in a django project. I am using Heroku bash to run a script that reads the text file and populate the data into the database. on my machine I have defined this: file=open(os.path.join(settings.BASE_DIR,'myappfolder/folder_name/data.txt'),'r',encoding="utf8") It works on my local but when I run it in the heroku using bash it replies: FileNotFoundError: [Errno 2] No such file or directory: '/app/myappfolder\\folder_name\\data.txt' Could tell me how can I modify in a way that it works on my heroku app and also my local machine? -
How to sync local Django sqlite3 data with Heroku's postgres database?
I have a Django website served by Heroku with a model storing data about projects that I've worked on in the past. I already ran makemigrations and migrate locally before pushing to heroku with git and running heroku run python3 manage.py migrate. So, my database models and fields are synced, but I'm asking about the field values. Whenever I update the value of a field for a model instance locally, I want it (the data) to sync with Heroku, and vice versa–sync values I've updated on Heroku in the admin panel with my local sqlite3 database. Is there a command for updating the values of the database itself, or am I missing something? Because I've looked all over the internet for the last hour for how to do this one thing. Side note: I also want the command I'm looking for to sync newly created instances, not just data for existing model instances. -
Python3 Django issues regarding paths and custom decorators
Rather new to Django first time using is. Python is not my strong point in a web context - i'm having issues with my custom decorator I made that will decode the jwt from all requests. decorators.py from django.core.exceptions import PermissionDenied import jwt def verify_token(function): def wrap(request, *args, **kwargs): if request: print('========='.format(request)) jwt.decode(request, 'secret', algorithms=['HS256']) else: raise PermissionDenied wrap.__doc__ = function.__doc__ wrap.__name__ = function.__name__ return wrap views.py from .User_Predictions.PredictionService import PredicitonController from django.http import JsonResponse from rest_framework.views import APIView from .decorators import verify_token class UserPredictions(APIView): @verify_token def generate_full_report(request): _predction = PredicitonController() results = _predction.compile_complete_predition() return JsonResponse(results, safe=False) urls.py from django.urls import path from .views import UserPredictions urlpatterns = [ path('compilePredictions/', UserPredictions.generate_full_report, name='generate_full_report') ] . ├── Analytics │ ├── __init__.py │ ├── __pycache__ │ │ ├── __init__.cpython-37.pyc │ │ ├── settings.cpython-37.pyc │ │ ├── urls.cpython-37.pyc │ │ └── wsgi.cpython-37.pyc │ ├── settings.py │ ├── urls.py │ └── wsgi.py ├── authentication │ ├── admin.py │ ├── apps.py │ ├── __init__.py │ ├── migrations │ │ └── __init__.py │ ├── models.py │ ├── tests.py │ └── views.py ├── biometrics │ ├── admin.py │ ├── apps.py │ ├── bodyfatPrediciton.py │ ├── Config.py │ ├── __init__.py │ ├── models.py │ ├── templates │ │ ├── … -
Django template won't render form errors
After a user has submitted a form with data that fails validation, form.errors in fact collects those errors as I've been debugging the issue. However when I render the page after a POST request, the errors will not be parsed in HTML alongside the fields where errors occur. What needs to change in order for the validation errors to render in the template when user data doesn't pass validation? # view that renders the template @login_required(login_url="/accounts/sign_in/") def new_profile(request, username): form = ProfileForm() import pdb; pdb.set_trace() if request.method == 'POST': user_profile = ProfileForm(request.POST) if user_profile.is_valid(): user_profile.cleaned_data.update(user=request.user) Profile.objects.create(**user_profile.cleaned_data) return HttpResponseRedirect( reverse("accounts:profile", kwargs={'username': username}) ) return render(request, 'accounts/create_profile.html', {'form': form}) # create_profile.html {% extends 'layout.html' %} {% block body %} <form action="{% url 'accounts:new_profile' username=user %}" method="post"> {% csrf_token %} {{ form }} <button type="submit">Submit</button> </form> {% endblock %} -> if request.method == 'POST': (Pdb) n -> user_profile = ProfileForm(request.POST) (Pdb) n -> if user_profile.is_valid(): (Pdb) p user_profile.errors {'birth': ['Enter a valid date.'], 'bio': ['Add more detail to your bio.']} -
How to group products by sellers in django
I am working on a multivendor ecommerce project for academic perspective.I am very beginner in Django. I am struck into this problem.Pls someone help. Here is the models for my Order. In the Order model i have items which is a Many to Many relationship with OrderItem. In OrderItem there is a field item which relates to the Product model. The product model holds the seller information and price. I want my products show on the order-summary grouped by the seller. And create different invoices for each of the sellers. But cannot find how to do that. I want to do something like the following snippet: Seller 1: Invoice Id- ____ Total Price:____ , ProductName - Quantity- Price, ProductName - Quantity- Price, ProductName - Quantity- Price Seller 2: Invoice Id- ____ Total Price:____ ,ProductName - Quantity- Price, ProductName - Quantity- Price The models for my Order app: class Order(models.Model): user = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.CASCADE) items = models.ManyToManyField(OrderItem) start_date = models.DateTimeField(auto_now_add=True) ordered_date = models.DateTimeField() ordered = models.BooleanField(default=False) billing_address = models.ForeignKey( 'BillingAddress', on_delete=models.SET_NULL, blank=True, null=True) class OrderItem(models.Model): user = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.CASCADE) item = models.ForeignKey(Product, on_delete=models.CASCADE) quantity = models.IntegerField(default=1) ordered = models.BooleanField(default=False) class Product(models.Model): name = models.CharField(max_length=50) category = models.ForeignKey(Category, on_delete=models.CASCADE, null=True) price = … -
When to use render and when to use redirect if you want to create login with session
so i want to make a login with a session , but i dont know when to use render or when to use redirect , here's the code def login_view(request): if request.method == 'POST': form = AuthenticationForm(data=request.POST) if form.is_valid(): username = form.cleaned_data.get('username') password = form.cleaned_data.get('password') guest = User.objects.get(username=username) role = guest.role user = authenticate(username=username, password=password) if user is not None: if role == 'Business Analyst': login(request, user) request.session['username'] = username return render(request,'index.html',{"username":username}) #return redirect('/home') elif role == 'Admin': login(request, user) request.session['username'] = username #return redirect('/manageuser/') elif role == 'Manager': login(request, user) request.session['username'] = username # return redirect('/approvallist/') elif role == 'Segment Manager': login(request, user) request.session['username'] = username #return redirect('/approvallist/') else: messages.error(request, "Invalid username or password!") else: messages.error(request, "Invalid username or password!") form = AuthenticationForm() return render(request,"login.html",{"form":form}) def index_view(request): #if request.session.has_key('username'): # username = request.session['username'] # return render(request,'index.html',{"username":username}) #else: # return render(request,'login.html',{}) return render(request,'index.html') am i doing this right? about the use of return render? or i must use return redirect? -
Spanning two multi-valued relationships in the same query [Django]
I can span foreign key relationships in django filters like this: brand_asset__business_unit__in=user.owner_for_business_units.id If the last item returns multiple values, I can use __in and all() brand_asset__business_unit__in=user.owner_for_business_units.all() How do I span two m2m relationships in a Teachers have a m2m relationship with I looked through the documentation but it deals with spanning one m2m relationship. -
Getting multiple queryset list of single model
I have a model say: class Abc(models.model): .... ..... Now When performing query(let go all the imports): print(Abc.objects.all()) I am getting multiple list of querySet: Output as <QuerySet [<Abc: ...>, <Abc: .....> , .....]> <QuerySet [<Abc: ...>, <Abc: .....> , .....]> I have to User so I am getting 2 different QuerySet. How can I get all the user's querySet in single list, Wanted output as: <QuerySet [<Abc: ...>, <Abc: .....> , .....]>, <QuerySet [<Abc: ...>, <Abc: .....> , .....]> or in a single list <QuerySet [<Abc: ...>, <Abc: .....> , .....]> But from my knowledge a model should list all the querySet in single list , why am I getting multiple list ? Image of my model and error -
Plotting a timestamp with django and matplotlib
I'm having some trouble creating a view in django, I'm trying to make a web app which will read in from a csv and then display the plot, however the time axis I need to plot from the csv is not a float it is a string, then way I have it here I'm not sure how to plot this timestamp: def showMe(request): fig = Figure() canvas = FigureCanvas(fig) x, y = np.loadtxt('/Users/name/Desktop/garden_app/stored.csv', delimiter=',', dtype={'names': ('time','moisture'), 'formats': ('|S1', np.float)}, unpack=True) plt.plot(x, y, align='center', alpha=0.5, label='Name') plt.ylabel('moisture') plt.xlabel('time') plt.title('Moisture V. Time') buf = io.BytesIO() plt.savefig(buf, format='png') plt.close(fig) response = HttpResponse(buf.getValue(), content_type = 'image/png') return response The csv file I have looks like this: moisture,time,pump,light,temperature 1023,2019-10-27 17:22:27.367391,running,5V,25 Celsius 1023,2019-10-27 17:22:30.402280,running,5V,25 Celsius ... The "ValueError: could not convert string to float: 'time'" comes from the 'formats': ('|S1', np.float) on line 4, I'm just not sure how to change this where one is a number and the other is the timestamp. -
Bulk Update of model fields baseds on user input in admin site
In django, let's say I have a model with an integerfield called "RouteNumber" in my model. I manage all the model entries in the django admin site and I want to assign a route number to more than 100 entries at a time. How can I do that based on a user input? I was thinking using an admin action that would request a number and that all the queryset would be assigned this value In my model.py: class Person(models.Model): Name = models.CharField("Nom du parent", max_length=40, default="") RouteNumber= models.IntegerField("Numéro de route", default=None, blank=True, null=True) In my admin.py: def assign_route_number # This is where I'm lost ==== number = user_input("Enter a route number") # ======== for obj in queryset: obj.RouteNumber = number obj.save() However I don't know how to get the user input. Is there an easy way to get that? Thank you for your answers -
Django error 'ManagerDescriptor' object has no attribute 'filter'
I am relatively new to django and am running into the error 'ManagerDescriptor' object has no attribute 'filter' when retrieving view 'dashboard' -- below is my view and model. Can anyone point me in the right direction here? Thanks! #views.py def dashboard(request): tabledata_totals = '' if not request.user.is_authenticated: return redirect(settings.LOGIN_URL, request.path) else: orgs = Profile.objects.values_list('assigned_org_ids', 'view_group').get(user_id=request.user.id) tabledata_totals = org_totals.objects.filter(org_id__in=orgs[0].split(',')).aggregate( sum('open_supplement_count'), sum('open_estimate_count'), sum('open_measurement_count'), sum('total_open_count'), sum('supplement_sent_to_ins'), sum('revised_scope_received_additional_items_needed'), sum('homeowner_permission_needed'), sum('three_calls_to_adjuster_without_response'), sum('spoke_to_adjuster'), sum('missing_documents_required_for_supplementation'), sum('wWaiting_on_a_revised_scope'), sum('estimate_created_and_sent_to_customer'), sum('deal_in'), sum('supplement_complete'), sum('eagleview_measurements'), sum('confirmed_received'), sum('confirmed_assigned_to_adjuster'), sum('additional_documentation_needed') ) return render(request, 'HTML/dashboard.html', {'data': tabledata_totals}) #models.py @login_required(login_url='/login/') class org_totals(models.Model): organization = models.CharField(max_length=100, blank=True, null=True) org_id = models.SmallIntegerField(primary_key=True) open_supplement_count = models.SmallIntegerField(blank=True, null=True) open_estimate_count = models.SmallIntegerField(blank=True, null=True) open_measurement_count = models.SmallIntegerField(blank=True, null=True) total_open_count = models.SmallIntegerField(blank=True, null=True) Supplement_Sent_to_Ins = models.SmallIntegerField(blank=True, null=True) Revised_Scope_Received_Additional_Items_Needed = models.SmallIntegerField(blank=True, null=True) Homeowner_Permission_Needed = models.SmallIntegerField(blank=True, null=True) three_Calls_to_Adjuster_Without_Response = models.SmallIntegerField(blank=True, null=True) Spoke_to_Adjuster = models.SmallIntegerField(blank=True, null=True) Missing_Documents_Required_for_Supplementation = models.SmallIntegerField(blank=True, null=True) Waiting_on_a_Revised_Scope = models.SmallIntegerField(blank=True, null=True) Estimate_Created_and_Sent_to_Customer = models.SmallIntegerField(blank=True, null=True) Deal_In = models.SmallIntegerField(blank=True, null=True) Supplement_Complete = models.SmallIntegerField(blank=True, null=True) Eagleview_Measurements = models.SmallIntegerField(blank=True, null=True) Confirmed_Received = models.SmallIntegerField(blank=True, null=True) Confirmed_Assigned_to_Adjuster = models.SmallIntegerField(blank=True, null=True) Additional_Documentation_Needed = models.SmallIntegerField(blank=True, null=True) class Meta: managed = False db_table = 'org_open_totals'