Django community: Django Q&A RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Django application handling for multiple tabs
I have a django based application integrated with login. When I open the application for the first tab and login, this tab logs out automatically when the application is opened in another tab of the same browser. When the sessions created for each tab is separate, why this logs out the old tabs. And the behaviour is not consistent too. I tried to add the settings SESSION_EXPIRE_AT_BROWSER_CLOSE = True SESSION_SAVE_EVERY_REQUEST = True and this seems to be not working -
Django tables2: Skipping object from queryset possible?
A database table contains a column "body" of type "text". This column contains valid JSON data. Displaying data from this table using django-tables2 should skip objects depending on JSON elements in this text field. This filter is obviously not possible using the usual Django QuerySet mechanisms. Therefore, I want to skip an object before rendering it into the table. Something like "before_render_row()" with the possibility to e.g. "return None" to skip the object. Is there any possibility to do that? Thanks! -
How to Speed Up Aggregation in Django
I have a pretty complex query I am running for a Trial Balance report that gathers current and prior debit and credit amounts and aggregates the Sum. In Django I use the ORM to create the query, and it takes about 5-6 seconds to load. I was figuring this was an ORM thing, and attempted the pure SQL in PGAdmin and the time for the query is the same, I am trying to see how I can improve the speed. Note I have indexes on date_entered, property, and is_voided so this should not be a bottleneck. There are also over a million rows in the table being queried. Here is the SQL: SELECT "accounting_glaccount"."deleted", "accounting_glaccount"."date_entered", "accounting_glaccount"."last_update", "accounting_glaccount"."uuid", "accounting_glaccount"."deleted_by_cascade", "accounting_glaccount"."id", "accounting_glaccount"."account_name", "accounting_glaccount"."account_identifier", "accounting_glaccount"."sortable_account_identifier", "accounting_glaccount"."account_type", "accounting_glaccount"."account_designation", "accounting_glaccount"."balance_type", "accounting_glaccount"."report_type", "accounting_glaccount"."report_designation", "accounting_glaccount"."description", "accounting_glaccount"."last_edited_by_id", "accounting_glaccount"."submitted_by_id", ( SELECT SUM(U0."credit_amount") AS "aggregation" FROM "accounting_generalledger" U0 WHERE ((U0."date_entered")::date >= '2024-02-06'::date AND (U0."date_entered")::date <= '2024-02-06'::date AND U0."property_id" = 20 AND NOT U0."is_voided" AND U0."account_id" = ("accounting_glaccount"."id") AND U0."deleted" IS NULL) GROUP BY U0."account_id" ) AS "current_credit", ( SELECT SUM(U0."debit_amount") AS "aggregation" FROM "accounting_generalledger" U0 WHERE ((U0."date_entered")::date >= '2024-02-06'::date AND (U0."date_entered")::date <= '2024-02-06'::date AND U0."property_id" = 20 AND NOT U0."is_voided" AND U0."account_id" = ("accounting_glaccount"."id") AND U0."deleted" IS NULL) GROUP BY … -
Django model if constructor called with None then set to chosen value
I have: class Scanned(models.Model): time = models.DateTimeField(default=datetime.now(timezone.utc), null=False) and in my unit tests I have instantiations of the form: Scanned(time=None) I would like to have that instantiation set the time value to datetime.now(timezone.utc) I have tried: time = models.DateTimeField(auto_now_add = True) and time = models.DateTimeField(auto_now = True) I also looked at validators but could not find a way to pass datetime.now() as the value if None. -
LOGOUT_REDIRECT_URL doesn't redirect to the desired page
I'm new to Django and run to the problem that I want to logout from an account by one click using 'django.contrib.auth.urls'. Here is my 'urls.py' path("accounts/", include('django.contrib.auth.urls')), home.html {% if user.is_authenticated %} <p>Hi, {{ user.username }}</p> <p><a href="{% url 'logout' %}">Log out</a></p> {% else %} <p>You are not logged in</p> <p><a href="{% url 'login' %}">Log In</a></p> {% endif %} settings.py LOGOUT_REDIRECT_URL = "home" LOGIN_REDIRECT_URL = "home" I know that by default I should be redirected to /accounts/logout, when I click on href link, but I set LOGOUT_REDIRECT_URL to home. LOGIN_REDIRECT_URL = "home" on the other hand works perfectly I read a lot of topics on this problem but none of the solutions helped me I tried setting path manually. It worked in a sense that it I stayed at the same page, but I didn't log out from my account path('', auth_views.LogoutView.as_view(next_page=settings.LOGOUT_REDIRECT_URL), name='logout'), -
Why in Django the post method considers an empty form and returns the code 200?
When the blank form is sent. Instead of skipping the conditions and rendering the same form. Instead, it returns an empty form and gives code 200 class ContactView(View): def get(self, request): form = ContactModelForm() return render(request, 'contact/contact_us.html', {'forms': form}) def post(self, request): if request.method == 'POST': form = ContactModelForm(request.POST) if form.is_valid(): form.save() return redirect('home') form = ContactModelForm() return render(request, 'contact/contact_us.html', {'forms': form}) -
How to allow public url access to Ubuntu Server installed in windows 10 as subsystem and using Ngnix with a Python Django & VueJS app
I have successfully installed Ubuntu 22.04.6 on Windows 10 as a subsystem. I have an app which runs with Python, Django, VueJS, Postgres using Nodejs. I am using Ngnix Web Server and am able to get the "Welcome to Nginx!" message. I have managed to get the app running on local ip http://127.0.0.1:8000. I am stuck at getting the app running using the public ip for remote access. I don't have a domain name. I am hoping to use my Windows 10 PC as a web server till the time the app gets completely tested and functional. I have followed steps as shown in: https://www.digitalocean.com/community/tutorials/how-to-set-up-django-with-postgres-nginx-and-gunicorn-on-ubuntu-20-04 The connection code is as below: /etc/systemd/system/gunicorn.socket: [Unit] Description=gunicorn socket [Socket] ListenStream=/run/gunicorn.sock [Install] WantedBy=sockets.target /etc/systemd/system/gunicorn.service: [Unit] Description=gunicorn daemon Requires=gunicorn.socket After=network.target [Service] User=bitrun Group=www-data WorkingDirectory=/home/bitrun/SAFE_ERP ExecStart=/home/bitrun/SAFE_ERP/env/bin/gunicorn \ --access-logfile - \ --workers 3 \ --bind unix:/run/gunicorn.sock \ SAFE_ERP.wsgi:application [Install] WantedBy=multi-user.target /etc/nginx/sites-available/SAFE_ERP: server { listen 80; server_name 103.122.201.91; location = /static/favicon.ico { access_log off; log_not_found off; } location /static/ { root /home/bitrun/SAFE_ERP; } location / { include proxy_params; proxy_pass http://unix:/run/gunicorn.sock; } } ufw status: To Action From -- ------ ---- 80/tcp ALLOW Anywhere 80 ALLOW Anywhere 443 ALLOW Anywhere 8000/tcp ALLOW Anywhere Nginx Full ALLOW Anywhere 8000 ALLOW … -
How To Get Netbox Plug-in Specific Filterset Values?
I’m building a Netbox plug-in, and have a filter form that looks the way that I want. But I want to give the user drop down options for each of the fields with the specific options that are available, and am unsure how to restrict the options to specific fields. I found a way to show options via drop-down, but it doesn’t show the options specific for that field. It works so that if there are 20 fields for value D, but 30 total values (10 aren’t present), how would I build the filterset to only get those 20 values? What about if they are foreign keys? -
How to return only one value in the field and not all the values in the django table?
I want only one representative of each telegram to be shown, and not all the tuples Where it is marked all the values from the messega bot table appear, if you have 50 tuples from the same Telegram group then you would have 50 options for you to choose from. How do you ensure there is only one representative? Example: 5X Group x, id =1; 10X Group y, id =2; but only one of each appears: Group x, id =1; Group y, id =2; code: class MessageBot(models.Model): chat_id = models.BigIntegerField() chat_group = models.CharField(max_length=30) first_name = models.CharField(max_length=30) last_name = models.CharField(max_length=60) date = models.DateTimeField(auto_now_add=True) messageUser = models.TextField() self.client = client super().save(*args, **kwargs) def __str__(self): return f"{self.chat_id} - {self.chat_group}" class MainGroup(models.Model): client = models.ForeignKey(Client, on_delete= models.CASCADE) telegram = models.ForeignKey('MessageBot', on_delete= models.CASCADE, null=False) def __str__(self): return f"{self.telegram}" -
nginx blocks outgoing requests
The situation: I launched django and nginx via docker-compose on ubuntu vps hosting. nginx supports ports 80 and 443. The project opens by domain and redirects to https. Problem: Endpoints that send requests to other servers (to remote APIs) do not work. After sending, there is always a waiting timeout. Here are some settings: #nginx.conf user nginx; worker_processes 1; events { worker_connections 1024; } http { upstream app { server backend:8000; } server { listen 80; server_name eternitydigital.ru; return 301 https://$host$request_uri; } server { listen 443 ssl; server_name eternitydigital.ru; ssl_certificate /etc/nginx/ssl/certs/cert.crt; ssl_certificate_key /etc/nginx/ssl/private/private.key; location / { proxy_pass http://backend:8000; } } } #Dockerfile nginx FROM nginx:1.10.2 COPY nginx.conf /etc/nginx/nginx.conf CMD ["nginx", "-g", "daemon off;"] #docker-compose version: '3.4' services: django_app: build: ./django ports: - "8000:8000" image: backend container_name: backend nginx: build: ./nginx volumes: - ./nginx/ssl/cert.crt:/etc/nginx/ssl/certs/cert.crt - ./nginx/ssl/private.key:/etc/nginx/ssl/private/private.key ports: - "80:80" - "443:443" depends_on: - django_app image: nginx container_name: nginx P.S. At first there were more settings, but I have not been able to fix the problem for 2 days, so I removed a lot of things to at least make it work What did you find out: requests/responses are successful directly from the system via curl I raised the same docker-compose on … -
dynamic block branding on django admin start page
I want to customize the admin home screen. I tried overwriting templates/admin/base.html like this: {% extends "admin/base.html" %} {% load static %} {% block extrahead %} TEST #1 {% endblock %} {% block branding %} TEST #2 {{ block.super }} {% endblock %} like suggested in the docs but while TEST #1 works, TEST #2 does not show up on the admin home page. First question: Why can I not overwrite my branding block, or is this simply the wrong block? Second question: I wish to show information on the main page that comes from the backend - let's for simplicity just say the output of timezone.now() - can this be done using a normal view in the admin? -
How to register a Django model for a specific database only
I am building a DJango multi-tenant web app that separates the tenants by giving them each their database. The app identifies the source and destination of the requests by checking the hostname. The localhost is the default tenant(me) using the default database and the subdomains from that are the tenants using their databases. There is a model Tenants that I am using to create tenants and store their data. I want it to be only registered in the default database so that only I can edit it from the localhost admin but the tenant's admin can't. I tried this and the only output was: ------------------------------TenantAdmin------------------------------ admin.py from django.contrib import admin from .models import Tenant from .utils import hostname_from_the_request # Register your models here. class TenantAdmin(admin.ModelAdmin): print("------------------------------TenantAdmin------------------------------") def get_form(self, request, obj=None, **kwargs): # Get the hostname from the request current_hostname = hostname_from_the_request(request) print("------------------------------Current hostname B4------------------------------", current_hostname) # Check if the hostname is 'localhost' if current_hostname == 'localhost': return super().get_form(request, obj, **kwargs) else: print("------------------------------Current hostname------------------------------", current_hostname) return None # Returning None effectively hides the model in the admin # Register the Tenant model with the custom admin class admin.site.register(Tenant, TenantAdmin) So I also tried interfering with the migrations in the routers: routers.py … -
csrfmiddlewaretoken included in the search url query
The problem is I have 2 searches, one is a search for job seekers to find jobs and another is a search for companies to find job seekers. The expected result is to have http://localhost:8000/search-job-seeker/?&q=searchquery but what I'm getting is http://localhost:8000/search-job-seeker/?csrfmiddlewaretoken=pF6HWEH2rOTvZTRsXzaDuQ9GiGw9ChmukeCYUSND15gzFPCKWmRtRGvVecMHIWKK&q=searchquery I don't see any error messages when I debug in the console or in the terminal. I've tried to use get in the form which results in the http://localhost:8000/search-job-seeker/?csrfmiddlewaretoken=pF6HWEH2rOTvZTRsXzaDuQ9GiGw9ChmukeCYUSND15gzFPCKWmRtRGvVecMHIWKK&q=searchquery but when I use post method in the form, I get http://localhost:8000/search-job-seeker/ and the search result comes out with out the q=searchquery in the url. My view for this is: class JobSeekerSearchView(LoginRequiredMixin, View): template_name = "core/job_seeker_search.html" form_class = JobSeekerSearchForm def post(self, request, *args, **kwargs): """ Handle HTTP POST requests, process form data, search for job seekers, and render the template. Args: self: the instance of the class request: the HTTP request object *args: variable length argument list **kwargs: variable length keyword argument list Returns: HTTP response object """ form = self.form_class(request.POST) job_seeker_results = [] if form.is_valid(): query = form.cleaned_data["q"] # Search for job seekers using PostgreSQL full-text search and icontains job_seeker_results = Seeker.objects.annotate( search=SearchVector("seekerprofile__pk", "seekerprofile__headline"), ).filter( Q(search=SearchQuery(query)) | Q(seekerprofile__skills__icontains=query) | Q(seekerprofile__rate__icontains=query) ) context = {"query": query, "job_seeker_results": job_seeker_results, "form": form} … -
OneToOneField, unique and inheritance in Django
I would like to have a relationship with the User model and one of some different (but related) models, but this must be with only one of the available models e.g. different kinds of subscriptions but a User can only have one related. I know I can solve this with a lot of custom checks but I want to know if there is a recommended or simple solution. If I use inheritance and define a base model, let's put "BaseModel" with a OneToOneField to User, and from this model, they will inherit several: ModelA and ModelB, class ModelBase(models.Model): user = models.OneToOneField(User, on_delete=models.CASCADE, related_name="model_base") class Meta: abstract = True class ModelA(ModelBase): pass class ModelB(ModelBase): pass Django shows this error Reverse accessor 'User.model_base' for 'models.ModelA.user' clashes with reverse accessor for 'models.ModelB.user'. I understand that defining a different related_name in submodels solves this, but this does not maintain the "unique" condition. What would be the best solution for this problem? Could I avoid using GenericForeignKeys? Thank you! -
ImproperlyConfigured at /admin/login/ Can't login to django admin after creating a super user with a custom user model
I'am trying to logging into the django admin panel with a superuser I have successfully created but evrytimes it gives me the ImproperlyConfigured at /admin/login/ saying that settings.DATABASES is improperly configured but I have check everything and nothing seems wrong the thing is that I'am also using multiple database with postgresql so the supersuer created is my user_account app, only this is the code of : the models.py of my user_account app: from django.db import models from django.contrib.auth.models import AbstractBaseUser, PermissionsMixin, BaseUserManager from django.core.validators import validate_email from django.utils.translation import gettext_lazy as _ from django.core.exceptions import ValidationError # Create your models here. class UserAccountManager(BaseUserManager): def email_validator(self,email): try: validate_email(email) except ValidationError: raise ValueError(_("please enter a valid email address")) def create_user(self, email, name, phone_number, password=None): if email: email=self.normalize_email(email) self.email_validator(email) else: raise ValueError(_("an email address is required")) if not name: raise ValueError(_("first name is required")) if not phone_number: raise ValueError(_("phone number is required")) user = self.model(email=email, name=name, phone_number=phone_number) user.set_password(password) user.save(using=self._db) return user def create_member(self, email, name, phone_number, password=None): user = self.create_user(email, name, phone_number,password) user.is_member = True user.is_staff = True user.is_superuser = False user.save(using=self._db) return user def create_superuser(self, email, name, phone_number, password=None): user = self.create_user(email, name, phone_number, password) user.is_member = True user.is_staff = True user.is_superuser … -
Maintaining Conversation Context in Django API View with OpenAI GPT for Chat Application
I am building a chat application using Django that integrates with OpenAI's GPT to generate responses based on the conversation history. I've set up an APIView in Django to handle the chat interactions but am struggling with maintaining and sending the previous conversation context to the OpenAI API for generating contextually relevant responses. Current Implementation: Here's the simplified version of my ChatGptApiView: class ChatGptApiView(APIView): # permission_classes =[IsAuthenticated] def get(self, request): return render(request, 'gpt/gpt.html') def post(self, request): if request.method == 'POST': data = request.data conversation_history = [] user_prompt = data.get('user_prompt') # assistant_prompt = data.get('assistant_prompt') profile_id = data.get('profile_id') user_id = request.user.id regenerate = data.get('regenerate', False) try: profile_data = Profile.objects.get(id=profile_id) except Profile.DoesNotExist: return error_response(error_message="Profile not found", status=status.HTTP_400_BAD_REQUEST) user_input = None if user_prompt is not None: user_input = {"role": "user", "content": user_prompt} conversation_history.append(user_input) save_chat_to_mongodb(profile_data, user_input, user_id, regenerate) recent_chats = get_recent_chats(int(profile_id)) # print("recent_chats",recent_chats,"::::") old_chats = recent_chats.get('chat', []) if 'chat' in recent_chats else [] old_chats = [{k: v for k, v in item.items() if k != 'created_at'} for item in old_chats] if len(old_chats) > 0: conversation_history.extend(old_chats) print(conversation_history, "================================================================") # Define a generator function to stream the response def generate_response(context, message, profile_name): print(conversation_history,"::::::::") if profile_name is not None: context.append({ 'role': 'user', 'content':f"You will follow the current conversation … -
Python - Django BASE_DIR is not populating completely
I am facing a strange issue with django BASE_DIR . My codebase base directory is apisetup. When i am using BASE_DIR for linking css and js files with the help of "static". But those are not working in production. When i see console , it is giving 404 errors for css and js files. the base directory is not reflecting completely. LAST LETTER is missing in the base path. eg : *****.com/apisetu/static/js/bootstrap.bundle.min.js , but it should be apisetup settings.py file BASE_DIR = Path(file).resolve().parent.parent In local it is working fine but creating issue in hosting server. Please help me out to understand the issue and resolution. Thanks in advance. -
Django- form submitting to the same view and not to desired view
My form stopped submitting to the desired view, and submitting to its own view instead. URLS.PY: path('validate_registration', views.validate_registration,name='validate_registration'), VIEWS.PY: def user_registration(request): print("in reg") # populate form form = register_form(request.POST) print("anonymous form") template = loader.get_template('registration.html') return HttpResponse(template.render({'form':form}, request)) def validate_registration(request): if request.POST: print("validating") #populate form form = register_form(request.POST) return render(request, 'val_reg.html', {}) TEMPLATS.HTML: <form class="text-warning text-center rounded pt-2 ps-2 pe-2" method="POST" action="{% url 'validate_registration' %}" > {% csrf_token %} {{form.as_p}} <br/> <button type="submit" class="btn btn-warning mt-5">Register</button> <br/> <br/> </form> The form was working, but after change to the views.py it stopped, which made me shorten its code to few lines only. Even the print "in reg" line doesn't work. Any help please ? -
Django, checkbox add goods to cart with size that user choose by click checkbox
Good day to all. Please don't judge strictly, I'm just learning. I started learning Django and everything seemed to be going smoothly until I ran into the problem of adding an item to the cart along with the size. There is no problem adding the product itself, but I need the user to select the size through a checkbox and after clicking on the “add to cart” button, not just a product will be added to it, but with the desired selected size. Here are the product models, sizes and carts class Product(models.Model): article = models.CharField(max_length=12,null=False,blank=False,unique=True,primary_key=True) img = models.ImageField(upload_to='products_images') price = models.DecimalField(max_digits=9,decimal_places=2) description = models.TextField(null=True,blank=True) gender = models.CharField(max_length=12,null=False,blank=False) is_child = models.BooleanField(null=False) season = models.CharField(max_length=12,null=False) color = models.CharField(max_length=24,null=False) sizes = models.ForeignKey(to='Size',on_delete=models.CASCADE,to_field='article') def __str__(self): return f"{self.article}" class Size(models.Model): article = models.CharField(max_length=12,null=False,unique=True) article_size = models.ForeignKey(to='ArticleSize',on_delete=models.CASCADE,to_field='article_size') def __str__(self): return f"{self.article}" class ArticleSize(models.Model): article_size = models.CharField(max_length=12, null=False, unique=True) size_name = models.CharField(max_length=12,null=False,blank=False) qty = models.SmallIntegerField() to_article = models.CharField(max_length=12, null=False) def __str__(self): return f"{self.article_size}" class Basket(models.Model): user = models.ForeignKey(to=User, on_delete=models.CASCADE) product = models.ForeignKey(to=Product, on_delete=models.CASCADE,to_field='article') size = models.ForeignKey(to=ArticleSize,on_delete=models.CASCADE,to_field='article_size') qty = models.PositiveSmallIntegerField(default=0) create_time_stamp = models.DateTimeField(auto_now_add=True) def __str__(self): return f"Корзина для {self.user.email} товар {self.product.article},размер {self.size.size_name}" Here is the form model: class CheckboxForm(forms.Form): checkbox_size = forms.CharField(widget=forms.CheckboxInput(attrs={ 'class':'size_checkbox', 'type':'checkbox', 'name':'size_checkbox'}),required=True) class Meta: … -
Django: Application redirects to login page again and again and not to home page in local network
I have created a Django application and hosted on local network. when I use http://localhost:8000/klo/ it redirects to the login page and after successful login, it redirects to the home page http://localhost:8000/klo/home/. Same behaviour is observed with local host IP:127/0.0.1:8000. However when I use the IP addr (172.xx.xx.xx:8000/klo) to connect to the app, login page appears but even after entering the correct credentials the redirect to home page not working but login appears again and again. But the url shown with next value (http://172.xx.xx.xx:8000/accounts/login/?next=/klo/home/) settings.py includes ALLOWED_HOSTS = ['*'] LOGIN_REDIRECT_URL = 'klo-home' project level - urls.py includes path('klo/', include('users.urls')), application name - users users application level - urls.py includes path('home/', views.klo_home, name="klo-home"), users application level - views.py @login_required(login_url="/accounts/login/") def klo_home(request): return render(request, 'registration/klo_home.html') Need to know what stops the app from redirecting to klo-home page after valid login only when using IP addr (http://<ip_addr:8000/klo/>) for accessing the app. -
Fuzzy Logic numpy in Django
I'm making website for web survey project. I have fuzzy logic python program and I want to try it to implement it to Django, but I don't know how to connect it to django. This is my model, though (Idk how to post code here) Class Survey (title) Class Question (fk Class Survey; question) Class Answer (fk Class Answer, answer) Class Fuzzy (fk Class Answer, fk User, output1, output2, output3, output4, output5, output6, output7, output8) I want to gain jawaban (answer) as the input of fuzzy logic. I've planned to having 16 inputs and 8 outputs like this : (example of one of the outputs) Input1 = Answer1 Input2 = Answer2 Outputs = Input1 and Input2 Is there anything that I have to prepare like models, views, urls, etc? I'm still beginner towards Django. Help will be appreciated, thanks :) I tried many times, though, but I don't know. I want to post code here, but it always error. -
Python: Get all data from database and write csv
I want to get all data from database and write a csv. But I can't get data by using this user.lrn (for example). But if I try to remove the lrn and just use user, I only got all lrn. I don't know how to call the other field. Below is my code for the write csv function. views.py def exportStudentList(request): user = Student.objects.all() data = [user.lrn, user.lastname] # data = [user] field = ['LRN', 'Last Name'] response = HttpResponse(content_type='text/csv') response['Content-Disposition'] = 'attachment; filename="Students.csv"' writer = csv.writer(response) writer.writerow(field) # Header writer.writerows(data) # Rows return response Your help is greatly appreciated! -
Problem with transferring/receiving an Excel file from the backend(django_v1.9.11) to the frontend(angularjs)
On the front end there is a table and a button to export to Excel. When you click on it, you need to send ajax to the backend, generate an Excel file and transfer it to the frontend in order to download it through the browser to disk. Backend (django v1.9.11) from openpyxl import Workbook from django.http import HttpResponse def send_xl(self, request): wb = Workbook() sheet = wb.active # this is test data. real data is hidden sheet['A1'] = 'Hello world!' sheet['B1'] = 'Excel with Django.' response = HttpResponse(content_type='application/vnd.openxmlformats- officedocument.spreadsheetml.sheet') response['Content-Disposition'] = 'attachment; filename=my_excel_file.xlsx' wb.save(response) return response HTML element Export Frontend (angularjs) $scope.downloadExcel = function(){ $.get("", {action:"send_xl", col: $scope.col, sortDirection: $scope.sortDirection }). then(function (response){ let blob = new Blob([response], { type: 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet' }); let url = URL.createObjectURL(blob); let a = document.createElement('a'); document.body.appendChild(a); a.href = url; a.download = 'filename.xlsx'; a.click(); window.URL.revokeObjectURL(url); } I expect that when the button is clicked, the browser will download a file that can be opened through Excel. The file is downloading, but Excel gives an error: (I open it via LibreOffice) "The file 'filename.xlsx' is corrupt and therefore cannot be opened. LibreOffice can try to repair the file. The corruption could be the result of document … -
Django Djoser not working in production return 405 using react as frontend
In my application, I'm using Django as my backend and react JS for frontend. I'm using Django Djoser for my user activation and reset password. Locally, everything works fine. After creating new user, activation link will be sent to the user email http://127.0.0.1/activate/MjE1/c1vk2z-0cf8bc5d2484ddd32001844b53da1900 If i'm using my domain https://workmatch.rickykristianbutarbutar.com/activate/MjE1/c1vk2z-0cf8bc5d2484ddd32001844b53da1900 then 405 comes out after clicking this link, it will navigate to the frontend activation page, then user click "Activate" const sendActivationConfirmation = async () => { setButtonLabel("Activating ..."); try { let response = await fetch(`/auth/users/activation/`, { method: "POST", headers: { "Content-Type": "application/json", }, body: JSON.stringify({ uid: uid, token: token }) }); if (response.ok) { setAlert({ success: "Your account has been activated. We'll redirect you to the login page in 5 seconds.", }); activationSuccess.current = true; } else if (response.status === 403) { let data = await response.json(); setAlert({ error: data.error }); } else if (response.status === 400) { setAlert({ error: "Bad Request, user may have been accidentally deleted." }); } } catch (error) { if (error.name === "SyntaxError" && error.message.includes("Unexpected end of JSON input")) { console.error("Truncated data: Not all of the JSON data was received"); } else { console.error(error); } } finally { setButtonLabel("Activate"); } }; this code will be … -
Jazzmin sidebar and navbar not hidden on custom login page in Django admin
I'm working on a Django project where I'm using the Jazzmin package to customize the Django admin interface. I've created a custom login page (custom_login.html) for the admin interface, and I want to hide the sidebar and navbar on this page. However, even after ensuring that the {% block nav-global %} and {% block nav-sidebar %} blocks are empty in my custom login template, and that the Jazzmin CSS and JavaScript files are not included on the login page, the sidebar and navbar are still showing up. I've tried several approaches, including selectively including the Jazzmin files, overriding the base template to conditionally include the Jazzmin files, and removing custom CSS and JavaScript from my custom login template. However, none of these solutions have worked so far. I've also inspected the HTML of the custom login page using my browser's developer tools and checked for JavaScript errors in the console, but I couldn't find any obvious issues. Here are the relevant parts of my code: custom_login.html {% extends "admin/base_site.html" %} {% load i18n static %} {% block extrastyle %} {{ block.super }} <link rel="stylesheet" href="{% static "admin/css/login.css" %}"> <style> .login #id_tenant { height: 2.5rem !important; padding: 8px; width: 100%; } …