Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
how to make an unlockscreen function and refer to the previous page they open before they lock it if they succeed login in django
Im trying to make a lock_screen function where you can lock the website , if you want to go to toilet or not , and login again if you want to unlock it , and refer to the last page they visit before they lock it The problem is , i put the name and the password right , but still redirect to lockscreen here's the view.py def unlockscreen(request): if request.method == 'POST': form = AuthenticationForm(data=request.POST) if form.is_valid(): username = form.cleaned_data.get('username') password = form.cleaned_data.get('password') path = request.META.get('HTTP_REFERER') guess = User.objects.get(username=username) identity = guess.id table2 = UserProfileInfo.objects.get(user_id=identity) role = table2.role user = authenticate(username=username,password=password) if user is not None: if role == 'Business Analyst': request.session['username'] = username request.session['role'] = role login(request, user) return HttpResponseRedirect('/home/') else : messages.error(request,"error1") else : messages.error(request,"error2") else : messages.error(request,"error3") form = AuthenticationForm() return render(request,"lock_screen.html",{"form":form}) #pretend the last page we visit is the index.html @cache_control(no_cache=True, must_revalidate=True, no_store=True) @login_required def index_view(request): if request.session.get('username'): username = request.session['username'] role = request.session['role'] print(username) return render(request, 'index.html',{"username":username , "role":role}) else : messages.error(request, "Login required") return HttpResponseRedirect('/') def lockscreen(request): del request.session['username'] return render(request, 'lock_screen.html') lock_screen.html <form method="post"> {% csrf_token %} <input type="text" name="username" value = {{request.user.username}} class ="form-control placeholder-no-fix" disabled=""> <br> <input type="password" name="password" placeholder="Password" … -
Detect changes in models and migrate automatically without have to run the migrations command
I want to create a new model on every button click in Django and migrate it without running migrations command. Is that possible??if yes,how? Thanks in advance.🙂 -
Display contents of a text file in Django template
I am attempting to create a file in simple website and then read the contents of the same in a variable inside a Django view function and parse the variable to the template to be displayed on web page. However, when I print the variable, it appears the same on cmd as is in the original text file, but the output on the web page has no formattings but appears like a single string. I've been stuck on it for two days. Also I'm relatively new to django and self learning it ''' file1 = open(r'status.txt','w',encoding='UTF-8') file1.seek(0) for i in range(0,len(data.split())): file1.write(data.split()[i] + " ") if i%5==0 and i!=0 and i!=5: file1.write("\n") file1.close() file1 = open(r'status.txt',"r+",encoding='UTF-8') d = file1.read() print(d) #prints on cmd in the same formatting as in text file return render(request,'status.html',{'dat':d}) **#the html displays it only as a single text string** ''' ''' {% block content %} {{dat}} {% endblock %} '''html page display -
Secure a file in endpoint with the same permissions as the endpoint in Django REST
I have a project in Django REST framework with model like this class Attachment attachment_type = models.PositiveSmallIntegerField(choices=constants.AttachmentTypes.CHOICES) creator = models.ForeignKey(User, related_name="attachments", on_delete=models.PROTECT) file = models.FileField(upload_to='uploads/%Y/%m/%d/', max_length=511) name = models.CharField(max_length=255) size = models.CharField(max_length=30) And ModelViewSet using the model with custom permissions class AttachmentViewSet(viewsets.ModelViewSet): queryset = models.Attachment.objects.all() Permissions for this ViewSet are based on a user roles and work fine. Problem is with permissions to a file field. It is now accessible to whoever has the link. I need the same permissions to a file as to Attachment endpoint. What is the proper way to do it? -
how to integrate keycloak with django and angular
i am using keycloak to login to my angular app instead of django rest API (simple token based authentication ) and i am following this below procedure and flow. so is correct? angular web page click on login went to keycloak login login successful and keycloak returned to angular app access key, id token , refresh token etc.. what is the next flow , what i need to send to django API from angular app , what i need to send fro django to angular? any suggestion? -
Optional virtual environment creation error
'"virtualenv"' is not recognized as an internal or external command, operable program or batch file.-is the error message that displayed after typing "mkvirtualenv " I am trying to create another virtual environment for a django project -
How to get name respect to that id form mysql table?
In my project i have crud like operation, so when i select department i save id of that item , and bind to table to show that inserted records , so when i bind department i want to bind name of that department not that id . pls help me in this.. Model.py class Department(models.Model): ACTIVE = 1 INACTIVE = 2 DELETED = 3 STATUS_CHOICES = ( (ACTIVE, 'active'), (INACTIVE, 'inactive'), (DELETED, 'deleted'), ) department_id = models.AutoField(primary_key=True) department_name = models.CharField(max_length=30, null=False) created_on = models.DateTimeField(auto_now_add=True, null=False) created_by = models.CharField(max_length=100, null=False) modified_on = models.DateTimeField(auto_now_add=True) modified_by = models.CharField(max_length=100) status = models.CharField(max_length=10, null=False, choices=STATUS_CHOICES) objects = UserManager() class Meta: managed = True db_table = "ht_department" def __str__(self): return self.department_id forms.py class EmpForm(ModelForm): class Meta: model = Employee fields = ["employee_id", "Name", "designation", "department_id", "manager_id", "date_of_joining","date_of_birth", "location_id", "email", "contact_number", "password", "created_by", "modified_by", "status", "user_type"] class dept(ModelForm): class Meta: model = Department fields = ["department_id", "department_name", "created_by", "modified_by", "status"] class EmpLoc(ModelForm): class Meta: model = Location fields = ["location_id", "location_name", "created_by", "modified_by", "status"] html <tbody id="myTable"> {% for employee in employees %} <tr> <td>{{ employee.employee_id}}</td> <td>{{ employee.Name}}</td> <td>{{ employee.designation}}</td> <td>{{ employee.department_id}}</td> <td>{{ employee.manager_id}}</td> <td>{{ employee.location_id}}</td> <td> <a href="#editEmployeeModal" class="edit" data-toggle="modal"><i class="material-icons" data-toggle="tooltip" title="Edit">&#xE254;</i></a> <a href="#deleteEmployeeModal" class="delete" … -
How to return data from a database for a logged-in user in Django Rest Framework?
Scenario: I have two APIs currently. A RegisterAPI and a LoginAPI. The RegisterAPI registers a new user and a LoginAPI allows them to access their details only. I used JWT authentication as well. I want to retrieve data from the database for a particular user who logs in using the Login API in DRF. My intention is to interact with the database but the problem is that I have two models in my serializer with a One-To-One relationship and I am confused about how to move forward with this issue. To get a clearer picture, view my code below: models.py: from django.db import models from django.contrib.auth.models import User class UserData(models.Model): user = models.OneToOneField(User, on_delete = models.CASCADE) company = models.CharField(max_length=100, blank=True, null=True) address = models.TextField() views.py: class RegisterAPI(APIView): permission_classes = [AllowAny] def post(self, request, format=None): serializer = UserDataSerializer(data=request.data) if serializer.is_valid(): content = { 'status': 'Thanks for registering'} return Response(content, status=status.HTTP_201_CREATED) return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST) class LoginAPI(viewsets.ModelViewSet): permission_classes = [IsAuthenticated] def list(self, request, *args, **kwargs): user_id = request.user.id queryset = User.objects.filter(id = user_id).first() user_serializer = UserSerializer(queryset, many = True) return Response(user_serializer.data) serializers.py: from rest_framework import serializers from users.models import UserData from django.contrib.auth.models import User class UserDataSerializer(serializers.ModelSerializer): class Meta: model = userData fields = … -
Filer and Multi-Tenant Problem (Postgres Schemas)
We are experiencing a weird problem. We use Postgresql Schemas and uses request middleware to switch between different schemas. Keep in mind that the Model -> Content Type ID links differ from schema to schema due to new models made after the first tenant was created. When I restart UWSGI and then on Tenant 1 goto the Filer->Folder page in the admin then it works well. Now when I go to Tenant 2 then it seems that filer is trying to use the content type id of the File model in Tenant 1 to lookup the real instance class. Could it be that the ctype_id is being cached somehow? -
draw polygon on google map and save for specific account
I want to draw polygon on google map to highlight the area and user can save and edit it whenever they want. I am a beginner and does not have a proper code. -
Django: Problem with Separating the Two User Names
I am learning Django by building an application, called TravelBuddies. It will allow travelers to plan their trip and keep associated travel items (such as bookings, tickets, copy of passport, insurance information, etc), as well as create alerts for daily activities. The application will also able to update local information such as weather or daily news to the traveler. Travelers can also share the travel information with someone or have someone to collaborate with them to plan for the trip. I am facing a problem. When I go to http://127.0.0.1:8000/triplist/, I see this page: When I click on Trip Name: Kuala Lumpur and taken to activity.html through this link: http://127.0.0.1:8000/triplist/kuala-lumpur/: "john" and "williams" are two separate user names. They need to be separated by a comma (,). So it will look like this: Co-traveller: john, williams. How can I do it? Here are my codes in models.py: from django.contrib.auth.models import User from django.db import models from django.template.defaultfilters import slugify # Create your models here. class Trip(models.Model): trip_name = models.CharField(max_length=100) date = models.DateField() planner_name = models.CharField(max_length=100) add_coplanner = models.ManyToManyField(User) slug = models.SlugField(max_length=150, default='null') def __str__(self): return self.trip_name def save(self, *args, **kwargs): self.slug = slugify(self.trip_name) super().save(*args, **kwargs) class Activity(models.Model): trip = models.ForeignKey(Trip, … -
How can write on two different postgres model?
Question: How can I write to two different Postgres model and read from one of them? Actually, I want to migrate some data from one Postgres database to another Postgres database. the databases schema are the same. So after migration, I want to write both databases and read from one of them. What I tried: I tried to handle it by writing a new database router in Django. from django.conf import settings class MigrationRouter: def db_for_read(self, model, **hints): return settings.READ_ALIAS_DB def db_for_write(self, model, **hints): return settings.WRITE_ALIAS_DB def allow_relation(self, obj1, obj2, **hints): return None def allow_migrate(self, db, app_label, model_name=None, **hints): if db in (settings.READ_ALIAS_DB, settings.WRITE_ALIAS_DB): return True return None If I put both database aliases in the db_for_write method that does not work as I expected. -
Update or create a model in django
I have a django table named Inventory Models.py class ClientInventory(models.Model): product_short_code = models.CharField(max_length=500, default=0, null=True) product_quantity = models.IntegerField(default=0, null=True) product_owner = models.ForeignKey(Client, on_delete=models.CASCADE, related_name='inventory_owner') and I want to update this inventory whenever a form named Delivered Docket is filled and this is my view to do that Views.py @method_decorator([login_required, employee_required], name='dispatch') class DeliveredDocketFormView(CreateView): model = DeliveredDocket fields = "__all__" template_name = 'packsapp/employee/docketDeliveredForm.html' def form_valid (self, form): product = form.save(commit=False) product.save() data = form.cleaned_data ClientInventory.objects.update_or_create(product_short_code=data["product1"], product_quantity =data["product1_recieved_quantity"], product_owner = data['created_for']) ClientInventory.objects.update_or_create(product_short_code=data["product2"], product_quantity=data["product2_recieved_quantity"], product_owner=data['created_for']) ClientInventory.objects.update_or_create(product_short_code=data["product3"], product_quantity=data["product3_recieved_quantity"], product_owner=data['created_for']) ClientInventory.objects.update_or_create(product_short_code=data["product4"], product_quantity=data["product4_recieved_quantity"], product_owner=data['created_for']) ClientInventory.objects.update_or_create(product_short_code=data["product5"], product_quantity=data["product5_recieved_quantity"], product_owner=data['created_for']) ClientInventory.objects.update_or_create(product_short_code=data["product6"], product_quantity=data["product6_recieved_quantity"], product_owner=data['created_for']) ClientInventory.objects.update_or_create(product_short_code=data["product7"], product_quantity=data["product7_recieved_quantity"], product_owner=data['created_for']) ClientInventory.objects.update_or_create(product_short_code=data["product8"], product_quantity=data["product8_recieved_quantity"], product_owner=data['created_for']) messages.success(self.request, 'The Delivered Docket was created with success!') return redirect('employee:delivered_docket_table') How can I reduce the number of ORM calls as this does not feel right?? This is the form data: {'sender': <Warehouse: Yantra Gurgaon Warehouse>, 'pending_docket_list': <AllotmentDocket: Yantra Gurgaon Warehouse::client::2019-12-04>, 'material_received_date': datetime.date(2019, 12, 4), 'pod _received': 'Yes', 'product1': 'Vipin', 'product1_alloted_quantity': 56, 'product1_recieved_quantity': 56, 'product2': None, 'product2_alloted_quantity': None, 'product2_recieved_quantity': None, 'product3': No ne, 'product3_alloted_quantity': None, 'product3_recieved_quantity': None, 'product4': None, 'product4_alloted_quantity': None, 'product4_recieved_quantity': None, 'product5': None, 'product5_alloted_quantity': None, 'product5_recieved_quantity': None, 'product6': None, 'product6_alloted_quantity': None, 'product6_recieved_quantity': None, 'product7': None, 'product7_alloted_quantity': None, 'product7_recieved_quanti ty': None, 'product8': None, 'product8_alloted_quantity': None, 'product8_recieved_quantity': None, 'created_on': datetime.datetime(2019, 12, … -
For Python2 to Python3 code conversion, Which version of Python & Django best suited?
Currently I am working in big firm where we need to convert python2 old big Django project into python3 version so I have done lots of research related but still not able to find any perfect answer related to which version of Python and Django best suited for conversion. Currently I am using Python : 2.7.16 & Django : 1.9.13 in my old version. Is there any document or reference available which can suggest me best suited version of Python & Django for above old version for python2 to python3 conversion. Thanks. -
How can I fix this error in my tutorial im working on?
I cant seem to figure this tutorial out, im studying django and python and im super stuck. My book says to update the paths like so @code TEMPLATE_DIRS = (getabspath('templates')) MEDIA_ROOT = getabspath('media') MEDIA_URL = '/media/' but when I do i get a syntax error. enter image description here -
Problem with Displaying the Output of models.ManyToManyField(User)
I am learning Django by building an application, called TravelBuddies. It will allow travelers to plan their trip and keep associated travel items (such as bookings, tickets, copy of passport, insurance information, etc), as well as create alerts for daily activities. The application will also able to update local information such as weather or daily news to the traveler. Travelers can also share the travel information with someone or have someone to collaborate with them to plan for the trip. I am facing a problem. I have added two activities for Kuala Lumpur through Django admin. They are "Going to Botanical Garden" and "Going to Aquaria." When I go to http://127.0.0.1:8000/triplist/, I see this page: As you can see, in the Co-planner field, the name of the user is being displayed as <QuerySet [<User: williams>]>.But it is supposed to be displayed as Co-planner: williams. Same problem occurs when I click on Trip Name: Kuala Lumpur and taken to http://127.0.0.1:8000/triplist/kuala-lumpur/: Here are my codes in models.py: from django.contrib.auth.models import User from django.db import models # Create your models here. from django.template.defaultfilters import slugify class Trip(models.Model): trip_name = models.CharField(max_length=100) date = models.DateField() planner_name = models.CharField(max_length=100) add_coplanner = models.ManyToManyField(User) slug = models.SlugField(max_length=150, default='null') … -
I m facing this prblm when I m running my django application on local host I m using atom ide
after starting my server when I open browser then this shows -
How to check whether a object is expired or not in django?
I'm trying to check whether a object is expired or not by using:- if (Token.objects.get(content=token).DatePosted-timezone.now())<'1 days': return False else: return True It is producing following error:- '<' not supported between instances of 'datetime.timedelta' and 'str' my question is hpw can i convert 0 days into a datetime.timedelta object? -
Django on docker container error when trying to connect to local mysql database
Please help me, I have django application that run on docker container with docker-compose, but i have error when trying to connect to mysql database on my local machine. The error message is like this : Can’t connect to local MySQL server through socket ‘/var/run/mysqld/mysqld.sock’ my docker-compose.yml file is like this : version: '3' services: web: container_name: web build: . command: python manage.py runserver 0.0.0.0:8000 volumes: - .:/code ports: - "8000:8000" and my Dockerfile is like this : FROM python:3 ENV PYTHONUNBUFFERED 1 RUN mkdir /code WORKDIR /code COPY . /code/ RUN apt-get update RUN apt-get install python3-dev default-libmysqlclient-dev -y RUN pip install pip -U RUN pip install -r requirements.txt -
ModuleNotFound error in django. PS - virtualenv misbehaving
Something had been wrong with my virtualenv. I never shut pc down nor the text editor with terminal(vs code). I just deactivated vituralenv last night and activated it today to find it's name has changed. I wasn't able to runserver so I figured out something was wrong with virutalenv because on pip freeze it shows all the packages. I installed virtualenv again and made a virtualenv with same name in same directory which overwrote previous virtualenv and now it's fine. Although while executing python manage.py runserver, it shows. Watching for file changes with StatReloader Exception in thread django-main-thread: Traceback (most recent call last): File "/usr/lib/python3.8/threading.py", line 932, in _bootstrap_inner self.run() File "/usr/lib/python3.8/threading.py", line 870, in run self._target(*self._args, **self._kwargs) File "/home/udaykhalsa/Projects/quick_timetable_main/quicktt/lib/python3.8/site-packages/django/utils/autoreload.py", line 54, in wrapper fn(*args, **kwargs) File "/home/udaykhalsa/Projects/quick_timetable_main/quicktt/lib/python3.8/site-packages/django/core/management/commands/runserver.py", line 109, in inner_run autoreload.raise_last_exception() File "/home/udaykhalsa/Projects/quick_timetable_main/quicktt/lib/python3.8/site-packages/django/utils/autoreload.py", line 77, in raise_last_exception raise _exception[1] File "/home/udaykhalsa/Projects/quick_timetable_main/quicktt/lib/python3.8/site-packages/django/core/management/__init__.py", line 337, in execute autoreload.check_errors(django.setup)() File "/home/udaykhalsa/Projects/quick_timetable_main/quicktt/lib/python3.8/site-packages/django/utils/autoreload.py", line 54, in wrapper fn(*args, **kwargs) File "/home/udaykhalsa/Projects/quick_timetable_main/quicktt/lib/python3.8/site-packages/django/__init__.py", line 24, in setup apps.populate(settings.INSTALLED_APPS) File "/home/udaykhalsa/Projects/quick_timetable_main/quicktt/lib/python3.8/site-packages/django/apps/registry.py", line 91, in populate app_config = AppConfig.create(entry) File "/home/udaykhalsa/Projects/quick_timetable_main/quicktt/lib/python3.8/site-packages/django/apps/config.py", line 116, in create mod = import_module(mod_path) File "/home/udaykhalsa/Projects/quick_timetable_main/quicktt/lib/python3.8/importlib/__init__.py", line 127, in import_module return _bootstrap._gcd_import(name[level:], package, level) File "<frozen importlib._bootstrap>", line 1014, in _gcd_import File "<frozen … -
Django changes dropdown menu to Input Text Fields by itself (CODE HAS DROPDOWN!)
THIS IS THE MODEL.PY file! - class userchoice(models.Model): choice = [] choice2 = list(userdata.objects.all().values_list('key')) for x in choice2: for t in x: choice.append((t,t.capitalize())) Job_ID = models.CharField(primary_key = True, max_length=200, choices=choice, default='key') Group_ID= models.CharField(max_length=200, choices=choice, default='key') Customer_name = models.CharField(max_length=200, choices=choice, default='key') Planned_Duration = models.CharField(max_length=200, choices=choice, default='key') Worker_name = models.CharField(max_length=200, choices=choice, default='key') Job_note = models.CharField(max_length=200, choices=choice, default='key') Customer_tp_name = models.CharField(max_length=200, choices=choice, default='key') AND THIS IS THE MIGRATIONS FILE (DOES NOT MIGRATE CHOICES!!)- from django.db import migrations, models class Migration(migrations.Migration): dependencies = [ ('csvfileapp', '0008_userdata'), ] operations = [ migrations.CreateModel( name='userchoice', fields=[ ('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')), ('Job_ID', models.CharField(default='key', max_length=200)), ('Group_ID', models.CharField(default='key', max_length=200)), ('Customer_name', models.CharField(default='key', max_length=200)), ('Planned_Duration', models.CharField(default='key', max_length=200)), ('Worker_name', models.CharField(default='key', max_length=200)), ('Job_note', models.CharField(default='key', max_length=200)), ('Customer_tp_name', models.CharField(default='key', max_length=200)), ], ), ] PLEASE HELP!! -
Django Treebread admin AttributeError - 'Page' object has no attribute 'page_ptr_id'
Please help. Stuck and confused. Trying to use Django Treebread admin to see the tree structure of Journal objects, which inherits from class Page in wagtail. Page inherits from MP_Node in Treebread. models.py from wagtail.core.models import Page class Journal(Page): body = RichTextField(blank=True) admin.py from django.contrib import admin from treebeard.admin import TreeAdmin from treebeard.forms import movenodeform_factory from .models import Journal class MyAdmin(TreeAdmin): form = movenodeform_factory(Journal) admin.site.register(Journal, MyAdmin) In Django admin, click Jounal and get error msg as below: AttributeError at /admin/journal/journal/ 'Page' object has no attribute 'page_ptr_id' Request Method: GET Request URL: http://127.0.0.1:8000/admin/journal/journal/ Django Version: 2.2.1 Exception Type: AttributeError Exception Value: 'Page' object has no attribute 'page_ptr_id' Exception Location: C:\Users\Freedom\Anaconda3\envs\myvenv\lib\site-packages\django\contrib\admin\views\main.py in url_for_result, line 473 Python Executable: C:\Users\Freedom\Anaconda3\envs\myvenv\python.exe Python Version: 3.7.3 Python Path: ['D:\\Python\\Django\\m4ever', 'C:\\Users\\Freedom\\Anaconda3\\envs\\myvenv\\python37.zip', 'C:\\Users\\Freedom\\Anaconda3\\envs\\myvenv\\DLLs', 'C:\\Users\\Freedom\\Anaconda3\\envs\\myvenv\\lib', 'C:\\Users\\Freedom\\Anaconda3\\envs\\myvenv', 'C:\\Users\\Freedom\\Anaconda3\\envs\\myvenv\\lib\\site-packages'] page_ptr_id is actually the Django auto-generated field name for the one-to-one relation from the specific Journal class to the base Page model. Tried define it explicitly in Journal as: page_ptr_id = models.OneToOneField(Page, on_delete=models.CASCADE, parent_link=True) But still get similar error msg, displaying as 'Page' object has no attribute 'page_ptr_id_id' -
Django: How to prevent form resubmission when form validation unsuccessful?
I have looked into this problem with possible duplication but it seems like mine's a different problem. So I have forms which use sessions to temporarily store data. I have also included {{ form.errors }} in my templates to display the errors upon validation. The problem is, when I try to reload the page () when form is invalid/unsuccessful and the errors were displayed, instead of just refreshing the page and clearing the fields as well as the displayed errors, a confirm form resubmission dialog appears and the errors in my form remained. How should I prevent this dialog from appearing? -
Django customize Admin login page
Would it be possible to just reuse the login page? I just want to add sign up button in the login page. But for what I have searched, it needed to customize all in order to override it. <div class="submit-row"> <input type="submit" value="Log in"> <input type="button" value="Sign up" onclick="location.href='/admin/signup'"> </div> Please help. -
Create login session in django
so i try to make a login with session , so user must logged in first before redirect to another page , so i think im doing right , but i dont know how to check if i save the session or not , here's the code views.py def login_view(request): if request.method == 'POST': form = AuthenticationForm(data=request.POST) if form.is_valid(): username = form.cleaned_data.get('username') password = form.cleaned_data.get('password') guess = User.objects.get(username=username) identity = guess.id table2 = UserProfileInfo.objects.get(user_id=identity) role = table2.role user = authenticate(username=username, password=password) if user is not None: if role == 'Business Analyst': request.session['username'] = username login(request, user) return render(request,'index.html',{"username":username}) elif role == 'Admin': login(request, user) return redirect('/manageuser/') elif role == 'Manager': login(request, user) return redirect('/approvallist/') elif role == 'Segment Manager': login(request, user) return redirect('/approvallist/') else: messages.error(request, "Invalid username or password!") else: messages.error(request, "Invalid username or password!") form = AuthenticationForm() return render(request,"login.html",{"form":form}) def index_view(request): if request.session.has_key('username'): username = request.session['username'] print(username) return render(request, 'index.html',{"username":username}) settings.py INSTALLED_APPS = [ 'polls.apps.PollsConfig', 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', ] MIDDLEWARE = [ 'django.middleware.security.SecurityMiddleware', 'django.contrib.sessions.middleware.SessionMiddleware', 'django.middleware.common.CommonMiddleware', 'django.middleware.csrf.CsrfViewMiddleware', 'django.contrib.auth.middleware.AuthenticationMiddleware', 'django.contrib.messages.middleware.MessageMiddleware', 'django.middleware.clickjacking.XFrameOptionsMiddleware', ] SESSION_ENGINE = "django.contrib.sessions.backends.cache" When i try to print the username , it wont show in command prompt , i thought i already save the request.session['username'] in …