Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
The 'for' loop only one product's attribute in django
I want to calculate the the difference between total product quantity and shopcart product quantity. So I made calculations in my views and applied to templates. The problem is the for loop which I think should loop through all products only loops to the recently added product and give the result to all the products. What did I do wrong? Here is the code: Template {% for rs in products %} <div> <a href="{% url 'addtoshopcart' rs.id %}" class="primary-btn add-to-cart"><i class="fa fa-shopping-cart"></i> Add to Cart</a> </div> <p><strong>Availability:</strong> {% if tot > 0 %} In Stock : {{tot}} Remaining {% else %} Out of Stock {% endif %}</p> {% endfor %} Views def category_products(request,id,slug): current_user = request.user #category = Category.objects.all() setting = Setting.objects.get(pk=1) catdata = Category.objects.get(pk=id) products = Product.objects.filter(category_id=id) context={'products': products, #'category':category, 'setting':setting, 'catdata':catdata } for rs in products: if rs.variant == 'None': checkinproduct = ShopCart.objects.filter(product_id=id, user_id=current_user.id) # Check product in shopcart if checkinproduct: control = 1 # The product is in the cart else: control = 0 # The product is not in the cart""" if control == 1: tot = rs.amount - ShopCart.objects.get(product_id=id, user_id=current_user.id).quantity else: tot = rs.amount context.update({'tot': tot}) else: pass return render(request,'category_products.html',context) -
Django / How to evaluate a django variable inside a bracket expression?
In my html file I need to define a variable for a js file. <script> var gltf_home = "{% static '/3d/ {{ scene.GltfFileToLoad }} ' %}"; </script> which gives as an output : /static/3d/%7B%7B%20scene.GltfFileToLoad%20%7D%7D instead of /static/3d/00-world.glb And this alternative var gltf_home = "{% static '/3d/' {{ scene.GltfFileToLoad }} %}"; gives /static/3d/ What would be the correct way to do it ? -
Djongo migrate models cons
Its's nice to see mongodb is connected with django but doesn't support completely. I explain why so because when you install any third party packages to your project it could written for Django models not Djongo which will fall you in Database error while migrating you apps. djongo.database.DatabaseError Do we have any solution for this case? -
Django: After updating a template, the changes are not reflected upon refreshing the page in the browser
I am testing a class based view in my Django application. I am currently in development, so I want to see changes in the browser as soon as I make any change in a template. The urls.py of the main app is below: urlpatterns = [ path('myapp/', include('myapp.urls')), ] urls.py of myapp: from django.urls import path, include from . import views urlpatterns = [ path('all/', views.AllView.as_view(), name="myapp-all"), ] The views.py file in myapp looks like below: from django.views import View from django.template import loader from django.http import HttpResponse # Create your views here. class AllView(View): template = loader.get_template('myapp/all.html') def get(self, request, *args, **kwargs): return HttpResponse(self.template.render(request=request)) The all.html template looks like below: {% extends 'base.html' %} {% block title %} Example Table {% endblock %} {% block content %} <div class="d-flex justify-content-center"> <div class="col-8"> <table class="table table-striped"> <thead> <tr> <th scope="col">#</th> <th scope="col">First</th> <th scope="col">Last</th> <th scope="col">Handle</th> </tr> </thead> <tbody> <tr> <th scope="row">1</th> <td>Mark</td> <td>Otto</td> <td>@mdo</td> </tr> <tr> <th scope="row">2</th> <td>Jacob</td> <td>Thornton</td> <td>@fat</td> </tr> <tr> <th scope="row">3</th> <td colspan="2">Larry the Bird</td> <td>@twitter</td> </tr> </tbody> </table> </div> </div> {% endblock %} The above template is stored in the below directory: base_directory -> myapp -> templates -> myapp -> all.html The settings.py file … -
How do I filter models from the Django admin sidebar while keeping them on their children's change page form?
I have a setup that looks like this: Because 'Charities' and 'Interventions' aren't meant to be edited except from the Evaluations and Max Impact Fund Grants page, I don't want to show up in the navbar menu. I've been scraping through the bowels of Django looking for a way to do this, and the least hacky way I can find is overwriting the django.contrib.admin.AdminSite.get_app_list function, such that after it's assembled the app_list array, I modify in place the element containing the models to delete the offending two. The two problems with this are 1) it's incredibly hacky and 2) it doesn't actually work - I end up with an empty navbar with the message that I don't have permission to modify any objects (I confirmed that the app_list post-modification had the rest of the elements). I feel like there's probably some trivial approach like 'define the app_navbar_models variable to have an exclude list on one of your admin objects', but I have failed to find such an approach either on StackOverflow or indicated in the Django code. Did I miss something? -
Ho to create serializer for model having foreign keys to access that foreign keys tables data also?
I want to rewrite the following API in a more efficient way using the serializer. In the following API, the user and group are foreign keys. I want to return all matching data of group and user using Serializer. How to design a serializer for this situation. @api_view(['GET']) def get_post(request, group_id, post_type, post_limit): if request.method == 'GET': print('group id = ') print(group_id) # data = GroupPostsModel.objects.filter( # group_id=group_id) & GroupPostsModel.objects.filter(post_type=post_type).order_by('-time_stamp') try: data = GroupPostsModel.objects.filter( group_id=group_id, post_type=post_type).order_by('-time_stamp')[post_limit:post_limit+3] # data = data[0:3] model.objects.filter(book = 'bible') post_arr_obj = [] for post in data: comments_count = GroupPostCommentsModel.objects.filter( post_id=post.id).count() print('post id = '+str(post.id)) post_dict = { 'post_id': str(post.id), 'post_text': str(post.post_text), 'post_type': str(post.post_type), 'image': str(post.image), 'document': str(post.document), 'likes': str(post.likes), 'group_id': str(post.group.id), 'user_id': str(post.user.id), 'time_stamp': str(post.time_stamp), 'profile_pic': str(post.user.profile_pic), 'first_name': str(post.user.first_name), 'last_name': str(post.user.last_name), 'gender': str(post.user.gender), 'comments_count': str(comments_count) } post_arr_obj.append(post_dict) except Exception as e: print('get_post exception : '+str(e)) resp = { 'resp': post_arr_obj } # group_post_serializer = GroupPostsSerializer(data, many=True) return Response(resp) else: return Response({'msg': 'Only GET request allowed..!'}) Relationship One user can join/create many groups One group can have mane posts One user can post many posts UserModel class UserModel(models.Model): first_name = models.CharField(max_length=20) last_name = models.CharField(max_length=20) gender = models.CharField(max_length=6) college_name = models.CharField(max_length=50) user_id = models.CharField(max_length=30,unique = True) user_password = … -
Django admin and normal user seperation
Everytime i logout of the normal user system it also logs me out of admin page. the normal user system is created using the AbstractUserModel provided by django and admin created using createsuperuser command. How do i prevent that from happening. Currently using authentication system provided by django (accounts/login, accounts/logout etc) -
Am trying to launch in Cpanel, but am getting a Module not found error
I'm new to Cpanel and am trying to launch my python Django project, I think I've set up everything correctly but am getting this error: File "/opt/alt/python38/lib64/python3.8/importlib/init.py", line 127, in import_module return _bootstrap._gcd_import(name[level:], package, level) ModuleNotFoundError: No module named '<my_module_name>' [UID:2291][2142962] Child process with pid: 2149437 was killed by signal: 15, core dump: 0 Any help offered would be much appreciated, thanks in advance -
Docker compose 'Address not available'
When I try to run docker-compose django postgres I get this error: could not connect to server: Address not available Is the server running on host "localhost" (::1) and accepting TCP/IP connections on port 8000? My Dockerfile: FROM python:3.8.3-alpine WORKDIR /bewise ENV PYTHONDONTWRITEBYTECODE 1 ENV PYTHONUNBUFFERED 1 RUN apk --no-cache --update-cache add postgresql-libs postgresql-dev libffi-dev openldap-dev unixodbc-dev git RUN pip install --upgrade pip COPY ./requirements.txt . RUN pip install -r requirements.txt COPY . . My docker-compose.yml: version: '3.7' services: web: build: . command: python manage.py runserver 0.0.0.0:8000 volumes: - . :/bewise/ ports: - 8000:8000 env_file: - ./.env.dev depends_on: - db db: image: postgres:12.0-alpine volumes: - postgres_data:/var/lib/postgresql/data/ environment: - POSTGRES_USER=user - POSTGRES_PASSWORD=123123 - POSTGRES_DB=db_01 volumes: postgres_data: Settings.py: DATABASES = { "default": { "ENGINE": os.environ.get("SQL_ENGINE", "django.db.backends.sqlite3"), "NAME": os.environ.get("SQL_DATABASE", os.path.join(BASE_DIR, "db.sqlite3")), "USER": os.environ.get("SQL_USER", "user"), "PASSWORD": os.environ.get("SQL_PASSWORD", "password"), "HOST": os.environ.get("SQL_HOST", "localhost"), "PORT": os.environ.get("SQL_PORT", "5432"), } } .env.dev: DEBUG=1 SECRET_KEY=foo DJANGO_ALLOWED_HOSTS=localhost 127.0.0.1 [::1] SQL_ENGINE=django.db.backends.postgresql SQL_DATABASE=db_01 SQL_USER=user SQL_PASSWORD=123123 SQL_HOST=db SQL_PORT=5432 -
Using forloop.counter to iterate over list in django template
I have a list of objects named chargers_list and on my view I estimate when will the charging be done. List of estimates is the same size and is named eta. I iterate over chargers {% for charger in charger_list %} to display some information about every charger. Inside that loop I want to print estimated time. Simple ETA: {{eta.0|date:'Y-m-d H:i'}} works if I provide the index. But how can I utilize forloop.counter (that's the only way I thought of doing this)? When I simply ETA: {{eta.forloop.counter|date:'Y-m-d H:i'}} it throws an error: Exception Type: TemplateSyntaxError Exception Value: Could not parse some characters: eta|[forloop.counter]||date:'Y-m-d H:i' -
I display a table with ajax in real time and I check some lines which I return in my views
I have this problem in summary: when i fill my input automatically i display an array using ajax , and on the same table I shock a few lines and when I send back to my views through a button I have nothing that is displayed either at the console or the terminal. Js & Ajax enter code here $(document).on("click","#final",function(){ const list_entrepot = getSelectedVals1(); const list_fournisseurs = getSelectedVals(); selection = {list_fournisseurs,list_entrepot}; $.ajax({ async: false, type : "GET", url : 'fournisseur_ajax', data :{ 'csrfmiddlewaretoken': csrf, 'selection':selection, }, success : (res) =>{ console.log(res.data) } }); }); function getSelectedVals(){ var tmp =[]; $("input[name='fournisseur_tab']").each(function() { if ($(this).prop('checked')) { checked = ($(this).val()); tmp.push(checked); } }); var filters = tmp.join(','); console.log(filters) return filters; } -
Django form with dropdown list using Database returns empty fields
I'm discovering Django and I'm trying to develop a simple application. I have three tables in my database : One big table to report all the information to users and 2 tables to create drop down list on my form (but no usage of foreign keys on purpose). I need to have these two tables because statuses and areas need to be editable at all time and need to be written in the same way each time in the main table Action. Here is my model.py : class Status(models.Model): id_status = models.AutoField(db_column='ID_STATUS', primary_key=True) status = models.CharField(db_column='STATUS', max_length=50) def __str__(self): return self.status class Meta: managed = False db_table = 'T_EAVP_STATUS' class Area(models.Model): id_area = models.AutoField(db_column='ID_AREA', primary_key=True) area_name = models.CharField(db_column='AREA_NAME', max_length=50) def __str__(self): return self.area_name class Meta: managed = False db_table = 'T_EAVP_AREA' class Action(models.Model): id = models.AutoField(db_column='ID', primary_key=True) title = models.CharField(db_column='TITLE', max_length=200) due_date = models.DateTimeField(db_column='DUE_DATE') status = models.CharField(db_column='STATUS', max_length=50) date_insert = models.DateTimeField(db_column='DATE_INSERT', auto_now_add=True) emitting_area = models.CharField(db_column='EMITTING_AREA', max_length=50) receiving_area = models.CharField(db_column='RECEIVING_AREA', max_length=50) owner = models.CharField(db_column='OWNER', max_length=200) def __str__(self): return self.title class Meta: managed = False db_table = 'T_EAVP_ACTION' Here is my forms.py : class ActionForm(forms.ModelForm): status = forms.ModelChoiceField(queryset=Status.objects.all()) receiving_area = forms.ModelChoiceField(queryset=Area.objects.all()) emitting_area = forms.ModelChoiceField(queryset=Area.objects.all()) class Meta: model = Action fields = ['title', … -
in Django : Why nothing happens when I try to Create new note with the html form in the notes.html page
I just start my first app with Django by following a video on YouTube.. the app is a students dashboard has 8 tools and features help the student to make note, search for help, save books, etc. So when I follow the steps I get stuck , in the creation of a new note but note from the admin side but from the actual notes template that has a crispy form and a create button. the program supposed to write a title and description(the content of the note) then press the create button. but nothing happened everytime I tried to click (create) #This is the view.py page in the dashboard app : from django.shortcuts import render from . forms import * from django.contrib import messages # Create your views here. def home(request): return render(request, 'dashboard/home.html') def notes(request): if request.method == "POST": form = NotesForm(request.POST) if form.is_valid(): notes = Notes(user=request.user,title=request.POST['title'],description=request.POST['description']) notes.save() messages.success(request,f"Notes Added from {request.user.username} Successfully") else: form = NotesForm() notes = Notes.objects.filter(user=request.user) context = {'notes':notes,'form':form} return render(request,'dashboard/notes.html',context) and this is the notes.html page in the dashboard app > template folder > dashboard folder : {% extends 'dashboard/base.html' %} <!-- Load the static files here --> {% load static %} {% … -
FieldError at /teacher/8/. Cannot resolve keyword 'teacher' into field. Choices are: classroom, faculty, faculty_id, id, name
I reach the error in my django project when I was trying to display my view. The problem seems like related to the Course model but i honestly dont know where to begin with it. My Teacher model: class Teacher(models.Model): GENDER_MALE = 0 GENDER_FEMALE = 1 GENDER_CHOICES = [(GENDER_MALE, 'Male'), (GENDER_FEMALE, 'Female')] fname = models.TextField(max_length=20) lname = models.TextField(max_length=20) gender = models.IntegerField(choices=GENDER_CHOICES) phone = models.IntegerField(default=None, blank=True, null=True) email = models.TextField(max_length=30, default=None, blank=True, null=True) faculty = models.ForeignKey('Faculty', on_delete=models.CASCADE ) def __str__(self): return self.lname + ' ' + self.fname My Course model: class Course(models.Model): name = models.TextField(max_length=50) faculty = models.ForeignKey('Faculty', on_delete=models.CASCADE ) def __str__(self): return f'{self.name}' My view: def teacher(request, teacher_id): teacher = get_object_or_404(Teacher, pk=teacher_id) faculties = Faculty.objects.filter(teacher=teacher) course = Course.objects.filter(teacher=teacher) classrooms = Classroom.objects.filter(teacher=teacher) students = Student.objects.filter(teacher=teacher) # students = [] # for cls in classrooms: # students.extend(Student.objects.filter(classroom=cls)) return render(request, 'polls/teacher.html', {'teacher': teacher,'faculties': faculties, 'courses':course,'classrooms':classrooms, 'students':students}) When i run the website, it point out in my view the code to be stoped at course = Course.objects.filter(teacher=teacher) My template: {% extends "polls/base.html" %} {% block body %} <h2>{{ teacher.fname }} {{ teacher.lname }}</h2> <h3>Faculty</h3> {% if faculties %} {% for faculty in faculties %} <p><a href="{% url 'faculty' faculty.id %}">{{ faculty.name }}</a></p> {% endfor … -
drf_yasg.generators: path component of api base URL http://localhost:8080/ is ignored; use FORCE_SCRIPT_NAME instead
I am using swagger (drf_yasg.generators) with Django and I get the following error message Error message is drf_yasg.generators: path component of api base URL http://localhost:8080/ is ignored; use FORCE_SCRIPT_NAME instead Here is the swagger class SchemaGenerator(OpenAPISchemaGenerator): def get_schema(self, request=None, public=False): schema = super(SchemaGenerator, self).get_schema(request, public) schema.basePath = os.path.join(schema.basePath, "") return schema if env.bool("DJANGO_DEBUG"): schema_view = get_schema_view( openapi.Info( title="API", default_version="v1", description="API endpoints", ), url="http://localhost:8080/", public=True, permission_classes=(permissions.AllowAny,), urlconf="config.urls", generator_class=SchemaGenerator, ) Here is the URL urlpatterns = [ path(settings.ADMIN_URL, admin.site.urls), path("api/", schema_view.with_ui("swagger", cache_timeout=0), name="swagger"), path("algo1/", include("core_functions.algo1.urls")), ] Can someone please help with the error? -
Django form_valid method
In my form's view I wonder what if I don't add product_form.save method in the code below and what if I add that: def form_valid(self, form): product_form = form.save(commit=False) product_form.user = self.request.user product_form.save() # what if I delete this? return super().form_valid(form) -
Django / Create HTMl file from a form
In my Models.py class Scenes(models.Model): name = models.SlugField('Scene name', max_length=60,unique=True) description = models.TextField(blank=True) I have submitted the form in Views.py (simplified version) def add_scenes(request): form = sceneForm(request.POST, request.FILES) if form.is_valid(): return HttpResponseRedirect('add_scenes?submitted=True') return render(request,'scenes3d/add_scenes.html', {'form':form, 'submitted':submitted}) What I would like is : after the form is submitted, a new html is created which would be defined in urls.py with the slug name of my form. path('<str:slug>',views.newpage, name="newpage"), Is it the right way to achieve that ? -
Stuck in urls.py while migrating a website from Python 2 to Python 3
urlpatterns = format_suffix_patterns(urlpatterns, allowed=['json', 'html']) While running manage.py makemigrations, got this error and was stuck in this error for a day . This is the error I received File "C:\Users\DSS-WT\AppData\Local\Programs\Python\Python310\lib\site-packages\rest_framework\urlpatterns.py", line 112, in format_suffix_patterns return apply_suffix_patterns(urlpatterns, suffix_pattern, suffix_required, suffix_route) File "C:\Users\DSS-WT\AppData\Local\Programs\Python\Python310\lib\site-packages\rest_framework\urlpatterns.py", line 59, in apply_suffix_patterns regex = urlpattern.pattern.regex.pattern.rstrip('$').rstrip('/') + suffix_pattern AttributeError: 'tuple' object has no attribute 'pattern' This is my urls.py ( Note: it is shorted because of more than 400 lines) urls.py urlpatterns = [('CyberHealth.views', re_path(r'^$', views.index, name='index'), #==== Role === re_path(r'^getorinsertroleAPI/$', views.getorinsertroleAPI, name='getorinsertroleAPI'), re_path(r'^updateordeleteroleAPI/(?P<pk>[0-9]+)/$', views.updateordeleteroleAPI, name='updateordeleteroleAPI'), #==== Register === re_path(r'^registerUser/$', views.registerUser, name='registerUser'), re_path(r'^registerFBUser/$', views.registerFBUser, name='registerFBUser'), re_path(r'^admin/registerCoach/$', views.registerCoach, name='registerCoach'), #==== Login === re_path(r'^login/$', views.loginMethod, name='loginMethod'), re_path(r'^getUserId/$', views.getUserId, name='getUserId'), ] urlpatterns = format_suffix_patterns(urlpatterns, allowed=['json', 'html']) views.py @csrf_exempt def getHealthyLivingListByUser(request, format=None): if request.method == 'POST': try: request_params=json.loads(request.body) limit=request_params.get('limit') offset=request_params.get('offset') limit=offset+limit tasks = tbl_healthyliving.objects.filter(status=1).order_by('-syndicateid') totalrecords=len(tasks) tasks=tasks[offset:limit] serializer = tbl_healthylivingSerializer(tasks, many=True) return JsonResponse({'Response':'Success','Response_status':1,'totalrecords':totalrecords,'healthyliving':serializer.data}) except Exception as e: return HttpResponse(status=500,content_type="application/json",content=json.dumps({'Response':'Failure','Response_status':'Invalid data provided','Error':e.message})) else: return HttpResponse(status=405,content_type="application/json",content=json.dumps({'Response':'Failure','Response_status':'Method not allowed'})) Kindly help me to solve this issue as soon as possible -
How to add Bearer {JWT} in swagger django?
when I authorize myself in Swagger UI, I have to write "Bearer {then I write JWT} here" How can I add the string "Bearer" automatically before the JWT token in swagger UI? Here is my Swagger Settings: SWAGGER_SETTINGS = { "SECURITY_DEFINITIONS": { "JWT [Bearer {JWT}]": { "name": "Authorization", "type": "apiKey", "in": "header", } }, "USE_SESSION_AUTH": False, } FORCE_SCRIPT_NAME = "/" -
Django: user visits package selection
What is the difference between the following packages: django-visits 0.1.6 (released on Jun 16,2014) and django-user-visit 0.5.1 (released on Sep 29, 2021)? If I simply want to record the number of all visitors in my django application, should I use the latest package django-user-visit? Also, which of the above packages (if any) can also record anonymous visitors in addition to logged users? -
How to django orm object to pydantic list object
i'm using django channels and pydantic how to this django orm object to pydantic response class ExchangeRateSchema(BaseSchema): currency: str sales_rate: str fix_time: datetime created_at: datetime @validator("currency") def validate_currency(cls, v): return v.split()[0] @validator("fix_time") def validate_fix_time(cls, v): return v.strftime("%Y.%m.%d %H:%M") # query_set list(ExchangeRate.objects.filter(*args, **kwargs)) How to this ExchangeRateSchema to list data [ { "currency": "USA1", "sales_rate": "1150.40", "fix_time": "2022.05.06 08:54", "created_at": "2022-05-06T08:55:07.998Z" }, { "currency": "USA2", "sales_rate": "1150.40", "fix_time": "2022.05.06 08:54", "created_at": "2022-05-06T08:55:07.998Z" } ] other using code ExchangeRateSchema ExchangeRate.objects.filter(*args, **kwargs).latest(latest) ExchangeRateSchema(**exchange.dict) { "currency": "USA", "sales_rate": "1150.40", "fix_time": "2022.05.06 08:54", "created_at": "2022-05-06T08:55:07.998Z" } -
How can I make add-to-cart fuctionality in django easily?
How can I make add-to-cart fuctionality in django easily? Hello friends, Currently I'm working on a django ecommerce project. I want users to add items in their shopping cart and then checkout to buy the products but I'm so confused how can I make it easily with only backend (no javascript ). Is it possible? I want my project not to be so much complex. So please tell me how to give add-to-cart funtionality to a django project without javascript and without complexity. please provide me helpful tutorial links for making cart system in django. Thank You! -
Django related_name import object instead of foreigne_key
When I importing my CSV file in db.sqlite3, I don't know how to import foreign_key instead of "Object". This is what I've tried. # import_csv.py (manage.my custom command) import csv from django.core.management.base import BaseCommand from models import Site, Association class Command(BaseCommand): help = "Import Command" def handle(self, *args, **options): with open(_file, newline='') as csvfile: reader = csv.DictReader(csvfile, delimiter=";") for row in reader: localsite, created = Site.objects.get_or_create(name=row["locSite"]) distantsite, created = Site.objects.get_or_create(name=row["disSite"]) csv_line, created = Association.objects.get_or_create( localName=row["Name"], locSite=localsite.id, disSite=distantsite.id, ... ) # models.py class Site(models.Model): name = models.CharField(max_length=5, unique=True, help_text="Site Local") objects = models.Manager() class Association(models.Model): localName = models.CharField(max_length=50, help_text="Nom Local") locSite = models.ForeignKey(Site, null=True, on_delete=models.SET_NULL, related_name='local_site_set') disSite = models.ForeignKey(Site, null=True, on_delete=models.SET_NULL, related_name='distant_site_set') Django Admin panel : add record Thx for help -
How do I Concatenate or Combine the dictionary of same data to One
I have the below set of 7 Dictionaries {'empid':785, 'empname':'Ibrahim', 'date(2022,5,1)':'Unmarked'} {'empid':785, 'empname':'Ibrahim', 'date(2022,5,2)':'Unmarked'} {'empid':785, 'empname':'Ibrahim', 'date(2022,5,3)':'Present'} {'empid':785, 'empname':'Ibrahim', 'date(2022,5,4)':'Unmarked'} {'empid':785, 'empname':'Ibrahim', 'date(2022,5,5)':'Unmarked'} {'empid':785, 'empname':'Ibrahim', 'date(2022,5,6)':'Absent'} {'empid':785, 'empname':'Ibrahim', 'date(2022,5,7)':'Unmarked'} I want to convert into the below format. {'empid':785, 'empname':'Ibrahim', 'date(2022,5,1)':'Unmarked', 'date(2022,5,2)':'Unmarked', 'date(2022,5,3)':'Present', 'date(2022,5,4)':'Unmarked', 'date(2022,5,5)':'Unmarked', 'date(2022,5,6)':'Absent', 'date(2022,5,7)':'Unmarked'} How can i do this? -
How to prevent django admin login and logout sessions from reflecting in actual website?
I'm quite new to django. I've made a website that makes use of user auth for login, logout and registration. Whenever I log into the admin panel, it also gets reflected in the actual website. The admin account gets logged into the website on its own. I know this is the default behaviour of the django auth system, but I want to separate the auth session of admin panel and the actual website. How can I do so? The screenshots below show the thing which I'm talking about. 👇 Here I've logged into the Admin panel. 👇 The Admin account got logged into the website on its own by using the admin session.. I just want that both admin panel and website should have separate auth sessions and shouldn't be linked to each other. The website is hosted online here Thanks in advance!