Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Problem with the grading queue in the online judge
I am working on creating an online judge using django and I have the following problem: Let's say I have a website that can score 6 (this number can be changed by admin) submissions at the same time. A user logged into the website can submit a submission for grading and if there are currently 6 submissions being graded it will enter something called a "queue" and wait for one of the submissions to finish scoring it will start dot. Same problem with multiple users submitting submissions to my website. How can I do that? (Here I treat grading as a "task", no matter what the task does.) -
How to redirect to another page with a search term?
I have a search engine that works great in home/views.py: def home(request): ... form = SearchForm() query = None results = [] if 'query' in request.GET: form = SearchForm(request.GET) if form.is_valid(): query = form.cleaned_data['query'] results = products.annotate( similarity=TrigramSimilarity('name', query), ).filter(similarity__gt=0.15).distinct().order_by('-similarity') # return render(request, 'search/search_results.html', locals()) return redirect(reverse('home:search_results')) else: form = SearchForm() ... return render(request, 'home/home.html', context) def search_results(request): form = SearchForm() query = None results = [] if 'query' in request.GET: form = SearchForm(request.GET) if form.is_valid(): query = form.cleaned_data['query'] results = products.annotate( similarity=TrigramSimilarity('name', query), ).filter(similarity__gt=0.15).distinct().order_by('-similarity') return render(request, 'search/search_results.html', locals()) else: form = SearchForm() return render(request, 'search/search_results.html', locals()) I also have in urls.py: app_name = 'home' urlpatterns = [ path('', views.home, name='home'), path('search_results/<query>', views.search_results, name='search_results'), ]\ + static(settings.STATIC_URL, document_root=settings.STATIC_ROOT) \ + static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT) How can I get a redirect to a page with url construction like this localhost/search_results/?query=['query']? -
Validation of Django Model form overwrie
Greeting people. I think this is pretty much a typical problem, but I can't find a way to solve it. Django admin has a model form, which always overwrites submitted fields. The most typical issue here is that user write changes that user didn't want to change (when data have been changed between opened and submit form) Do we have any best practice to avoide that? -
Django 'Upload a valid image' when using png and jpeg
I am trying to upload an image, when posting .gif it works, and not with jpeg and png -
How to load a trained model in django
I'm working on a django project where I have to use Doc2Vec model to predict most similar articles based on the user input. I have trained a model with the help of articles in our database and when I test that model using a python file .py by right clicking in the file and selecting run from the context menu its working. The problem is Now I'm moving that working code to a django function to load model and predict article based on user-given abstract text But I'm getting FileNotFoundError. I have searched how to load model in django and it seems the way is already OK. here is the complete exception: FileNotFoundError at /searchresult [Errno 2] No such file or directory: 'd2vmodel.model' Request Method: GET Request URL: http://127.0.0.1:8000/searchresult Django Version: 3.1.5 Exception Type: FileNotFoundError Exception Value: [Errno 2] No such file or directory: 'd2vmodel.model' Exception Location: C:\Users\INZIMAM_TARIQ\AppData\Roaming\Python\Python37\site-packages\smart_open\smart_open_lib.py, line 346, in _shortcut_open Python Executable: C:\Program Files\Python37\python.exe Python Version: 3.7.9 Python Path: ['D:\Web Work\doc2vec final submission', 'C:\Program Files\Python37\python37.zip', 'C:\Program Files\Python37\DLLs', 'C:\Program Files\Python37\lib', 'C:\Program Files\Python37', 'C:\Users\INZIMAM_TARIQ\AppData\Roaming\Python\Python37\site-packages', 'C:\Program Files\Python37\lib\site-packages'] Server time: Mon, 24 May 2021 12:44:47 +0000 D:\Web Work\doc2vec final submission\App\views.py, line 171, in searchresult model = Doc2Vec.load("d2vmodel.model") Here is my django function … -
How i can get plaint text from django-tinymce htmlfield?
I need to get only text from html field to add it to another field, to search from it so how can i do that? -
How do i have a different data for every account in Django
Excuse my lack of knowledge I'm a complete newbie to Backend Development. I've had this very simple model for testing class Text(models.Model): text = models.CharField(max_length=30) def __str__(self): return self.text And with that I have this simple app that saves text through a form and also I've made an entire basic login & sign up system with UserCreationForm and AuthenticationForm and with that I've made 3 different users. With my lack of knowledge, I'm expecting to see a completely fresh app with no text saved to it when I log in with brand new user. But instead I just saw the same texts saved as every other users. So my question is what Django method should I learn so that my text database is empty everytime I create a new user Thank you in advance -
How to get total in django template
My database have one col namely MaxSubjectMarks MaxSubjectMarks (Column name) 10 20 30 40 50 150 (I want 150 output) q = SubjectsMaximumMarks.objects.filter(SessionCode=SessionResult,ClassCode=StudentClass).values('MaxSubjectMarks').annotate(total=Sum("MaxSubjectMarks")) {{ q }} output => <QuerySet [{'MaxSubjectMarks': '10', 'total': 10.0}, {'MaxSubjectMarks': '20', 'total': 20.0}, {'MaxSubjectMarks': '30', 'total': 30.0}, {'MaxSubjectMarks': '40', 'total': 40.0}, {'MaxSubjectMarks': '50', 'total': 50.0}]> i want output Total = 150 -
Is there any way to join three tables for querying to find the aggregate sum of a field in django (query set api)?
i am a complete beginner in django i'm stuck with this problem and can't seem to find a solution to query it properly. T.T T.T django ver : 1.11 python ver : 2.7 let's say we have 3 models: class Coupon(models.Model): pass class CouponApplication(models.Model): """ Track application of a coupon. """ coupon = models.ForeignKey(Coupon, related_name="applications",verbose_name=("Coupon")) order = models.ForeignKey(Order, verbose_name=("Order")related_name='order_coupon_applications') class Order(models.Model): user = models.ForeignKey(settings.AUTH_USER_MODEL, related_name='user_order', verbose_name="Customer") order_date = models.DateTimeField(verbose_name='Order Date and Time') shop = models.ForeignKey(Location, null=True, on_delete=models.SET_NULL) class OrderItem(models.Model): order = models.ForeignKey(Order, related_name='order_items') order_type = models.CharField('Type', choices=ORDER_ITEM_TYPE, default=INVENTORY) buy_get_discount = models.DecimalField(_('Buy & Get Discount')) sub_total = models.DecimalField(_('Sub Total'), max_digits=18, decimal_places=2) now for each coupon i need to find the gross sales of the products sold using it. I am finding it pretty hard to write a query for the same cos i need to annotate the sum of subtotal of order item to each coupon object and i guess this requires joining coupon application, order item and order table so far i've wrote this much: buy_gets_gross_sales = OrderItem.objects.filter(order_type=OrderItem.INVENTORY, buy_get_discount__gt=0, order_id__in=CouponApplication.objects.filter(coupon=OuterRef('pk'), ).values('order') ).values('order_type') gross_sales = buy_gets_gross_sales.annotate(gross=Sum('sub_total')).values('gross') gross_Sales_report = Coupon.objects.annotate( total_gross_sales =Round(Coalesce(Subquery(gross_sales, output_field=models.DecimalField()), Value(0))) ,) i know this wont work, but i need something of this sort. it is already throwing some … -
I am new to django,is it mandatory to use django authorization
Is it required to use django authorization or is it possible to implement my own code for authorization? Can we implement own authorization. -
DRF and admin static urls pointing to wrong location
I have a Django Rest Framework project running on a subpath /api, together with the frontend on the root /. When I go to /api and /api/admin I get messages in the console saying that the static is missing. The urls listed are /static/... instead of the expected /api/static/.... I found out that this was bug a bug in Django before version 3.1 by looking at the answers to related questions. Hence I upgraded to version 3.2.2. This should have fixed the problem, but it did not. Neither did clearing cache, recollecting static and restarting apache. What else could be the issue? Note: An environment with the same apache settings works when not placed on a subpath and not behind the proxy. The errors Settings: My pip packages: apache2.4 django version 3.2.2 python 3.8 djangorestframework 3.11.2 My Apache conf: <VirtualHost *:443> ... SSLProxyEngine on SSLProxyVerify none SSLProxyCheckPeerCN off SSLProxyCheckPeerName off SSLProxyCheckPeerExpire off ProxyPreserveHost on ProxyPass "/admin" "https://localhost:8081/api/admin" ProxyPassReverse "/admin" "https://localhost:8081/api/admin" ProxyPass "/api" "https://localhost:8081/api" ProxyPassReverse "/api" "https://localhost:8081/api" <Directory ${docroot}> Options FollowSymlinks Require all granted FallbackResource /index.html </Directory> ErrorLog ${APACHE_LOG_DIR}/frontend-error.log CustomLog ${APACHE_LOG_DIR}/frontend-access.log combined </VirtualHost> <VirtualHost *:8081> ... <Directory ${docroot}/${project}> <Files wsgi.py> Require all granted </Files> </Directory> WSGIDaemonProcess API python-path=${docroot}:${docroot}/venv/lib/python3.8/site-packages display-name=api WSGIProcessGroup API … -
Django nameing conventions
I have tried to find best practice for naming conventions but I can't find a site that explains it. I would like to correct my project so it is up to standard and before deployment. I know that can take alot of time, but I think it is best to correct it now then later. I can tell what I have done and I hope some one tell me what I need to change. the project name: MyToolsProject apps name: myapp_ap, pages_app, to_do_list_app Class: Asset, AssetType functions: do_this(), happy() variables: var, this_variable objects: obj. this_obj Module: my_app_asset, my_app_asset_type Module fields: last_updated, notes templates: asset.html, asset_type.html url: path("asset_app/asset/", views.AssetListView.as_view(), name="asset_app_asset_list"), -
Using both firebase-admin and pyrebase
I am new to dev, I am using firebase react and django in order to create my app In react, I am using firestore and firebase storage to store basic stuffs, I got to use that in my Django So I have to use both pyrebase (for firebase storage) and firebase-admin (for firestore) [ I know I can use firebase-admin to do both but it's hard to find storage details ] how do I initialize both together -
How to get auto end date based on selection of start date and no. of days of travel
I am new with Django and coding. After doing Local Library and Polls tutorial on MDN and Django respectively. I am now working on travel itinerary app. Where I want that my model should be able to take start date as enter by user and based on number of nights selected by user should auto fill the end date. Example: Start Date: 09-July-21 No. of Nights: 05 End Date: 14-July-21 Code for models.py is as follows, I will be using Postgresql DB for this project class Packages(models.Model): title_package = models.CharField(max_length=300) no_of_nights = models.SmallIntegerField() summary = models.TextField(max_length=3000) start_date = models.DateField(help_text='should not allow client to book in past') end_date = models.DateField(help_text='based on start date selection and no. of nights client is staying.') -
Django - How to implement a search box
I'm struggling to implement a search bar and could really do with a few suggestions on how it could be done. I'm quite a novice, so please bear with me. My difficulties lie more with the general understanding of what needs to be built than with a specific line of code and somehow that's making it even harder for me to find an answer. In summary, I have: Django Models: Recipe Tags (M2M with Recipe) Category (ForeignKey with Recipe) etc. I've written Graphene schemas to query the database (Postgres) by Tags, Categories and numerous Recipe attributes (e.g.: Recipe name). You can filter the recipes displayed on the frontend with those queries, by clicking on e.g. a certain category name. What I'd however also like to have, is a search box where a user can enter a keyword of their choice on the frontend, and get back all the recipes that have something matching that keyword. I don't know what or how to build something like that. To my novice mind, it seems like a search box of that sort would essentially be a query where I don't know what the filter is in advance, i.e. "fresh" as an input could … -
I newly start django and launc server once but now its now working and showing me following errors. my all settings are default
PS C:\Users\Prem\Desktop\demo> django-admin runserver manage.py Traceback (most recent call last): File "c:\users\prem\appdata\local\programs\python\python39\lib\runpy.py", line 197, in run_module_as_main return run_code(code, main_globals, None, File "c:\users\prem\appdata\local\programs\python\python39\lib\runpy.py", line 87, in run_code exec(code, run_globals) File "C:\Users\Prem\AppData\Local\Programs\Python\Python39\Scripts\django-admin.exe_main.py", line 7, in File "c:\users\prem\appdata\local\programs\python\python39\lib\site-packages\django\core\management_init.py", line 419, in execute_from_command_line utility.execute() File "c:\users\prem\appdata\local\programs\python\python39\lib\site-packages\django\core\management_init.py", line 413, in execute self.fetch_command(subcommand).run_from_argv(self.argv) File "c:\users\prem\appdata\local\programs\python\python39\lib\site-packages\django\core\management\base.py", line 354, in run_from_argv self.execute(*args, **cmd_options) File "c:\users\prem\appdata\local\programs\python\python39\lib\site-packages\django\core\management\commands\runserver.py", line 61, in execute super().execute(*args, **options) File "c:\users\prem\appdata\local\programs\python\python39\lib\site-packages\django\core\management\base.py", line 398, in execute output = self.handle(*args, **options) File "c:\users\prem\appdata\local\programs\python\python39\lib\site-packages\django\core\management\commands\runserver.py", line 68, in handle if not settings.DEBUG and not settings.ALLOWED_HOSTS: File "c:\users\prem\appdata\local\programs\python\python39\lib\site-packages\django\conf_init_.py", line 82, in getattr self.setup(name) File "c:\users\prem\appdata\local\programs\python\python39\lib\site-packages\django\conf_init.py", line 63, in _setup raise ImproperlyConfigured( django.core.exceptions.ImproperlyConfigured: Requested setting DEBUG, but settings are not configured. You must either define the environment variable DJANGO_SETTINGS_MODULE or call settings.configure() before accessing settings. -
Template data not passing into Django view.py
Create account form We are trying to get the name, email-ID and password through post method in the form, we get the data as none instead of the data filled in the form. view.py from django.http import HttpResponse # Create your views here. def sign_up_in(response): email = response.POST.get('eemail') #Getting the data of email by the name of eemail print(email) #Trying to print the email that we got from the form return render(response, "main/sign_up_in.html",{}) HTML code There are two forms and we are trying to get the data from the first form. The first form is for creating the account and the second is for signing in. <h2 class="form_title title">Create Account</h2> <div class="form__icons"><img class="form__icon" src="svg_data" alt=""><img class="form__icon" src="svg_data"><img class="form__icon" src="svg_data"></div><span class="form__span">or use email for registration</span> <input class="form__input" type="text" placeholder="Name" name="eemail"> <input class="form__input" type="text" placeholder="Email"> <input class="form__input" type="password" placeholder="Password"> <button class="form__button button submit">SIGN UP</button> </form> <form method="POST" class="form" id="b-form" action=""> <h2 class="form_title title">Sign in to Website</h2> <div class="form__icons"><img class="form__icon" src="svg_data" alt=""><img class="form__icon" src="svg_data"><img class="form__icon" src="svg_data"></div><span class="form__span">or use your email account</span> <input class="form__input" type="text" placeholder="Email" name="eemail"> <input class="form__input" type="password" placeholder="Password"><a class="form__link">Forgot your password?</a> <button class="form__button button submit">SIGN IN</button> </form> url.py from . import views urlpatterns = [ path("", views.Home, name = "Homes"), path("sign/", … -
Assigning multiple leads to users and changing the category in django
Hey guys im trying to make a function in django for assigning multiple leads to an user or changing the lead category using FormView and AJAX. What im trying to do is from the datatable select all paginated rows and below have the form to submit. HERE IS MY CODE: forms.py class AssignForm(forms.Form): user = forms.ModelChoiceField(queryset=User.objects.none()) category = forms.ModelChoiceField(queryset=Category.objects.none()) def __init__(self, *args, **kwargs): request = kwargs.pop("request") users = User.objects.all() categories = Category.objects.all() super(AssignForm, self).__init__(*args, **kwargs) self.fields["user"].queryset = users self.fields["category"].queryset = categories views.py: class LeadAssignView(LoginRequiredMixin, generic.FormView): form_class = AssignForm template_name = "leads/lead_assign.html" def get_form_kwargs(self, **kwargs): kwargs = super(LeadAssignView, self).get_form_kwargs(**kwargs) kwargs.update({ "request":self.request }) return kwargs def get_context_data(self, **kwargs): context = super(LeadAssignView, self).get_context_data(**kwargs) context['leads'] = Lead.objects.all() return context def form_valid(self, form, request): user = form.cleaned_data["user"] category = form.cleaned_data["category"] if request.method == "POST": lead_ids = request.POST.getlist('id[]') for id in lead_ids: lead = Lead.objects.get(id=self.kwargs["pk"]) lead.user = user lead.category = category lead.save() return super(LeadAssignView, self).form_valid(form) And here is how i get the selected data from te datatable in the template ('leads/lead_assign.html'): <table id="misen" class="table table-bordered nowrap table-sm" cellspacing="0" style="width:100%"> <thead class="thead-dark"> <tr> <th class="text-center">#</th> <th class="text-center"><input type="checkbox" name="" id="site_select_all"></th> <th class="text-center">Name</th> <th class="text-center">Phone</th> <th class="text-center">Data Creation</th> <th class="text-center">Source</th> <th class="text-center">Category</th> <th class="text-center">User</th> <th class="text-center">Action</th> </tr> </thead> … -
Nginx static files 404 with django swagger rest api
I have Django rest API application and swagger for that is working fine locally. I am trying to configure it using containers and deploy it on ECS. Now when I build and run the container the application works fine (I mean the swagger UI is appearing). When I attach the application load balancer to it, on the browser it is giving me 404 files not found for js and CSS files. Here is the console output from the web browser. Here is my Nginx config file # nginx.default add_header X-Content-Type-Options nosniff; include /etc/nginx/mime.types; add_header X-XSS-Protection "1; mode=block"; server { listen 8020; access_log /var/log/nginx/access.log; error_log /var/log/nginx/error.log; location / { proxy_pass http://127.0.0.1:8010; proxy_set_header Host $host; proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for; } location /static { root /home/app/codebase; } } THe path of static folder inside docker container is /home/app/codebase/static/ Also added the following lines in the Django Settings.py file. STATIC_URL = '/static/' STATIC_ROOT = os.path.join(BASE_DIR, 'static/') Not sure what am I missing. Any leads will be appreciated. I have looked into these questions. The problem is something similar but not sure what I'm missing. -
How to display the CommentForm in my django template?
I am trying to display the CommentForm on Django template but it just wont display. I have a ViewBased Form class PostUpdateView(LoginRequiredMixin, UserPassesTestMixin, UpdateView): model = PostForNewsFeed fields = ['description', 'pic', 'tags'] template_name = 'feed/create_post.html' def form_valid(self, form, request,pk): post = get_object_or_404(PostForNewsFeed, pk=pk) if request.method == 'POST': if form.is_valid(): data = form.save(commit=False) data.post = post data.username = request.user data.save() form = NewCommentForm() return redirect('post-detail', pk=pk) else: form = NewCommentForm() return render(request,'feed/post_detail.html', {'form':form}) <div class="row"> <div class="col-md-8"> <div class="card card-signin my-5"> <div class="card-body"> <form class="form-signin" method="POST" id="post-form"> {% csrf_token %} <fieldset class="form-group"> <br /> {{ form|crispy }} </fieldset> <div class="form-group"> <button class="btn btn-lg btn-primary btn-block text-uppercase" type="submit" > Comment</button ><br /> </div> </form> </div> </div> </div> </div> The CommentForm Doesnt get displayed. -
Match and subtract QuerySet with dict in django
I have two variables containing the following output: city_sum_added: <QuerySet [{'city': '8000', 'cinnamon__sum': None, 'peber__sum': Decimal('240.00')}, {'city': '9000', 'cinnamon__sum': Decimal('250.00'), 'peber__sum': None}, {'city': '9800', 'cinnamon__sum': Decimal('500.00'), 'peber__sum': None}]> our_total: {'Hovedlager': [Decimal('3167.50'), Decimal('752.50')], 'Odense': [Decimal('177.50'), Decimal('10.00')], 'Holstebro': [Decimal('52.50'), Decimal('12.50')], 'Hjørring': [Decimal('57.50'), 0], 'Rødekro': [Decimal('325.00'), Decimal('70.00')], 'Esbjerg': [Decimal('125.00'), Decimal('30.00')], 'Århus': [Decimal('492.50'), Decimal('20.00')], 'København': [Decimal('45.00'), 0], 'Ålborg': [Decimal('380.00'), Decimal('102.50')]} In city_sum_added we see the city number (zip code) and then amount of cinnamon and peber in decimals. In our_total we see the city name and then two decimals being cinnamon and peber too (starting with cinnamon) I now wanna take my our_total and match the city with the one from city_sum_added before I subtract the amount of cinnamon and peber in our_total with the amount in city_sum_added. The names and numbers of the cities comes from this model, where you see what numbers belongs to what city when they are going to be matched: class InventoryStatus(models.Model): CITIES = [ ('9800', 'Hjørring'), ('9000', 'Ålborg'), ('7500', 'Holstebro'), ('8000', 'Århus'), ('6700', 'Esbjerg'), ('6230', 'Rødekro'), ('5220', 'Odense'), ('2300', 'København'), ('4682', 'Hovedlageret'), ] cinnamon = models.DecimalField(max_digits=10, decimal_places=2, null=True, blank=True) peber = models.DecimalField(max_digits=10, decimal_places=2, null=True, blank=True) city = models.CharField(max_length=4, choices=CITIES) created_at = models.DateTimeField(auto_now_add=True) created_by = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.CASCADE) is_deleted = … -
When I try to happen to the second URL I created it says "Page not found" and "calls it" 3. ^ (? P <path>. *) $
It does not show me the url created. When I try to go to the localhost it tells me: admin / Bag/ ^ (? P . *) $ The created URL calls it ^ (? P . *) $. How can I do? urls.py from django.urls import path from . import views urlpatterns = [ path('', views.Borsa), path('Investimenti', views.Investimenti) ] urls.py (project) from django.contrib import admin from django.urls import path, include from django.conf.urls.static import static from django.conf import settings urlpatterns = [ path('admin/', admin.site.urls), path('Borsa/', include('Borsa.urls')), ]+static(settings.MEDIA_URL, document_root =settings.MEDIA_ROOT) views.py from django.shortcuts import render from .models import Aziende def Borsa(request): Borsa = Aziende.objects.all() return render(request, 'Borsa/Home.html', {'Borsa': Borsa},) def Investimenti(request): return render(request, 'Borsa/Investimenti.html') Thanks in advance! -
Filter list of objects, check if exists
I have a local database which contains objects and a remote one that should have the same values. I check for any differences every time someone refreshes certain page. I am loading remote dataset into list of objects. I am stuck at checking if someone deleted object from remote location. Deleting local one is fairly simple. for row in cursor_from_pyodbc: w = LzWidlak(some_id=row[0], another_value=row[1]) remote_objects.append(w) for remote_object in remote_objects: if MyModel.objects.filter(some_id=remote_object.some_id).exists(): ... I have no idea how to do it the other way around. It seems like there is no filter function on my list of objects? for local_object in MyModel.objects.all(): if remote_objects.filter(some_id=local_object.some_id).exists(): ... It throws: Exception Value: 'list' object has no attribute 'filter' I feel there is a simple way to do that but don't know what it is. -
Django timeout before submitting background task
I maintain a Django app hosted on Heroku. We use DRF intensively to serve our FE app. Django version: 2.2.21. Celery version: 4.2.2 We have an endpoint that works perfectly well 99% of the time, but sometimes, it timeouts. We use Sentry to monitor and you can find the traces here. FYI but maybe it is not useful, this endpoint: Has very little processing then starts a background task. In the breadcrumb of Sentry, we can see that the REDIS LPUSH command is triggered at the very end of the 20s heroku timeout. It is happening only in production and not staging and we cannot reproduce it It seems to me that the function calls is going back and forth between django/core/handlers/exception.py in inner at line 34 django/utils/deprecation.py in __call__ at line 94 This has been happening for months now and we still do not have a solution. Any idea as to why this might happen? And why only in certain cases? Thank you very much for the help! Robin Bonnin -
Django: Toggle Logged in users
Here, in this project, I want to show toggle green when admin is logged in and others user's toggle red as well as when other user is logged in,their toggle must be in green color and other remaining in red color. This is my template. <table class="table table-hover text-nowrap" id="rooms"> <thead> <tr> <th>SN</th> <th>Users</th> <th>Email</th> <th>Status</th> <th>Action</th> </tr> </thead> <tbody> {% for user in object_list %} <tr> <td>{{forloop.counter}}</td> <td>{{user.username }}</td> <td>{{user.email}}</td> <td> <label class="switch"> <input type="checkbox"> <span class="slider round"></span> </label> </td> <td> <span ><a class="btn btn-info mr-2" href="{% url 'dashboard:passwordreset' %}" ><i class="fa fa-edit m-1" aria-hidden="true" ></i>Reset Password</a ></span> </td> </tr> {% endfor %} </tbody> </table> When admin is logged in the toggle of admin must be in green color and whereasee other users toggle must be in red color, same as when other users are logged in their toggle must be in green color. This is my views class UsersListView(SuperAdminRequiredMixin, AdminRequiredMixin, ListView): template_name = 'dashboard/users/userlist.html' login_url = '/login/' redirect_field_name = 'user_list' paginate_by = 5 def get_queryset(self): return User.objects.all()