Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
How to pass a variable between methods inside Django class based View
I have a class and several methods inside. I need to pass a variable from one method to another. But I've got an error all the time... How can I do it correctly? Here is my code: class AddSiteView(View): form_class = AddSiteForm template_name = 'home.html' def get(self, request, *args, **kwargs): form = self.form_class() return render(request, self.template_name, { 'form': form }) def post(self, request, *args, **kwargs): form = self.form_class(request.POST) if form.is_valid(): # Get website url from form site_url = request.POST.get('url') # Check if the site is in DB or it's a new site try: site_id = Site.objects.get(url=site_url) except ObjectDoesNotExist: site_instanse = form.save() else: site_instanse = site_id return site_instanse return render(request, self.template_name, { 'form': form }) def get_robots_link(self, *args, **kwargs): # Set veriable to the Robot Model robots = Robot.objects.get(site=site_instanse) # Robobts Link robots_url = Robots(site_url).get_url() robots.url = robots_url robots.save() return redirect('checks:robots', robots.id, ) I need to pass site_instanse from def post to def get_robots_link -
Django: What self function we can use instead of _str_ , I just want to get the return value as a integar and list
I am using the Djnago and create the junction table in which only two rows and both are foreign key that return the integar value, but at the end of my model class I want to get the some return value of row or model. Just like we use str to return the string value. What we can use to return the integar value and also the list value as I am creating the other model with MultiSelectFeild, thats require to return the list -
Environment Properties Not Avaialble In Django ElasticBeanstalk
I have set a few variable properties by going to the environment -> configuration -> Modify Software -> Environment properties. When I SSH into the instance, activate the virtual environment and run python and check for the variable, it returns nothing. This is what I type before I enter the python shell: source /opt/python/run/venv/bin/activate cd /opt/python/current/app/ python >>> import os >>> os.environ.get('VARIABLE') >>> -
Change query column name to variable in Django template
I use the django framework to do my task, I want to optimize my code in the template file. Here is my code blow. {% ifequal name 'jack' %} {% ifequal item.jack 'lower' %} <button type="button" class="btn btn-block btn-lg btn-outline-primary active" style="height: 120px; margin-bottom:100px; margin-height:120;" name="label" value="lower">風險比較低</button> {% else %} <button type="button" class="btn btn-block btn-lg btn-outline-primary" style="height: 120px; margin-bottom:100px; margin-height:120;" name="label" value="lower">風險比較低</button> {% endifequal %} {% ifequal item.jack 'higher' %} <button type="button" class="btn btn-block btn-lg btn-outline-primary active" style="height: 120px; margin-bottom:100px; margin-height:120;" name="label" value="higher">風險比較高</button> {% else %} <button type="button" class="btn btn-block btn-lg btn-outline-primary" style="height: 120px; margin-bottom:100px; margin-height:120;" name="label" value="higher">風險比較高</button> {% endifequal %} {% ifequal item.jack 'unknown' %} <button type="button" class="btn btn-block btn-lg btn-outline-primary active" style="height: 120px; margin-bottom:100px; margin-height:120;" name="label" value="unknown">無法判斷</button> {% else %} <button type="button" class="btn btn-block btn-lg btn-outline-primary" style="height: 120px; margin-bottom:100px; margin-height:120;" name="label" value="unknown">無法判斷</button> {% endifequal %} {% endifequal %} {% ifequal name 'du01' %} {% ifequal item.du01 'lower' %} <button type="button" class="btn btn-block btn-lg btn-outline-primary active" style="height: 120px; margin-bottom:100px; margin-height:120;" name="label" value="lower">風險比較低</button> {% else %} <button type="button" class="btn btn-block btn-lg btn-outline-primary" style="height: 120px; margin-bottom:100px; margin-height:120;" name="label" value="lower">風險比較低</button> {% endifequal %} {% ifequal item.du01 'higher' %} <button type="button" class="btn btn-block btn-lg btn-outline-primary active" style="height: 120px; margin-bottom:100px; margin-height:120;" name="label" value="higher">風險比較高</button> {% … -
jquery click toggling troubleshooting
I am using jquery and AJAX calls to send data to my django views when a user clicks and unclicks a button (there are multiple buttons on the page). Clicking once on the button should make the counter go up and store the word that was clicked. Then in my view a model object is created based on this data. Clicking a second time on the same button should do the opposite: make the count go down by one, and delete this object from the model. Everything was working well before I started implementing the toggle methodology. Now the toggling works, but both the clicked_words and unclicked_words lists are empty (and the counter doesn't work anymore), which means that there is nothing to save in the model. (Previously, all of these were working as expected.) I can't figure out where I have gone wrong. I have very limited experience with jquery, so in trying to add the toggling I must have broken something else! jquery: $(document).ready(function() { var known_words = 0; var clicked_words = []; var unclicked_words = []; $(".word_known").click(function() { var reference = this; var songpk = $(this).data('songpk'); var userpk = $(this).data('userpk'); $(this).toggleClass('increment'); if ($(this).hasClass('increment')) { known_words++; clicked_words.push($(this).data('word')); add_object … -
"Attempted relative import beyond top-level package"
When i want to save this django file: from django.urls import path from . import views urlpatterns = [ path('', views.index) ] I get an error : "Attempted relative import beyond top-level package" What should I do with it? -
Deleting list objects in Django?
I was always taught, if you create array or list, you have to delete this array or list object. So if you append (push) , then you have to pop and delete. Otherwise this object will create bad references on the hard drive and eventually eat up the disk space with the bad fragments. In Django, I cannot find any info on how properly dispose temporary objects. Especially, after using them in template (so, like, redirecting them from view function into the template). Even more... I can pop from list of object like this: if a_object: while a_object: a_object.pop() print('deleted a_object') But as soon as I try something like: delete a_object Django tells me that there is no such function... And also, how would I pop items from list if I redirect from view function to template, so I am gone from view function and cannot pop items from list object neither before going to template, nor after I gone to template. Any thoughts on this? Because I am confused... Does Django automatically take care of objects as a higher level language? -
django keeps showing Could not parse the remainder: '=="dashboard"' from 'section=="dashboard"' when i try running the server
[django keeps showing Could not parse the remainder: '=="dashboard"' from 'section=="dashboard"' when i try running the server][1] -
Django rest swagger_auto_schema customize response body to API VERSION
So I have 2 different api version (API v1 and v2). I want a different Swagger response for those because the output is different. I know that it needs to be done here in the view: responses={ 200: openapi.Response( _( "Successfully fetched the array of all sites where the user belongs to." ), SiteSerializer, ) } But I can't access the "version" (it is stored in self.request.version. This is my version url file router = routers.DefaultRouter() app_name = "v1" schema_view = get_schema_view( openapi.Info( title="API", default_version="v1", description="## Admin dashboard" ), # validators=['flex', 'ssv'], public=True, permission_classes=(permissions.AllowAny,), ) v1_urls = [...] Do I need to use this schema view to access the version number or use self? -
How do I prevent database query on related model?
I have my models like this: class Author(models.Model): name = models.CharField() # other fields class Book(models.Model): author = models.ForeignKey(Author, related_name='books') reader = models.ForeignKey(Reader) # other fields class Reader(models.Model): name = models.CharField() age = models.PositiveIntegerField() # other fields Now I have a code snippet like this: authors = Author.objects.filter(**some_filter) books_objs = authors.books.filter(reader__age__gt=18) This second line of code is querying the database on Book model, which I want to prevent. Is there any way I can prevent the db query in the second line? -
Join Two Querysets
This is a development on a question I previously asked. I have this queryset user_packages = ModulePackage.objects.filter(student=user.student).prefetch_related('individual_modules') and this one module_data = StudentModuleData.objects.filter(package__in=user_packages, student=user.student) StudentModuleData has a one-to-many relationship with individual_modules (module) class StudentModuleData(models.Model): student = models.ForeignKey('users.Student', related_name='student_module_data', on_delete=models.CASCADE) module = models.ForeignKey(BaseModule, on_delete=models.CASCADE) package = models.ForeignKey(ModulePackage, on_delete=models.CASCADE, default=None, null=True) Now that I have both of these, how can I join them so in template I can say {% for package in user_packages.all %} {{ package }} {% for module in package.individual_modules.all %} {{ module }} {% for extra_data in module.extra_data %} {{ extra_data }} (calling {% for data in module.studentmoduledata_set.all %} doesn't help) Thank you. -
Some problems happened in the pycharm when i use svn download a project
When I use the instruction python manage.py runserver, then the terminal appear as follow: Performing system checks ... abort trap: 6 What's that means? And how can I solve the problem so I can continue to work on my project? -
select group except if any of the element has a definide atribute
I'm new to this, but I have this example table sample: |id| recordId|type|state|date| |---|--- | ---|--- |---| |1 | A01 |1 |ACPTD|x| |2 | A01 |1 |RJCTD|x| |3 | A02 |1 |RJCTD|x| |4 | A02 |1 |RJCTD|x| How do I get The elements for a specific recordID, type and Date, but exclude the elements with the same recordID if any of them has a ACPTD state? something like this. SELECT * FROM sample as s WHERE (s.recordId, s.state, s.type, s.date) NOT IN (SELECT * FROM sample where state='ACPTD') Is it possible with django ORM? -
could updating django model object via asynchronous processes with .save(update_fields=) argument cause race condition?
Say, there is a standard django model: class AModel(models.Model): field_a = ... field_b = ... field_c = ... .... There are several signals to update AModel triggered by asynchronous processes. SignalA SignalB SignalC ... Signals can update same row with update_fields argument like: @receiver(m2m_change, sender=Model1) def signal_a_to_update_field_a(sender, instance, *args, **kwargs): modela_obj = ```getting foreign object via instance``` modela_obj.field_a = 'any data' modela_obj.save(update_fields=['field_a', ]) @receiver(post_save, sender=Model2) def signal_b_to_update_field_b(sender, instance, *args, **kwargs): modela_obj = ```getting foreign object via instance``` modela_obj.field_b = 'any data' modela_obj.save(update_fields=['field_b', ]) @receiver(post_save, sender=Model3) .... While asynchronous processes are triggers signals simulteneously; SignalA should update field_a with modela_obj.save(update_fields=['field_a', ]) I can see it in the logs that signal is triggered, but: While signal_a running, signal_b is triggered, too. And, before signal_a finished signal_b were does what it meant to be. Then, the signal_a finished it's task. But, the field_a field could updated via signal_a is not changed on the final state of the row. What am I missing here? Is it possible to be a race condition even strictly specified the which field should be updated? Using django 1.10 with celery and rabbitmq. -
Filter for Multiple values of a field in DRF
In Amazon you can filter by Multiple Brands, eg. You select Nike, Puma, Adidas. The queryset that is sent back has products which belong to either of those brands. if you have a model like: class Product(models.Model): name = models.CharField(max_length=100) description = models.TextField() brand = models.CharField(max_length=100) a serializer like: class ProductSerializer(serializers.ModelSerializer): class Meta: model = models.Product fields = "__all__" viewset like: class ProductViewSet(viewsets.ModelViewSet): serializer_class = serializers.ProductSerializer permission_classes = [IsAuthenticated] filter_backends = [filters.ProductMultipleFilterBackend ] filters.py file: from rest_framework import filters as drf_filters from django_filters import rest_framework as df_filters class MultipleField(MultipleChoiceField): def valid_value(self, value): return True class MultipleFilter(df_filters.MultipleChoiceFilter): field_class = MultipleField class ProductMultipleFilterBackend(df_filters.FilterSet): brand = MultipleFilter(lookup_expr="icontains", field_name = "brand") search = MultipleFilter(lookup_expr="icontains", field_name = "description") class Meta: model = models.Product fields = ["brand", "search"] the above code was something i found here. But it's like 5 years old and there might be a better way that i surely don't know about and i'm getting the following error on the code: filter_queryset() takes 2 positional arguments but 4 were given What would be the url structure for these requests: /someurl?brand=Nike,Adidas,Puma or /someurl?brand=[Nike,Adidas,Puma] Thanks in Advance !!!! -
Elastic search: Partial search not working properly
Partial search is not working on multiple fields. Data: - "Sales inquiries generated". { "query_string": { "fields": ["name", "title", "description", "subject"], "query": search_data+"*" } } Case1: When I pass search data as "inquiri" it works fine, But when I pass search data as "inquirie" it's not working . Case2: When I pass search data as "sale" it works fine, But when I pass search data as "sales" it's not working. Case3: When I pass search data as "generat" it works fine, But when I pass search data as "generate" it's not working. I defined my field this way. text_analyzer = analyzer("text_analyzer", tokenizer="standard", filter=["lowercase", "stop", "snowball"]) name = Text(analyzer=text_analyzer, fields={"raw": Keyword()}) title = Text(analyzer=text_analyzer, fields={"raw": Keyword()}) subject = Text(analyzer=text_analyzer, fields={"raw": Keyword()}) What is the issue in the code, Can you please give me a solution. Thanks in Advance. -
how to compress uploaded files in django using 7zip subprocess.call method?
im trying to compress uploaded files in django using 7zip. i have successfully implemented compression and decompression of files using 7zip in python but i am not able to figure out how to integrate the same with django uploaded file so that whenever a file is uploaded ,a 7zp format for the same file is create and stored in the disk. Code used in python for compression : import subprocess from py7zr import unpack_7zarchive import shutil exe = r"C:\Program Files\7-Zip\7zG.exe" source = r"C:\profiles\Living in the Light_ A guide to personal transformation.pdf" target = r"C:\profiles\Living1.7z" def compress(source,traget): subprocess.call(exe + " a -t7z \"" + target + "\" \"" + source + "\" -mx=9") print('file compressed') def uncompress(target): shutil.register_unpack_format('7zip', ['.7z'], unpack_7zarchive) shutil.unpack_archive(target, r'C:\Users\098an\Pictures\Camera Roll') print('file uncompressed') -
How can I delete related models in Django (many-to-many)?
I have two models in Django, which I use for storing some document and also to build an index of the words within the documents. Here are there models: class DMS_Dokument(models.Model): dms_dok_titel = models.CharField(max_length=255, blank=True) dms_dok_beschreibung = models.CharField(max_length=3000, blank=True, null=True) dms_dok_datei = models.FileField(max_length=255,upload_to='DMS/') dms_dok_hochgeladen_am = models.DateField() dms_dok_indiziert = models.BooleanField(default=False) dms_dok_gehoert_zu_app = models.CharField(max_length=255, choices=app_choices, blank=False, null=False) dms_dok_typ = models.CharField(max_length=255, choices=typ_choices, blank=False, null=False, default='Sonstiges') def save(self, *args, **kwargs): preserve_ext = extension(self.dms_dok_datei.name) neuer_dateiname = self.dms_dok_gehoert_zu_app + '_' + self.dms_dok_titel + '_' + self.dms_dok_hochgeladen_am.strftime("%d.%m.%Y") self.dms_dok_datei.name = neuer_dateiname + preserve_ext super(DMS_Dokument, self).save(*args, **kwargs) class Meta: app_label = 'DMS' class DMS_Index_Data(models.Model): dms_ind_wort = models.CharField(max_length=255, blank=False, null=True) dms_ind_m2m = models.ManyToManyField(DMS_Dokument, related_name='indexes') #dms_ind_dok_fk = models.ForeignKey('DMS_Dokument', on_delete=models.CASCADE) class Meta: app_label = 'DMS' ordering = ['dms_ind_wort'] When I now use a DeleteView to delete a DMS_Dokument object, then this is correctly removed from the database. But the entries in the other table remain. How can I tell Django that upon removing a document, the index should also be cleaned from entries relating to it? And is this special, as I have many-to-many relationships? -
How to pass id and saving data in clicking submit button in django
I am new to Django I want to submit data and pass id with the same button to another page example like http://127.0.0.1:8000/app/home/ to http://127.0.0.1:8000/app/data1/1 I am stuck in this point please help me models.py from django.db import models class username(models.Model): name=models.CharField(max_length=100) email=models.EmailField(max_length=100) class Profilephoto(models.Model): profile_photo = models.FileField(upload_to='media/') uname = models.ForeignKey(username, on_delete=models.CASCADE, null=True) forms.py from django import forms from .models import Profilephoto class DocumentForm(forms.ModelForm): class Meta: model = Profilephoto fields = ['profile_photo','uname'] view.py from django.shortcuts import render, redirect, HttpResponse from .models import username,Profilephoto from .form import DocumentForm def home(request): if request.method == 'POST': name = request.POST['name'] email = request.POST['email'] username(name=name,email=email).save() users = username.objects.latest('id') return render(request, 'home.html',{'usernames': users}) else: users = username.objects.latest('id') return render(request, 'home.html',{'usernames': users}) def data1(request,id): if request.method == 'GET': obj = username.objects.get(id=id) form = DocumentForm(instance=obj) return render(request, 'data1.html', {'form': form, 'usernames': obj}) elif request.method == 'POST': obj = username.objects.get(id=id) form = DocumentForm(request.POST, request.FILES, instance=obj) if form.is_valid(): form.save() return redirect('home') return render(request, 'data1.html', {'usernames': obj}) home.html <form METHOD="post"> {% csrf_token %} <div class="container-fluid"> <div class="form-group .col-sm-4"> <input name="name" type="text" class="form-control" id="usr"> </div> <div class="form-group"> <input name="email" type="text" class="form-control" id="em"> </div> </div> <a href="{% url 'data1' id=usernames.id %}"><button type="submit" class="btn btn-default" >Save </button></a> </form> data1.html <form method="post" enctype="multipart/form-data"> {% csrf_token … -
How to show username already exists without reloading page in Django?
My View: from django.shortcuts import render from django.http import HttpResponse, JsonResponse from django.contrib.auth.models import User from . import AccountsForms def SignUpView(request): if request.method == "POST": form = AccountsForms.SignUpForm(request.POST) if form.is_valid(): SignUp = form.save(commit=False) user = form.cleaned_data['username'] if User.objects.filter(username=user).exists(): return JsonResponse(User) else: SignUp.save() else: form = AccountsForms.SignUpForm(request.POST) return render(request, 'Accounts/SignUp.html', {'form':form}) I am using the above view but I don't know how to catch the JsonResponse in JS. Somebody help me please. -
When extending base.html, getting identation problem in home.html
I'm using Django 3.0.8 on visual studio code IDE. Here is a blog template(in template root) contained files base.html and home.html. Here is my full base.html code: {% load static %} <!doctype html> <html lang="en"> <head> <!-- Required meta tags --> <meta charset="utf-8"> <meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no"> <!-- Bootstrap CSS --> <link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.5.0/css/bootstrap.min.css" integrity="sha384-9aIt2nRpC12Uk9gS9baDl411NQApFmC26EwAOH8WgZl5MYYxFfc+NcPb1dKGj7Sk" crossorigin="anonymous"> {% if title %} <link rel="stylesheet" type="text/css" href="{% static 'blog/main.css' %}"> <title>Django blog-{{title}}</title> {% else %} <title>Django blog</title> {% endif %} </head> <body> <header class="site-header"> <nav class="navbar navbar-expand-md navbar-dark bg-steel fixed-top"> <div class="container"> <a class="navbar-brand mr-4" href="/">Django Blog</a> <button class="navbar-toggler" type="button" data-toggle="collapse" data-target="#navbarToggle" aria-controls="navbarToggle" aria-expanded="false" aria-label="Toggle navigation"> <span class="navbar-toggler-icon"></span> </button> <div class="collapse navbar-collapse" id="navbarToggle"> <div class="navbar-nav mr-auto"> <a class="nav-item nav-link" href="/">Home</a> <a class="nav-item nav-link" href="/about">About</a> </div> <!-- Navbar Right Side --> <div class="navbar-nav"> <a class="nav-item nav-link" href="#">Login</a> <a class="nav-item nav-link" href="#">Register</a> </div> </div> </div> </nav> </header> <main role="main" class="container"> <div class="row"> <div class="col-md-8"> {% block content %}{% endblock %} </div> <div class="col-md-4"> <div class="content-section"> <h3>Our Sidebar</h3> <p class='text-muted'>You can put any information here you'd like. <ul class="list-group"> <li class="list-group-item list-group-item-light">Latest Posts</li> <li class="list-group-item list-group-item-light">Announcements</li> <li class="list-group-item list-group-item-light">Calendars</li> <li class="list-group-item list-group-item-light">etc</li> </ul> </p> </div> </div> </div> </main> <!-- Optional JavaScript --> <!-- jQuery first, … -
Pipe Python Console To HTML iFrame (Django Web App)
Take the following bit of Python code from my Django web app: def Deploy(request, home, staging_folder): os.chdir(staging_folder) tf = Terraform() tf.init() tf.plan(capture_output=False) approve = {"auto-approve": True} try: print(tf.apply(capture_output=False, auto_approve=True, skip_plan=True,**approve)) except Exception as e: print(e) os.chdir(home) This prints to the console. Is it possible to pipe this through to a HTML iframe? If so, what will the iframe source be? <iframe src="" width="650" height="800" frameborder="0" ALLOWTRANSPARENCY="true" name="display"></iframe> I essentially want to redirect the output from the console to the iframe so the user can see exactly what's happening on a deployment page (like a live stream), rather than waiting for the function to execute whilst the HTML page looks like it's hanging. -
best parctice for URL's architectural Design in Django
I have been designing websites with Django for a while and I have also designed various sites. But here is a question that comes to mind at the beginning of any new project: What is the best a URLs architectural Design that creates both logical and meaningful URLs path as well as plugable apps? Parctical Example And Problem I will explain my question with a practical example. Suppose that we have project with these features: It has three applications called Shop, Blog and Support. It has three URL section: 2.1. Public section: that start with /. 2.2. Consumer panel: that start with /panel. 2.3. Administrator panel: that start with /administrator. Each application has 3 views. For example Shop has: public_shop_view, panel_shop_view and administrator_shop_view. Now, What is the best URL design for this project? I describe two possible answers here for URLs desing. Solution 1: project/urls.py path('', include('Shop.urls', namespce='Shop')), path('', include('Blog.urls', namespce='Blog')), path('', include('Support.urls', namespce='Support')), Shop/urls.py path('shop/', views.public_shop_view, name='public_shop_view'), path('panel/shop/', views.panel_shop_view, name='panel_shop_view'), path('administrator/shop/', views.administrator_shop_view, name='administrator_shop_view'), Blog/urls.py path('blog/', views.public_blog_view, name='public_blog_view'), path('panel/blog/', views.panel_blog_view, name='panel_blog_view'), path('administrator/blog/', views.administrator_blog_view, name='administrator_shop_view'), Support/urls.py path('support/', views.public_support_view, name='public_support_view'), path('panel/support/', views.panel_support_view, name='panel_support_view'), path('administrator/support/', views.administrator_support_view, name='administrator_support_view'), Solution 2: In this solution we create three app (Public, Panel, Administrator) that just have urls.py … -
Can I use query filter in Django template tag?
So I have this set of data in my DB, which are categorized. Then, I have a dropdown menu in my template, which is designed to filter the categories. When the page is loaded, all data are shown. Then if the user clicks a specific category in the dropdown menu, I want data with the selected category to show up. But I'm not sure if it is possible to have query filter in template tag. Here's my code. models.py class SeedCategory(models.Model): objects = models.Manager() category = models.CharField(max_length=10, default="book") def __str__(self): return self.category class AllSeed(models.Model): objects = models.Manager() category = models.ForeignKey(SeedCategory, on_delete=models.CASCADE, related_name = 'seed', null=True, default=None) title = models.CharField(max_length = 100) def __str__(self): return self.title views.py def seed(request): seeds = AllSeed.objects.all() context = { 'seeds':seeds, 'categories' : categories } return render(request, 'dansang/seed.html', context) template <div class="row"> <div class="col col-6"> <div class="dropdown"> <button class="btn btn-primary dropdown-toggle" type="button" id="dropdownMenuButton" data-toggle="dropdown" aria-haspopup="true" aria-expanded="false"> <strong>Seeds</strong> </button> <div class="dropdown-menu" aria-labelledby="dropdownMenuButton"> <button class="dropdown-item" id="seeAllCat">See All</button> <div class="dropdown-divider"></div> {% for cat in categories %} <button class="dropdown-item" id="{{cat-cat.category}}" value="{{cat.category}}"></button> {% endfor %} </div> </div> </div> </div> {% for item in seeds reversed %} <div class="row seed-row-allCat"> <a href="{{item.url}}" class="all-links" id="seed#{{forloop.revcounter}}" target="_blank" rel="noopener noreferrer"> <div class="col"> <span class="seed-title">{{item.category}} {{item.title}}</span><br … -
Checking if admin is logged in
I am trying to check if current logged in user is admin then allow them to access admin page else return to homepage. heres my view.py from django.shortcuts import render, redirect from django.http import HttpResponse from django.contrib.auth import login, logout, authenticate from django.contrib import messages from teacher.models import users def login(request): if request.method == "POST": username = request.POST['username'] password = request.POST['password'] user = authenticate(username = username, password = password) if user is not None: login(request, user) print (user) messages.success(request, "You have successfully Logged In.") return redirect('index') else: messages.error(request, "You have entered invalid credentials. Please try again") return redirect('login') else: return render(request, 'main/login.html') def admin(request): user = users.objects.get(category = 'admin') if user: return render(request, 'main/admin.html') else: return render(request, 'main/home.html') I have tried using different method of query. But I end up getting error page as 'user matching query doesn't exist'. Also it doesn't check if user is logged in or not. Even if user is not logged in it returns to admin page.