Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
How to download pdf from huge data in efficient way in django?
How can we download or generate pdf from huge data in Django in an efficient way? I'm having huge records like in millions and I want to generate pdf from data,As of now pdf is generating but it takes time to download, does an one know the efficient way or any alternative way to download pdf in more faster -
Django Filter based on 2 fields
I have a model where I can set expire_date_1 and expire_date_2. And 2 filters like this. filter_1 = Q(expire_date_1__isnull=False) & Q(expire_date_1__lte=after_30days) filter_2 = Q(expire_date_2__isnull=False) & Q(expire_date_2__lte=after_30days) I want to filter the model that if expire_date_2 is not null then using filter_2 else use filter_1 I tried it to do with Case and When but I can't filter in a When function, can I? -
CORS issue in django
settings.py INSTALLED_APPS = [ ... 'corsheaders', ] MIDDLEWARE = [ 'django.middleware.security.SecurityMiddleware', 'django.contrib.sessions.middleware.SessionMiddleware', 'corsheaders.middleware.CorsMiddleware', 'django.middleware.common.CommonMiddleware', ... ] ALLOWED_HOSTS = ['*'] CORS_ORIGIN_ALLOW_ALL = True ajax request $.ajax({ type: "POST", url: `https://example.com/requestlink/`, crossDomain: true, data: { link: link, csrfmiddlewaretoken: csrf, }, success: function (data) { if (data) { data.forEach(src => { createresult(src); }) } icon.classList.replace('loading', 'search'); }, error: function (data) { icon.classList.replace('loading', 'search'); } }) Now when i do ajax post request, I got this in console tab Status 403 Forbidden Version HTTP/1.1 Transferred 1.53 KB (2.50 KB size) Referrer Policy no-referrer-when-downgrade and this in backend Forbidden (Referer checking failed - https:// anotherexample.com / does not match any trusted origins.): /requestlink/ Why so? -
Django - Compare Queryset with JSON data to make update operations
I have a dynamic form as JSON. When input added, JSON data has more items than Queryset. When input deleted, JSON data has less items than Queryset. My code as below: selectedUserForm = UserMeta.objects.filter(user=selectedUser, isDeleted = False) for form in selectedUserForm: if getJson['Id'] == form.id: formData = UserMeta.objects.filter(id=form.id).update(metaVal=getJson['Input'].title(), metaKey=getJson['Label']title()) elif getJson['Id'] == 0: formData = UserMeta(user = selectedUser, metaVal=getJson['Input'].title(), metaKey=form.Label.title()) try: formData.full_clean() formData.save() output.append({'Dynamic Form: Added! ': str(formData)}) except ValidationError as e: output.append({'Error': e}) return HttpResponse(e) elif getJson['Id'] != form.id: formData = UserMeta.objects.filter(id=form.id).update(isDeleted = True) It won't work because there is no iteration for JSON variable but when I add counter to iterate JSON data it gives error as "JSON data out of index" if JSON data has less items. Also, if JSON has more data, iteration cannot reach to those items. What is the proper approach to make update operation? -
Django: Prefetch Related multiple reverse relationships
I have the following models: class Animal(models.Model): name = models.CharField(max_length=256, blank=True, null=True) class Carnivore(models.Model): name = models.CharField(max_length=256, blank=True, null=True) animal = models.ForeignKey(Animal) testing_params = models.ForeignKey(TestParams, blank=True, null=True) class TestParams(models.Model): params_1 = models.CharField(max_length=256, blank=True, null=True) params_2 = models.CharField(max_length=256, blank=True, null=True) class Metrics(models.Model): carnivore = models.ForeignKey(Carnivore, null=True, blank=True) Now I want to prefetch carnivore animal, metrics for TestParams filter objects. So I am doing the following: test_params = TestParams.objects.filter(**filters) test_params_data = test_params.prefetch_related("carnivore_set", "carnivore_set__animal", "carnivore_set__metrics_set") But I am only getting carnivore_set in _prefetched_objects_cache parameter when I loop over the test_params_data and print each instance's __dict__. So how can I get multi level reverse relationships in prefetch_related? -
Css & Js not loading in Django cpanel
I just upload django project to cpanel but css & js not loading. this my path <link rel="stylesheet" type="text/css" href="/static/css/forms/switches.css%20"> my static folder is in public_html STATIC_URL = '/static/' -
How Do I Accept Nested JSON Data in django REST framework
I need to accept a user data via API in a django app using django-rest-framework, but the problem is that my server returns this error each time I make a POST request. My server always returns the error { "detail": "JSON parse error - Expecting property name enclosed in double quotes: line 2 column 1 (char 2)" } After a few research, I realized that this request data couldn't be parsed as a result of the presence of the square bracket in the JSON data value. Here is my serializers classes: app/serializers.py class ProfileSerializer(serializers.ModelSerializer): class Meta: model = ProfileModel fields = ['age', '', 'reputation', 'date', 'confirmation'] class UserSerializer(serializers.ModelSerializer): profile = ProfileSerializer() class Meta: model = UserModel fields = '__all__' Here is also an example of my JSON request data: { "user": "John Doe", "profile": [ { "age": 28, "reputation": "https://www.example.com", "date": "2021-02-27 15:05:02", "confirmation": 1 } ], "last_updated_date": "2021-09-27 15:05:02" } The question is how do I make the REST framework ignore the structure of the nested data or make it accept the square bracket([]) int the JSON data?. -
Using select_related in django for a specific use case?
I have these two models and I am trying to build up the logic of given the combination of days ( e.x., Mon-Tue 2-3 pm) I want to find out all the instructor names. I am unable to do that. I have tried using select_related but I am not able to use it properly I think. :) class TimeSlot(models.Model): instructor = models.ForeignKey('Instructor', on_delete=models.PROTECT) day = models.CharField(max_length=10, choices=WEEKDAYS) start_time = models.TimeField() end_time = models.TimeField() class Instructor(models.Model): name = models.CharField(max_length=50, validators=[validate_instructor_name]) -
django-smart-selects not working properly with jquery.formset.js django
I am a beginner in django. I have created a form using inlineformset_factory with jquery.formset.js library for increasing rows. The price field uses django-smart-selects where depending on the product selected, the available prices are populated in the price field. Everything works fine for the first row but for any other new row added, the django-smart-selects price field no longer works. Also, when I delete the first row and re-add it, the django-smart-selects no longer works. I want the price field to keep working on each row depending on what product is selected. Below are my codes: urls.py from django.contrib import admin from django.urls import path from django.conf.urls import url, include from django.conf import settings urlpatterns = [ path('admin/', admin.site.urls), url(r'^chaining/', include('smart_selects.urls')), ] models.py class InventoryItem(models.Model): date = models.DateField(default=timezone.now) product_name = models.TextField(blank=False, unique=True) sales_price = models.DecimalField(_(u'Selling Price'), decimal_places=2, max_digits=12, validators=[MinValueValidator(Decimal('0.01'))]) objects = models.Manager() class Price(models.Model): product_id = models.ForeignKey(InventoryItem, on_delete=models.DO_NOTHING, verbose_name='Item Name') selling_price = models.DecimalField(_(u'Price'), decimal_places=2, max_digits=12, validators=[MinValueValidator(Decimal('0.01'))], blank=False, default=0) objects = models.Manager() class Invoice(models.Model): customer_name = models.TextField(blank=False, unique=True) objects = models.Manager() class InvoiceItem(models.Model): invoice = models.ForeignKey(Invoice, on_delete=models.CASCADE) quantity = models.PositiveIntegerField(blank=False) product_id = models.ForeignKey(InventoryItem, on_delete=models.DO_NOTHING, verbose_name='Item Name') price = ChainedForeignKey(Price, chained_field="product_id", chained_model_field="product_id", show_all=False, auto_choose=True, sort=True, default=0) objects = models.Manager() forms.py class InvoiceItemForm(ModelForm): … -
AttributeError: 'FileUploadSerializer' object has no attribute 'create_df'
class UploadFileView(generics.CreateAPIView): serializer_class = FileUploadSerializer @method_decorator(name='post', decorator=swagger_auto_schema( operation_id='Import operatives from csv', operation_description="Requires key 'csv' in form-data" )) def create(self, request, *args, **kwargs): serializer = FileUploadSerializer(data=request.data) if serializer.is_valid(): errors = serializer.create_df(request.files.get("csv")) if errors: return Response(errors, status=status.HTTP_400_BAD_REQUEST) serializer.prepare_df() serializer.validate_duplicate_emails() data = serializer.df.to_dict('records') file_serializer = FileUploadSerializer(data=data, many=True) file_serializer.is_valid() serializer.add_error_messages(file_serializer.errors) if serializer.error_messages: return Response(serializer.error.messages, status=status.HTTP_409_CONFLICT) else: file_serializer.save() return Response(file_serializer.data, status=status.HTTP_200_OK) return Response(serializere.errors, status=status.HTTP_400_BAD_REQUEST) It looks like your post is mostly code; please add some more details. -
How to sort table in columns using Django?
I have some tables in html like this: ... <th> <div class="d-flex align-items-center"> <p class="fw-normal size-12 text-label mb-0 d-inline-block"></p> <i class="fas fa-arrow-down ms-2 text-gray-dark size-12"></i> </div> </th> ... I want to sort them using an arrow, but I have to use Django here. I didn't find much materials online. Any suggestion? -
How can I replace Email with Phone Number in Django Rest Framework's Forgot Password Module
I have developed an app using ReactJS and Django Rest Framework. Problem: For Forgot Password functionality, we're using the built in module which requires email. The link is propagated to the given email. I want to do this via phone number only. Is it possible? -
How to display data from parent model using foreign key django
I want to display the child model data with the parent model data as well in a queryset. This is my models in model.py class Shareholders(models.Model): sharehold_IC = models.CharField(primary_key=True, unique=True, validators=[RegexValidator(r'^\d{12,12}$'), only_int], max_length=12) sharehold_name = models.CharField(max_length=100, null=True) sharehold_email = models.CharField(max_length=50, null=True, unique=True) sharehold_address = models.TextField(null=True, blank=True) password = models.CharField(max_length=100) def __str__(self): return self.sharehold_name class Meeting(models.Model): MEETING_STATUS = ( ('Coming Soon', 'Coming Soon'), ('Live', 'Live'), ('Closed', 'Closed') ) meeting_ID = models.CharField(primary_key=True, max_length=6, validators=[RegexValidator(r'^\d{6,6}$')]) meeting_title = models.CharField(max_length=400, null=True) meeting_date = models.DateField() meeting_time = models.TimeField() meeting_desc = models.CharField(max_length=500, null=True) meeting_status = models.CharField(max_length=200, null=True, choices=MEETING_STATUS) date_created = models.DateTimeField(default=timezone.now, null=True) def __str__(self): return self.meeting_ID class Question(models.Model): question_ID = models.AutoField(primary_key=True) question = models.CharField(max_length=400, null=True) meeting_id = models.ForeignKey(Meeting, on_delete=CASCADE) shareholder_IC = models.ForeignKey(Shareholders_Meeting, on_delete=CASCADE, related_name='shareholder_ic') date_created = models.DateTimeField(default=timezone.now, null=True) def __str__(self): return str(self.meeting_id) I try to display all the data from the Question model with the shareholders details such as sharehold_name from the Shareholders model. This is how I try to do in Views.py. Views.py def getMessages(response, meeting_id): meeting = Meeting.objects.get(meeting_ID=meeting_id) questions = Question_Meeting.objects.filter(meeting_id=meeting.meeting_ID) # print(list(questions.values('shareholder_IC_id'))) for i in questions: print(i.shareholder_ic.all()) return JsonResponse({"questions":list(questions.values())}) But somehow I got this error AttributeError: 'Question' object has no attribute 'shareholder_ic'. I want to get the result like this: {'question_ID': 141, 'question': "I'm … -
Django perform Annotate , count and Compare
I have following Model. class Gallery(BaseModel): company = models.ForeignKey(to=Company, on_delete=models.CASCADE) image = models.ImageField( upload_to=upload_company_image_to, validators=[validate_image] ) def __str__(self): return f'{self.company.name}' I want to allow maximum upto 5 image to be uploaded by one company so I tried my query as def clean(self): print(Gallery.objects.values('company').annotate(Count('image')).count()) I don't know how to compare above query with Integer 5. How do I do that? -
Found array with 0 sample(s) (shape=(0, 5880)) while a minimum of 1 is required by MinMaxScaler
Hope you people are doing well I found this error==> "Found array with 0 sample(s) (shape=(0, 5880)) while a minimum of 1 is required by MinMaxScaler." Here I am Stuck that I did not know what to do: I am using Django Development and deploy my ML Model: here is the code of my model: CODE import numpy as np import pandas as pd def series_to_supervised(df, cols_in, cols_out, days_in=1, days_out=1): # input sequence (t-n, ... t-1) cols, names = list(), list() for i in range(days_in, 0, -1): cols.append(df.shift(i)) names += [('{}(t-{})'.format(j, i)) for j in cols_in] # concatenate input sequence partial_in = pd.concat(cols, axis=1) partial_in.columns = names # forecast sequence (t, t+1, ... t+n) df = df.filter(items=cols_out) cols, names = list(), list() for i in range(0, days_out): cols.append(df.shift(-i)) if i == 0: names += [('{}(t)'.format(j)) for j in cols_out] else: names += [('{}(t+{})'.format(j, i)) for j in cols_out] # concatenate forecast sequence partial_out = pd.concat(cols, axis=1) partial_out.columns = names return partial_in.join(partial_out).dropna() def transform_data(df, cols, scaler, n_days_past=120): n_cols = len(cols) # df to np array np_arr = np.array(df.values.flatten().tolist()) np_arr = scaler.transform([np_arr]) np_arr = np_arr.reshape((np_arr.shape[0], n_days_past, n_cols)) return np_arr def transform_predictions(pred_df, cols, scaler, n_days_future=30): n_cols = len(cols) # np array to df … -
Django slider widget default value
Using django I have implemented a slider for a form, that is presented as part of a formset so as to enable users to add additional rows using jquery. My issue is that although the model has the default value as ‘0’, and this is what the first row displays, when I add additional rows the slider is at the midpoint (’50’). Can anyone advise how to make additional rows also start at ‘0’. models.py class SideEffect(TimeStampedModel): concern = models.IntegerField(default=0) patient = models.ForeignKey(Patient, on_delete=models.CASCADE) widgets.py from django.forms.widgets import NumberInput class RangeInput(NumberInput): input_type = 'range' forms.py SideeffectFormSet = inlineformset_factory( Patient, SideEffect, fields=("se_name", "timepoint", "concern"), widgets={'concern': RangeInput()}, extra=0, min_num=1, validate_min=True, ) -
WSGI ERROR :Target WSGI script cannot be loaded as Python module
I am trying to deploy a Django application using apache and i am getting the following error [Fri Oct 08 07:55:44.393237 2021] [wsgi:error] [pid 12424:tid 140450959271680] mod_wsgi (pid=12424): Target WSGI script '/home/preinstall/hx_preinstaller/hx_preinstaller/wsgi.py' cannot be loaded as Python module. [Fri Oct 08 07:55:44.393281 2021] [wsgi:error] [pid 12424:tid 140450959271680] mod_wsgi (pid=12424): Exception occurred processing WSGI script '/home/preinstall/hx_preinstaller/hx_preinstaller/wsgi.py'. [Fri Oct 08 07:55:44.393408 2021] [wsgi:error] [pid 12424:tid 140450959271680] Traceback (most recent call last): [Fri Oct 08 07:55:44.393430 2021] [wsgi:error] [pid 12424:tid 140450959271680] File "/home/preinstall/hx_preinstaller/hx_preinstaller/wsgi.py", line 12, in <module> [Fri Oct 08 07:55:44.393435 2021] [wsgi:error] [pid 12424:tid 140450959271680] from django.core.wsgi import get_wsgi_application [Fri Oct 08 07:55:44.393446 2021] [wsgi:error] [pid 12424:tid 140450959271680] ModuleNotFoundError: No module named 'django' My apache virtual host <VirtualHost *:80> DocumentRoot /home/preinstall/hx_preinstaller ErrorLog ${APACHE_LOG_DIR}/preinstall_error.log CustomLog ${APACHE_LOG_DIR}/access.log combined <Directory /home/preinstall/hx_preinstaller/hx_preinstaller> <Files wsgi.py> Require all granted </Files> </Directory> <Directory /home/preinstall/hx_preinstaller> Require all granted </Directory> WSGIDaemonProcess preinstall python-path=/home/preinstall/hx_preinstaller:/home/preinstall/.local/lib/python3.6/site-packages WSGIProcessGroup preinstall WSGIPassAuthorization On WSGIScriptAlias / /home/preinstall/hx_preinstaller/hx_preinstaller/wsgi.py </VirtualHost> What should i do?.. -
Django route giving 404
I've got a route registered in the urls.py file of my django main app as: router.register(r"visual/(?P<random_url>[\w]+)/$", views.LinkTest, basename="test") and the url patterns defineded as: urlpatterns = [ # Admin path("admin/", admin.site.urls), # Model API Routes path("rest/api/latest/", include(router.urls)) ] which means I should be able to hit the viewset via the following call http://localhost:8000/rest/api/latest/visual/random_string/ but I'm getting a 404 Can anyone tell me what I'm doing wrong? -
The one line if else elif not working in Django
After referring to this answer Tim Pietzcker, I implemented that code on my website. I'm not getting the proper solution for the same. Well, I try to implement if elif and else statement in one line Django. So I have tried this. views.py cart1 = CartTube.objects.values_list('tube__tubecode', flat = True) cart2 = CartDrum.objects.values_list('drum__drumcode', flat = True) machine = Machine.objects.filter(tubecode__in=cart1) if cart1 else Machine.objects.filter(drumcode__in=cart2) if cart2 else Machine.objects.filter(Q(tubecode__in=cart1) & Q(drumcode__in=cart2)) if cart1 else Machine.objects.all().order_by('id') Well, From the above code I'm trying to find a solution: If the user chooses Drum as a product then the same code should match with Machine and filter the exact matching product. and if, Drum product + Tube product is chosen then show the exact combination product from the Machine Since the individual code works perfectly. Down below are the code work perfectly. ✔️ machine = Machine.objects.filter(tubecode__in=cart1)if cart1 else Machine.objects.all().order_by('id') ✔️ machine = Machine.objects.filter(drumcode__in=cart2) if cart2 else Machine.objects.all().order_by('id') ✔️ machine = Machine.objects.filter(Q(tubecode__in=cart1) & Q(drumcode__in=cart2)) if cart1 else Machine.objects.all().order_by('id') Tell me where I'm going wrong -
import variables if file exists
I have two Python files on the same level in my Django app. settings.py SECRET.py I want to import the variables from SECRET.py in case the file exists. # This code checks if you have the SECRET.py file to connect to the live server if Path("SECRET.py").is_file(): print("Live Database") from .SECRET import * else: print("Local Database") NAME = 'blog_db' USER = 'postgres' PASSWORD = 'admin' HOST = 'localhost' PORT = '5432' DATABASES = { 'default': { 'ENGINE': 'django.db.backends.postgresql_psycopg2', 'NAME': NAME, 'USER': USER, 'PASSWORD': PASSWORD, 'HOST': HOST, 'PORT': PORT, } } The code keeps connecting to the local database; prints "Local Database", even though I have the SECRET.py file -
Deploy multi Django app on AWS with configuration per instance
I developed a Django+Vuejs app and time has come to try deploying it. The thing is that I want to have an instance of it running for each customer. So each customer would have : AWS RDS database (psql) Container running with the app (AWS ECS instance ?!) Customer 1 can be on v1.0 of my software while Customer 2 could be on v1.2. So they must have different containers (all my versions will be stored in AWS ECR). AWS S3 for their media files Its own subdomain (customer1.mydomain.com, customer2.mydomain.com, ...) While I've been able to build my container with the following Dockerfile : FROM node:lts-alpine as build-frontend-stage WORKDIR /frontend COPY ./frontend/package*.json /frontend/ RUN npm install COPY ./frontend . RUN npm run build FROM python:3.8.10-slim as build-backend-stage RUN apt-get update && apt-get install --yes --no-install-recommends \ g++ \ libpq-dev WORKDIR /backend RUN pip install --upgrade pip COPY ./backend/requirements.txt /backend RUN pip install -r requirements.txt COPY ./backend . COPY --from=build-frontend-stage /frontend/dist/static /backend/static COPY --from=build-frontend-stage /frontend/dist/index.html /backend/static I'm now wondering how can I run it with following questions : When starting the container, It should perform a manage.py migrate to apply migrations to the customer database (so that if I deploy a … -
How can I show help_text attribute through for loop in my template?
forms.py class UserRegistratiion(forms.Form): email = forms.EmailField() name = forms.CharField(help_text="80 Char Maximum") views.py def showFormData(request): fm = UserRegistratiion(auto_id="my_%s") return render(request, "blog/login.html", {"form":fm}) When i use this in my template it works fine and my help_text shows in span tag.. <form action=""> <div> {{form.as_p}} </div> But, whwn i use for loop {% for field in form.visible_fields %} <div> {{field.label_tag}} {{field}} </div> {% endfor %} help_text doesn't show how can i get this? -
form cannot redirect url after clicking on the button django
I have a web page as shown in the picture below, when I click on the add packing or picking button, it is supposed to redirect me to this url: http://127.0.0.1:8000/packing/13/ but it redirect me back to the home page url: http://127.0.0.1:8000/gallery/. How do i fix this issue? views.py @login_required() def packing(request, id): photo = get_object_or_404(Photo, id=id) if request.method == "POST": form = packingForm(request.POST, instance=photo) pickingform = pickingForm(request.POST, instance=photo) if form.is_valid(): if form != photo.packing: photo.status = 'Packing' photo.Datetime = datetime.now() form.save() if pickingform != photo.picking: photo.status = 'Picking' photo.Datetime = datetime.now() form.save() return redirect('gallery') else: form = packingForm(instance=photo) pickingform = pickingForm(instance=photo) context = { "form": form, "pickingform": pickingform } return render(request, 'packing.html', context) forms.py class packingForm(forms.ModelForm): packing = forms.CharField(label='', widget=forms.TextInput(attrs={"class": 'form-control', 'placeholder': 'Indicate packed if the item has been packed'})) class Meta: model = Photo fields = ("packing", ) def __init__(self, *args, **kwargs): super(packingForm, self).__init__(*args, **kwargs) self.fields['packing'].required = False #self.fields['picking'].required = False class pickingForm(forms.ModelForm): picking = forms.CharField(label='', widget=forms.TextInput(attrs={"class": 'form-control', 'placeholder': 'Indicate picked if the item has been picked'})) class Meta: model = Photo fields = ("picking",) def __init__(self, *args, **kwargs): super(pickingForm, self).__init__(*args, **kwargs) self.fields['picking'].required = False packing.html <!DOCTYPE html> <html> <head> <meta charset='utf-8'> <meta http-equiv='X-UA-Compatible' content='IE=edge'> <title>SCS Add Packing … -
I'm trying to add a new page in Django but getting 404 error yet I've added urls and views
I'm a newbie trying to add an a new page but the following error Page not found (404) Request Method: GET Request URL: http://127.0.0.1:8000/study Using the URLconf defined in student_management_system.urls, Django tried these URL patterns, in this order: I've added a function for the page in Views.py and also added the path in URLS.py StudentViews.py code-----> in student management app folder from django.shortcuts import render, redirect from django.http import HttpResponse, HttpResponseRedirect from django.contrib import messages from django.core.files.storage import FileSystemStorage # To upload Profile Picture from django.urls import reverse import datetime # To Parse input DateTime into Python Date Time Object from student_management_app.models import CustomUser, Staffs, Courses, Subjects, Students, Attendance, AttendanceReport, \ LeaveReportStudent, FeedBackStudent, StudentResult def study(request): return render(request, "student_template/study.html") Views.py ----->in student management app folder # from channels.auth import login, logout from django.contrib.auth import authenticate, login, logout from django.http import HttpResponseRedirect, HttpResponse from django.shortcuts import render, redirect from django.contrib import messages from student_management_app.EmailBackEnd import EmailBackEnd def home(request): return render(request, 'index.html') def loginPage(request): return render(request, 'login.html') def doLogin(request): if request.method != "POST": return HttpResponse("<h2>Method Not Allowed</h2>") else: user = EmailBackEnd.authenticate(request, username=request.POST.get('email'), password=request.POST.get('password')) if user != None: login(request, user) user_type = user.user_type #return HttpResponse("Email: "+request.POST.get('email')+ " Password: "+request.POST.get('password')) if user_type == '1': … -
how I can access class method variable in other class method in Python/Django
class Login_View(LoginView,FormView): template_name = 'app1/login.html' def form_valid(self, form): global login_user login_user = form.cleaned_data['username'] return super().form_valid(form) class DashboardView(ListView,Login_View): model = AllCompanies template_name = 'app1/dashboard.html' context_object_name = 'data' def get_queryset(self): return AllCompanies.objects.filter(user=login_user)