Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
How to redirect already authenticated users from login page to home in django?
I'm trying to redirect users who are already authenticated to the home page, so they can't access the login page while they are logged in. This was easily doable for my registration page as its leveraging a function in views.py, but seems to be harder to do for the login page as its leveraging django.contrib.auth.urls (so without a function in views.py). So my question is: how can I redirect users to a specific page without going through a view function? In this case, the mydomain.com/login/ page should redirect to mydomain.com when a users is already logged in. urlpatterns = [ path('admin/', admin.site.urls), path('', homepage), path('registration/', registration), path('', include('django.contrib.auth.urls')), ] -
Django super().save and get_or_create conflict
Inside my Django models under Movies table I have a super().save function. I also have a scraper inside my views.py in another app, that scrapes some data and inserts them using get_or_create() into the Movies table that has the super().save function in it. My problem is that When I try to scrape data and create them using get_or_create(), it gets created twice. I noticed when I comment the super.save() function in my models.py, the problem is solved. How can I have them both together? How can I prevent super.save() from happening when I'm scraping? Thaks in advance for your help. -
SQLite 3.8.3 or later is required (found 3.7.17) 0 0 vote positif
I am trying to eb deploy some Django app. But I face this error. File "/opt/python/run/venv/local/lib/python3.6/site-packages/django/db/utils.py", line 201, in __getitem__ backend = load_backend(db['ENGINE']) File "/opt/python/run/venv/local/lib/python3.6/site-packages/django/db/utils.py", line 110, in load_backend return import_module('%s.base' % backend_name) File "/opt/python/run/venv/lib64/python3.6/importlib/__init__.py", line 126, in import_module return _bootstrap._gcd_import(name[level:], package, level) File "/opt/python/run/venv/local/lib/python3.6/site-packages/django/db/backends/sqlite3/base.py", line 66, in <module> check_sqlite_version() File "/opt/python/run/venv/local/lib/python3.6/site-packages/django/db/backends/sqlite3/base.py", line 63, in check_sqlite_version raise ImproperlyConfigured('SQLite 3.8.3 or later is required (found %s).' % Database.sqlite_version) django.core.exceptions.ImproperlyConfigured: SQLite 3.8.3 or later is required (found 3.7.17). (ElasticBeanstalk::ExternalInvocationError) I use Django3.1, I've tried downgrading to 2.1 but it won't work neither. File "/opt/python/run/venv/local/lib/python3.6/site-packages/django/db/backends/sqlite3/creation.py", line 12, in is_in_memory_db return database_name == ':memory:' or 'mode=memory' in database_name TypeError: argument of type 'PosixPath' is not iterable. container_command 01_migrate in .ebextensions/db-migrate.config failed. For more detail, check /var/log/eb-activity.log using console or EB CLI. 2021-06-22 15:34:35 INFO Command execution completed on all instances. Summary: [Successful: 0, Failed: 1]. 2021-06-22 15:34:35 ERROR Unsuccessful command execution on instance id(s) 'i-0c5bbcb2318daa82b'. Aborting the operation. 2021-06-22 15:34:35 ERROR Failed to deploy application. ERROR: ServiceError - Failed to deploy application. I don't quite understand what's going on here, I'd use some help. -
django multiple user with multiple groups problem at signup
here is my problem, I created 3 groups with django admin panel ('admin', 'prof', 'etudiant' but I don't use the group admin for the moment). I created two model classes which inherit from the User model with oneToOneField ('Professeur' and 'Etudiant'). I also create a registration form for all two model classes. Using django post_save I can register my different users with groups. but now if I try to register a new user 'Professeur' with its own register form for example it is automatically added to the two groups 'prof' and 'etudiant'. what to do so that a user belongs to only one group etudiant/models.py from django.db import models from django.contrib.auth.models import User from django.core.validators import RegexValidator class Etudiant(models.Model): user = models.OneToOneField(User, on_delete=models.CASCADE, primary_key=True) et_matricule_regex = RegexValidator(regex=r'^(ET)-[A-Z]{2}-(PM)-[\d]{4}$', message="ex: ET-AD-PM-2020 -> Etudiant - Ali Diop - Pierre Michel- 2020") et_numero_matricule = models.CharField(validators=[et_matricule_regex], max_length=40, unique=True, verbose_name="numéro matricule") et_lieu_de_residence = models.CharField(max_length=150, blank=True, verbose_name="lieu de résidence") et_date_de_naissance = models.DateField(null=True, blank=True, verbose_name="date de naissance") et_telephone_regex = RegexValidator(regex=r'^\+?[\d]{3}-[\d]{2}-[\d]{2}-[\d]{2}-[\d]{2}$', message="+000-00-00-00-00") et_telephone = models.CharField(validators=[et_telephone_regex], max_length=40, blank=True, verbose_name="telephone") professeur/models.py from django.db import models from django.contrib.auth.models import User from django.core.validators import RegexValidator class Professeur(models.Model): user = models.OneToOneField(User, on_delete=models.CASCADE, primary_key=True) prof_matricule_regex = RegexValidator(regex=r'^(PR)-[A-Z]{2}-(PM)-[\d]{4}$', message="ex: PR-ZT-PM-2017 -> Professeur - Zan Togola - … -
NameError During Migrations for Django
I am trying to make migrations but am getting a NameError: name 'Product' is not defined and am not really sure why. I assume it may be something simple but I cannot for the life of me figure it out. The error is happening on line 13(class Orders... is line 12 for quick reference). My models are as follows: from django.db import models from django.contrib.auth.models import User from django.core.validators import MinLengthValidator from phone_field import PhoneField class MyUser(models.Model): user = models.OneToOneField(User, on_delete=models.CASCADE) address = models.CharField(max_length=255) phone = PhoneField(help_text='Contact Phone Number') class Orders(models.Model): products = models.ForeignKey(Product, on_delete=models.CASCADE) date_ordered = models.DateTimeField(auto_now=True) quantity_ordered = models.PositiveSmallIntegerField() price = models.PositiveIntegerField() user = models.OneToOneField(MyUser, on_delete=models.CASCADE) class Product(models.Model): name = models.CharField(max_length=120) description = models.CharField(max_length=255) price = models.PositiveIntegerField() style = models.CharField(max_length=50) artist = models.OneToOneField(Artist, on_delete=models.SET_NULL) class Review(models.Model): user = models.ForeignKey(MyUser, on_delete=models.CASCADE) rating = models.DecimalField(max_digits=2, decimal_places=1) comment = models.TextField(validators=[MinLengthValidator(10)]) product = models.OneToOneField(Product, on_delete=models.SET_NULL, null=True) class Artist(models.Model): name = models.CharField(max_length=255) -
uuid.uuid4() not creating random UUID in DJango forms
I have a product creation form in Django admin space. In the product creation form I have a clean product ID method: forms.py import UUID def clean_pk_product_id(self, *args, **kwargs): pk_product_id = uuid.uuid4() return pk_product_id For some reason, this is not generating a random UUID, it will attempt to use a 'pre-determined' ID. I have attempted to create multiple new objects, and all throw the same error stating that the primary key is not unique, and gives the same UUID > (3e18d2da4f624649a7cfa310108a1421) Is there something wrong with the way I am handling the validation of this form? I am unsure how Django admin processes these forms... -
Displaying data retrieve through GraphQL in a django website
(Disclaimer : I'm just getting started with django, and with web dev in general) I have a backend app that stores different kinds of resources. Some are public and some are private. The application is accessible only to identified users. A GraphQL API allows me to access the resources. On another server, I'd like to create a website that will be accessible to everyone. I want to use django to create it. The website will display a list of resources tagged as "public" in the backend app, with a pagination system and, say, 20 resources by page. The CSS will differ from the backend app and there will be a search section. From what I understant, I should be able to retrieve the data through the GraphQL API, but I'm a bit confused here. All doc and tutos I can find about django and GraphQL seem to be about setting up a GraphQL API server with django. All I want to do is to build custom queries and to display them on my different html pages. How can I do that? Where should I start? Any hint or direction will be much appreciated, thank you! -
From Django to Angular - Create dynamic "Fill in blank" and "Multiple choices" questions/exercises
I created years ago a website with Django, where a teacher can add dynamic questions and exercises. For example, Fill in blank or Multiple choices questions, like this one : "Rabbits eats (multiplechoices: apples,carrots,tomatoes) and live in a (fillinblank: burrow)." This question will display a dropdown with 'apples','carrots' and 'tomatoes' choices first, and a text input for the 'burrow' answer. Of course, a question may contains any number of dropdowns or inputs. With Django, it was pretty simple to parse the text from db and replace special patterns (representing input or dropdown) with the right answers when rendering the HTML. I found that with Angular, I can use the same solution, as described here, but I don't know if it's a safe solution. I also read something about Component Factory in Angular, but I don't really figure out how to implement it. The goal is to be able to display all the exercises stored in my db in a brand new Angular web app. Any suggestion would be welcome. Thanks for reading ! -
How to map the response and save it to the database in Django?
I have a Person model: class Person(AbstractBaseUser): userName = models.CharField(max_length=100, unique=True, null=False, blank=False) is_active = models.BooleanField(default=True) staff = models.BooleanField(default=False) admin = models.BooleanField(default=False) dateOfBirth = models.DateField(null=True, blank=True) In my serializers.py I have this: class PersonSerializer(serializers.ModelSerializer): class Meta: model = Person fields = '__all__' def create(self, validated_data): userName = validated_data['userName'] is_active = validated_data['is_active'] staff = validated_data['staff'] admin = validated_data['admin'] dateOfBirth = validated_data['dateOfBirth'] user = Person(userName=userName, is_active=is_active, staff=staff, admin=admin, dateOfBirth=dateOfBirth) user.set_password("") user.save() return user Then in my views.py I use the serializer like this: class PersonList(generics.ListCreateAPIView): permission_classes = (permissions.AllowAny,) serializer_class = PersonSerializer def post(self, request, format=None): serializer = PersonSerializer(data=request.data) if serializer.is_valid(): serializer.save() return Response(serializer.data, status=status.HTTP_201_CREATED) return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST) Now, this works as supposed to when I send the request from the client with the Person data. But what I'd like to do now is to modify my API so that it would receive a request from the client with no Person information, just a verification code or something like that. After that the back end would send a request to an external API and as a response my app would receive that Person data. I'm wondering what would be the best way to apply these changes. Do I just modify my serializer to … -
How to combine querysets retaining annotate fields?
I have two different queries for the same table: m_i = MyModel.objects.filter( user__profile__newsletter=True ).annotate(name=F('user__profile__complete_name'))\ .values('name')\ .annotate(indicado=Count('user'))\ .order_by('user__profile__complete_name') and m_e = MyModel.objects.filter( user__profile__newsletter=True, chosen=True)\ ).annotate(name=F('user__profile__complete_name'))\ .values('name')\ .annotate(escolhido=Count('user'))\ .order_by('user__profile__complete_name') The queries are very much the same except for one filter in the second and I annotate this same value for the both of them but they come out with different values. Right now the querysets are like this: # m_i [{name:'ex1', indicado: 1}, {name:'ex2', indicado: 2}, {name:'ex3', indicado: 9}, {name:'ex4', indicado: 3}] # m_e [{name:'ex1', escolhido: 1}, {name:'ex2', escolhido: 1}, {name:'ex3', escolhido: 4}, {name:'ex4', escolhido: 2}] I wanted to unite the querysets so I could have something like this: # union [{name:'ex1', escolhido: 1, indicado: 1}, {name:'ex2', escolhido: 1, , indicado: 2}, {name:'ex3', escolhido: 4, , indicado: 9}, {name:'ex4', escolhido: 2, , indicado: 3}] I tried using the method union like this m_i.union(m_e) but it seems as if it assumes that indicado and escolhido are the same thing and retains only one of the two. Using itertools.chain returns to me the both querysets one after the other, not united by the same key. Is there a way to union them both without iterating on the querysets? I can go over all of … -
best way to integrate 2checkout with django
I know(maybe) it's silly question, but just sucked in to it. I'm building an eCommerce website using django, where i need to use 2checkout payment gateway, i'm wondering if there is a package, tutorials or anything that helps me(almost 3days searching about.. I've no idea if it's possible) :| -
How to determine the type of a querset in django
How can I check to know the 'TYPE' of my database queryset. I want to use an 'IF' statement to do something when a certain condition is met but I don't know how to go about it. def tot_query(request): fb = Fblink.objects.all() tw = Twlink.objects.all() yt = Ytlink.objects.all() th = Thlink.objects.all() ig = Iglink.objects.all() sc = Sclink.objects.all() tk = Tklink.objects.all() query = chain(fb, tw, yt, th, ig, sc, tk) print(type(list(query)[0])) if type(list(query)[0]) == 'src.link.models.Fblink': print("This is a facebook link") The first print statement prints the following <class 'src.link.models.Fblink'> and the second and one prints nothing. -
How to display Logs of Django middleware in terminal
I created my own Middleware to validate HTTP-Requests. To make sure everything works fine, I added some logs into the code. I excpect that they will be display in the terminal (if reached obviously). import logging LOG = logging.getLogger(__name__) class ValidationMiddleware: # init-Method is called once the server starts def __init__(self, get_response): self.get_response = get_response # call-Method is called for every new request to the Django application def __call__(self, request): # Code to be executed before middleware is called validate_settings = settings.VALIDATIONMIDDLEWARE.get("default") token_header = 'X-Token' if token_header in request.headers: request_token = request.headers[token_header] url = validate_settings.get("VALIDATE_URL") md5_token = hashlib.md5(request_token.encode('utf-8')).hexdigest() payload = {'checksum': md5_token} LOG.info("Calling" + url + " to validate token.") req = requests.post(url, json=payload) result = req.json() if result['result'] is False: LOG.info("Token not valid anymore.") raise PermissionDenied else: LOG.info("Big Error") requests.HTTPError() response = self.get_response(request) return response I start my django server and did some Post requests (created users via admin, login, etc.), but none of the Logs in the code was displayed in the terminal. Why? -
Django ORM convert month name to date
I want to convert a month name (stored as CharField) to a DateField using the Django ORM. For example, if I have July in the database, then I want it to return as 07/01/2021 The way I have done it before without Django ORM is like this: dt.datetime.strptime(MONTH_NME + ', 01, ' + str(dt.datetime.now().year), '%B, %d, %Y') However, I would perfer to use the Django ORM, but am unable to get my head around how to do this. Here is what I have so far: QS = MyModel.objects.all().Annotate( review_dte = dt.datetime.strptime(F('MONTH_NME') + ', 01, ' + str(dt.datetime.now().year), '%B, %d, %Y') ) Any help would be appreciated! -
Django ORM: how do I count objects that have the same properties?
I want to use the Django ORM to find instances in my models that have some of the same properties. For instance, given this model: class Person(Model): name = CharField() age = IntegerField() gender = CharField() how can I find all persons that don't have a unique age and gender? For instance given the following data: John 20 M Bob 21 M Diana 20 F Janet 20 F I want a query that would return Diana and Janet. Thanks! -
Why does one user can add only one record in form in django?
I have created form, in which users can add some kind of information. But, I noticed that one user can add only one object. I mean, after secod time of filling out a form, new infermation displayed, but old record was deleted. models.py: from django.db import models from django.contrib.auth.models import User class File(models.Model): customer = models.ForeignKey(User, on_delete=models.CASCADE, null=True) graf_title = models.CharField('Название файла', max_length = 200) chart = models.TextField('Значения осей') title = models.CharField('Название Графика', max_length = 50) x_title = models.CharField('Название Оси Х', max_length = 50) y_title = models.CharField('Название Оси Y', max_length = 50) forms.py: from .models import File from django import forms class FileForm(ModelForm): class Meta: model = File fields = '__all__' exclude = ['customer'] views.py: #It is the form view def main(request): error = '' customer = File.objects.get(customer=request.user) formset = FileForm(request.POST) if request.method == 'POST': formset = FileForm(request.POST, instance=customer) if formset.is_valid(): formset.save() return redirect('grafic:list') else: error = 'Форма была неверной(' formset = FileForm() data = { 'form': formset, 'error': error, } return render(request, 'graf/first.html', data) #list is the view, which show all user's records def list(request): record= File.objects.filter(customer=request.user) return render(request, 'graf/list.html', {'record': record}) SO as I said, when one user fills out form more than one time, in the list … -
Run ansible playbook after changing host file and vars
I am referencing ansible playbook to create some VMs from django, and dynamically change host file and extra vars in ansible based on user submitted form. Now it is stuck on the implementation of the race condition for the host file and extra vars, say 2 users are modifying them at the same time, so I use lock for the modification in a celery task, however, when the 1st user changed the files and run playbook using his own variables and host files. The 2nd user is doing the change as well, my question is whether the 2nd user changing the files(host and vars) will cause the 1st to run the playbook abnormally? Thanks. -
Django - can't update existing data in database, doesn't update
I have an authenticated user with related data, such as a file which the user uploaded and a description and ID number associated with the user. (The user previously used a Document model and associated form to upload the original info. This is working fine. Now I have an EditForm which I want to use to update the user ID and description, but when I call save, it doesn't get updated. Here is the views and models. I can print to the console my new data as entered in the form, I'm just not saving it correctly. Thanks in advance. views.py: def edit(request): items = Document.objects.filter(created_by=request.user) for object in items: print(object.id_number,'original') # shows original data print(object.description,'original') # shows original data if request.method == 'POST': form = EditForm(request.POST, instance = request.user) if form.is_valid(): post = form.save(commit = False) post.description = form.cleaned_data['description'] post.id_number = form.cleaned_data['id_number'] print(post.id_number,'############') #shows form data as entered print(post.description,'!!!!!!!!!!!') #shows form data as entered post.save() else: return render(request, 'edit.html', {'form': form}) messages.info(request, 'Successfully Saved') return redirect('home') else: form = EditForm( instance = request.user) return render(request, 'edit.html',{ 'form':form, 'items':items }) Models.py from django.db import models from django.conf import settings # Create your models here. class Document(models.Model): description = models.CharField(max_length=255, blank=True) … -
Should I automatically update my Profile model on User updates?
I am wiring a Profile model to my User with a signal receiver that updates the Profile on User updates, but I'm not sure what is the drawback of dealing with the Profile update in my own code? My logic for posing this question is that I might want an user to exist without a profile, for example I don't want my admins to be associated with a credit card number nor I want the credit card number to be nullable. Is assigning a signal receiver from the User to a Profile model just a matter of convenience or is there some other interaction that would be difficult to manage otherwise? -
how to overwrite wagtail function?
i want to overwrite wagtail function i want to add a column in admin user page but i want to use # add column class SiteUser(models.Model): user = models.OneToOneField(User, on_delete=models.CASCADE) note = models.TextField(verbose_name='note') this way to add column and i found wagtail is not allow to custom admin user view in wagtail/users/views/users.py so i want to overwrite function in users.py def index(request, *args): i want to edit it and change users column how i can do that? thanks for help~ -
Adding product variants into database with forms in Django
First of all I'm new to Django so I apologize in advance for wasting your time if I have any silly questions. I'm trying to create an e-commerce project in Django and need to add product variations into the database. What is the correct way doing this? I've come so far, but can't go any further. I appreciate if you can help. What I want to do: "Generate" button generates all the possible variations according to selection as html(Javascript). "Submit" button post the form Try to save variations to the database Error: SkuForm.variation_value1 is not an instance of VariationValuesModel. Variation Section ScreenShot FORM: class ProductsForm(forms.ModelForm): class Meta: model = ProductsModel fields = ['name',] class SkusForm(forms.ModelForm): variation_value1 = forms.ModelMultipleChoiceField(queryset=VariationValuesModel.objects.filter(variation_id=2).order_by("name"), required=False, widget=forms.SelectMultiple(attrs={ 'id' : 'var_color', 'class' : 'form-control selectpicker', 'title' : 'Select Color', })) variation_value2 = forms.ModelMultipleChoiceField(queryset=VariationValuesModel.objects.filter(variation_id=1).order_by("name"), required=False, widget=forms.SelectMultiple(attrs={ 'id' : 'var_size', 'class' : 'form-control selectpicker', 'title' : 'Select Size', })) variation_value3 = forms.ModelMultipleChoiceField(queryset=VariationValuesModel.objects.filter(variation_id=3).order_by("name"), required=False, widget=forms.SelectMultiple(attrs={ 'id' : 'var_pattern', 'class' : 'form-control selectpicker', 'title' : 'Select Pattern', })) class Meta: model = SkusModel fields = ['variation_value1', 'variation_value2', 'variation_value3',] MODEL: class ProductsModel(models.Model): name = models.CharField(max_length = 200, blank=False, null=False, class SkusModel(models.Model): product = models.ForeignKey(ProductsModel, related_name='product_sku', on_delete=models.DO_NOTHING) variation_value1 = models.ForeignKey(VariationValuesModel, related_name='VariationValue1_sku', blank=True, null=True, on_delete=models.DO_NOTHING) … -
Calling Model method inside template file
I am learning to create a blog website using django. I encountered an issue while calling my model method inside template file. The site is not displaying contents inside the body. It was working fine when i used article.body but its not working when i use article.snippet. models.py file:- ... from django.db import models class Article(models.Model): title = models.CharField(max_length = 100) slug = models.SlugField() body = models.TextField() date = models.DateTimeField(auto_now_add=True) def __str__(self): return self.title def snippet(self): return self.body[:50] ... articles_list.html file:- ... <html lang="en" dir="ltr"> <head> <meta charset="utf-8"> <title>Articles</title> </head> <body> <h1>Articles List</h1> <div class="articles"> {% for article in articles %} <div class="article"> <h2><a href="">{{article.title}}</a></h2> <p>{{article.body.snippet}}</p> <p>{{article.date}}</p> </div> {% endfor %} </div> </body> </html> ... views.py file:- ... from django.shortcuts import render from django.http import HttpResponse from .models import Article def articles_list(request): articles = Article.objects.all() return render(request, 'articles/articles_list.html', {'articles': articles}) ... There is no error displayed in code but still there is no output inside body tag. -
Algolia ranking edge cases
I am new to Algolia and Django so any help with the following task would be much appreciated. I am trying to re-rank the search results on the UI such that certain edge cases don't cause issues anymore. The problem was that initially there was only one searchable attribute that was used but we actually want that one to be split into 2. I did that so I split the initial attribute into 2 attributes, call them attribute_1 and attribute_2 and also passed them in the settings of the index.py file as follows: "searchableAttributes": [ "attribute_1", "attribute_2" ] From the documentation I understand that the order in which the attributes are added in the above lists prioritizes the search so the search engine will first look for matches in attribute_1 and then in attribute_2. This solved the issue for one of the edge cases but there is still one edge case that is not solved. I will explain the issue with this edge case below in more detail. Call the 2 examples that I want to be ranked for the remaining edge case E1 and E2. The search keyword, call it some_text, matches perfectly attribute_1 of E1 but it is … -
Perform action on saving inline django model
I have two models, one CommentModel displayed as an inline to the MainModel in the admin. models.py: class MainModel(models.Model): customer = models.OneToOneField(Customer, on_delete=models.CASCADE) class CommentModel(models.Model): main = models.ForeignKey(MainModel, on_delete=models.CASCADE, default=None) comment_german = CharField(blank=True, default='', null=True) comment_english = CharField(blank=True, default='', null=True) admin.py: class MainModelAdmin(SimpleHistoryAdmin): model = MainModel inlines = [CommentModelInline] class CommentModelInline(admin.StackedInline): model = CommentModel fields = ['comment_german', 'comment_english'] Suppose I want to automatically translate what the user writes in the comment_german field and save it to the comment_english field when the MainModel is saved. I tried overriding the save method. I successfully did it for another model which is not an inline. But this does not work for inlines. I need something like this: def save(self, *args, **kwargs): super().save(*args, **kwargs) for comment in CommentModel.objects.filter(main=self): if comment.comment_german != '' and comment.comment_english == '': comment.comment_english = comment.comment_german.translate_to_english() There must be a way to do this, maybe with a formset, but I can't wrap my head around it. -
Django Clear Sessions and Flags every 20 mins
I am working on a Django Website in which whenever a user logs in it creates a session and in Models active is set to true (is_active=true) when users logout the sessions clear and is_active=false for the user But the problem is when a User closes the tab/ browser instead of logging out user is still said to be active . How to make a function which will logout all active users after 15 mins of their login? Models.py class Employee(models.Model): emp_id = models.CharField(primary_key=True,max_length=50) name = models.CharField(max_length=50) gender = models.CharField(max_length=50,default="None") email = models.EmailField(max_length=50) password = models.CharField(max_length=50,help_text="Minimum of 8 Characters") dept = models.CharField(max_length=50) phone = models.CharField(max_length=20) last_login=models.DateTimeField(auto_now_add=True, blank=True) is_active=models.BooleanField(default=False) authcode=models.CharField(max_length=25) Views.py def home(request): loginUser= request.session['username'] if loginUser == '': return redirect('log') name= request.session['name'] return render(request,'home.html') def logot(request): loginUser=request.session['username'] Employee.objects.filter(emp_id=loginUser).update(is_active=False) request.session['name']=''; request.session['username']=''; return redirect('welcome') # def scheduled_logout # Logout all user's after 15 mins of last_login Thanks in advance