Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Django: "Cannot assign must be a "X" instance", don't want to fetch the object
I have the following view on my Django app and I need to update one object status_id is a ForeignKey field and it has some default values loaded via fixtures def stopObject(request, id_object): object = Object.objects.get(id=id_object) object.status_id = 1 object.save() I'm getting the classical error where I need to assign the object, not its Id. There are countless questions on SO about this problem, but I came looking for an answer I didn't found I know very well I can just perform a fetch from the database and assign to status, but I want to explore other possibilities, even though they may not be the best practices -
Django or FastAPI for an E-commerce website?
I'm planning to build an e-commerce website and I'm torn between choosing FastAPI or Django for the backend. Considering factors like scalability, security, and ease of development, which framework would be better suited for an e-commerce site? Old Django or newer FastAPI I'd appreciate insights or experiences from the community to help make an informed decision. -
Upgraded to Django 4.2, import storages module failed
I recently upgraded Django 4.2 and was applying storage change to my project. Ran into an import error with the storage module. screenshot for my code and the error I double checked the package versions. I tried to re-install the requirements. Both pycharm and mypy threw me the error. I tried to import that module in shell and it worked fine. Does anyone know why this is happening? -
ValidationError doesn't show up in my registration form(Django)
i wrote 2 validation functions in my forms.py but they don't show up in my registration form when i fill fields with wrong data views.py: def register(request): form=RegisterUserForm() if request.method== 'POST': form = RegisterUserForm(request.POST) if form.is_valid(): user=form.save(commit=False) user.set_password(form.cleaned_data['password']) user.save() return render(request, 'user/register_done.html') else: form = RegisterUserForm() return render(request, 'user/register.html',{'form': form} ) forms.py class RegisterUserForm(forms.ModelForm): username = forms.CharField(label='Логин') password = forms.CharField(label='Пароль', widget=forms.PasswordInput()) password2 = forms.CharField(label='Повтор пароля', widget=forms.PasswordInput()) class Meta: model=get_user_model() fields=['username','email','first_name','last_name','password','password2'] labels={ 'email':'E-mail', 'first_name':'Имя', 'last_name':'Фамилия', } def cleaned_password2(self): cd=self.cleaned_data if cd['password']!=cd['password2']: raise forms.ValidationError('Пароли не совпадают!') return cd['password'] def clean_email(self): email = self.cleaned_data['email'] if get_user_model().objects.filter(email=email).exists(): raise forms.ValidationError('Такой адрес уже есть') return email HTML template {% extends 'movieapp/base.html' %} {% block content %} <h1>Регистрация</h1> <form method='post'> {% csrf_token %} {{ form.as_p }} <p><button type="submit">Регистрация</button></p> </form> {% endblock %} urls.py from django.contrib.auth.views import LogoutView from . import views from django.urls import path urlpatterns = [ path('login/',views.LoginUser.as_view(), name='login'), path('logout/',LogoutView.as_view(), name='logout'), path('register/',views.register,name='register') ] I am only learning django and still don't understand why validationerror doesn't show up and return me on the same page when i write wrong password on passwordcheck and the already existing email adress -
Application error after deployed my django project in Heroku
Trying to launch a Django web app on Heroku. Get Application Error: An error occurred in the application and your page could not be served. Please try again in a few moments. If you are the application owner, check your logs for details. heroku logs: PS C:\django24_project\student_info_project> heroku logs --tail 2024-03-22T14:45:16.638981+00:00 app[web.1]: File "", line 488, in _call_with_frames_removed 2024-03-22T14:45:16.638981+00:00 app[web.1]: File "", line 1387, in _gcd_import 2024-03-22T14:45:16.638982+00:00 app[web.1]: File "", line 1360, in _find_and_load 2024-03-22T14:45:16.638982+00:00 app[web.1]: File "", line 1324, in _find_and_load_unlocked 2024-03-22T14:45:16.638982+00:00 app[web.1]: ModuleNotFoundError: No module named 'mysite' 2024-03-22T14:45:16.639044+00:00 app[web.1]: [2024-03-22 14:45:16 +0000] [9] [INFO] Worker exiting (pid: 9) 2024-03-22T14:45:16.644266+00:00 app[web.1]: [2024-03-22 14:45:16 +0000] [10] [INFO] Booting worker with pid: 10 2024-03-22T14:45:16.647216+00:00 app[web.1]: [2024-03-22 14:45:16 +0000] [10] [ERROR] Exception in worker process 2024-03-22T14:45:16.647217+00:00 app[web.1]: Traceback (most recent call last): 2024-03-22T14:45:16.647218+00:00 app[web.1]: File "/app/.heroku/python/lib/python3.12/site-packages/gunicorn/arbiter.py", line 609, in spawn_worker 2024-03-22T14:45:16.647219+00:00 app[web.1]: worker.init_process() 2024-03-22T14:45:16.647219+00:00 app[web.1]: File "/app/.heroku/python/lib/python3.12/site-packages/gunicorn/workers/base.py", line 134, in init_process 2024-03-22T14:45:16.647219+00:00 app[web.1]: self.load_wsgi() 2024-03-22T14:45:16.647219+00:00 app[web.1]: File "/app/.heroku/python/lib/python3.12/site-packages/gunicorn/workers/base.py", line 146, in load_wsgi 2024-03-22T14:45:16.647220+00:00 app[web.1]: self.wsgi = self.app.wsgi() 2024-03-22T14:45:16.647220+00:00 app[web.1]: ^^^^^^^^^^^^^^^ 2024-03-22T14:45:16.647220+00:00 app[web.1]: File "/app/.heroku/python/lib/python3.12/site-packages/gunicorn/app/base.py", line 67, in wsgi 2024-03-22T14:45:16.647220+00:00 app[web.1]: self.callable = self.load() 2024-03-22T14:45:16.647221+00:00 app[web.1]: ^^^^^^^^^^^ 2024-03-22T14:45:16.647221+00:00 app[web.1]: File "/app/.heroku/python/lib/python3.12/site-packages/gunicorn/app/wsgiapp.py", line 58, in load 2024-03-22T14:45:16.647221+00:00 app[web.1]: return self.load_wsgiapp() 2024-03-22T14:45:16.647221+00:00 app[web.1]: ^^^^^^^^^^^^^^^^^^^ 2024-03-22T14:45:16.647221+00:00 … -
How to dynamically change resource class in Django Import-Export admin based on user group?
I am using Django Import-Export library to manage export functionalities in my Django admin interface. I have a requirement where I need to dynamically change the resource class based on the user's group membership. Here's a simplified version of what I am trying to achieve: from import_export.admin import ImportExportModelAdmin from django.contrib import admin from .resources import RawFileDMDResource, RawFileResource class RawFileAdmin(ImportExportModelAdmin): resource_class = RawFileResource [...] def get_resource_class(self, request=None): resource_class = self.resource_class if request is None: user = get_user() else: user = request.user if user.groups.filter(name='DMD ext_users').exists(): resource_class = RawFileDMDResource return resource_class However, the get_resource_class method expects a request argument. It seems that the Import-Export library doesn't provide the request object in the context of this method. Is there a way to access the current user's information or request object within the get_resource_class method without explicitly passing the request object? -
is this a right way to use regular exprissio?
how to use regular expression with python? i searched and write code in my laptop i get the output as i want but on the web site it didn't match in Courser a course python for everybody i tried to solve an assignment but it didn't work on the web site but it worked correctly on my own laptop it's about regular expression. import re fh = open("regex_sum_42.txt") text = fh.read() number_final = re.findall('[0-9]+',text) total = 0 for i in number_final: i = int(i) total = total + i; print(total) print(number_final) fh.close() -
setting async python-telegram-bot(ptb) webhooks using django
setting async python-telegram-bot(ptb) webhooks using django I am using Django==5.0.3 and python-telegram-bot==21.0.1 I have developed several telegram bots using fastapi+uvicorn and ptb but I can't make django work with python telegram bot library. I get timeout error when I include this line: async with application: I am using postman to simulate a telegram request with a post request with a body like this: {"update_id": 400838435, "message": {"message_id": 627, "from": {"id": 357686176, "is_bot": false, "first_name": "-----", "last_name": "---", "username": "----", "language_code": "en"}, "chat": {"id": 357686176, "first_name": "----", "last_name": "------", "username": "----", "type": "private"}, "date": 1711115302, "text": "hi"}} here is my code. I have tested both uvicorn nameoftheproject.asgi:application and python manage.py runserver to run the project but the result is the same from django.shortcuts import render, HttpResponse from django.http import HttpRequest from django.views.decorators.csrf import csrf_exempt from . import botInstance # from handlers.handler_mapping import set_handlers from .handlers.handler_mapping import set_handlers from telegram.ext import MessageHandler, filters, ContextTypes from telegram import Update import json # Create your views here. async def echo(update: Update, context: ContextTypes.DEFAULT_TYPE): await Update.message.reply_text(update.message.text) @csrf_exempt async def say_hello(request: HttpRequest): #print(request) # print(request.body) #print(request.GET) token = "-------A" application = botInstance.get(token) if request.method == 'POST': print(json.loads(request.body)) async with application: pass # await application.start() # # … -
VERCEL Deployment : NotSupportedError at / deterministic=True requires SQLite 3.8.3 or higher
How do i solve this? i visited the sqlite website but is shows only version 3.45.2 version available to download whereas when hosting the website it says version 3.8.3 or higher is required? How do i update my dbsqlite version ? anyone please help and also english is not my first language so please do not use any fancy words I tried to download from the db sqlite but it doesnt show version 3.8.3 so i didnt download it thinking it might cause errors adn also stack over flow what is your problem just let me post this -
Readonly map for GeoDjango fields in Django>=4.0?
I was searching old answers on how to show the dynamic Openlayers map but not allow you to move/change the coordinates/geometry of a given GeoDjango field (a PointField in my case) in the Django Admin. Old solutions mention using the OSMGeoAdmin class (from django.contrib.gis.admin), which allows you to set the modifiable attribute to False to make the map be shown but not modifiable. This is exactly what I want. However, that class is deprecated since Django 4.0, and you are now prompted to use ModelAdmin or GISModelAdmin instead, but none of the two allow me to replicate the same behaviour as OSMGeoAdmin. I searched the documentation for GISModelAdmin and it points that I can send some parameters to the gis_widget using the dictionary gis_widget_kwargs, but the modifiable attribute is still not working, so I am beggining to think that the functionality was removed. Example of code to pass parameters to the gis_widget: @admin.register(m.City) class CityAdmin(GISModelAdmin): gis_widget_kwargs = {'attrs':{'map_width':1200, 'modifiable':False}} Am I missing something? Is that really no longer possible with GISModelAdmin? Do I have to go through the annoying process of creating my own widget to replicate this behaviour? If someone has faced the same situation, did you manage to … -
Background video scaling through the whole page
right now the video is scaling through the whole page, like when I start scrolling it is not fixed on the first page but scales downwards too. I want it to be fixed at the first page of home screen, for example at 1920*1080 resolution for computer users HTML : <div class="home-video"> <video autoplay muted loop id="bg-video"> <source src="{% static 'core/background/background-video.mp4' %}" type="video/mp4"> </video> </div> CSS : .home-video { position: fixed; top: 0; left: 0; width: 100%; height: 100%; overflow: hidden; z-index: -1; } #bg-video { width: auto; height: auto; min-width: 100%; min-height: 100%; position: absolute; top: 50%; left: 50%; transform: translate(-50%, -50%); z-index: -1; } Tell me what I'm doing wrong -
Django: KeyError at /panel/home/login/ 'HTTP_REFERER'
I have a problem to get the HTTP_REFERER address from django. I want to userauth system in two separate login pages and for that, I set in one of login pages if the url that redirected person to this login page had 'business' word, redirect user into business login page. Thanks for Help I wrote this Code: if 'business' in request.META['HTTP_REFERER']: return redirect('panel_business:login_business') Here is My Error: KeyError at /panel/home/login/ 'HTTP_REFERER' Django Error Full Trace: Environment: Request Method: GET Request URL: http://localhost:8009/panel/home/login/?next=/panel/business/ Django Version: 4.2.6 Python Version: 3.8.10 Installed Applications: ['django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'website', 'panel', 'panel_business'] Installed 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'] Traceback (most recent call last): File "/home/arshia/w/recycle/venv/lib/python3.8/site-packages/django/core/handlers/exception.py", line 55, in inner response = get_response(request) File "/home/arshia/w/recycle/venv/lib/python3.8/site-packages/django/core/handlers/base.py", line 197, in _get_response response = wrapped_callback(request, *callback_args, **callback_kwargs) File "/home/arshia/w/recycle/panel/views.py", line 44, in login_home if 'business' in request.META['HTTP_REFERER']: Exception Type: KeyError at /panel/home/login/ Exception Value: 'HTTP_REFERER' -
Advice regarding integrating C# code with django backend
I use C# to convert documents (pdf, docx etc) to other formats (docx, xls, ppt etc) and my backend is written with Python (django) I successfully wrote and loaded a c# dll which let me call it's functions and convert the documents directly from python, using pythonnet clr Issue is, it's slow, like marginally slower (I'd say 20 times slower) than using the same code as if I compiled and ran it as an executable instead of loading it as a dll to python So I need an advice, should I just make the c# code into an executable and then call it via a subprocess with a file path argument (which will force me to write the file into the disk, call the subprocess, which will on turn read the file, and write again, and then the python will read the output file and delete it) or is there alternative? With the dll solution i just pass the file bytes to the dll and don't need to write a file to disk, which would be (for me) a preferable solution, but not at the cost of that big of speed diffrance. Im assuming passing the entire file's contents (bytes) … -
DRF Simple JWT functions RefreshToken.for_user(user) get Attribute error with Custom User Model
I create a custom User Model with usercode is PrimaryKey class User(AbstractBaseUser, PermissionsMixin): usercode = models.CharField(primary_key=True, unique=True, null=False) username = models.CharField(max_length=255, unique=True, null=True, blank=True, default=None) email = models.EmailField(unique=True, null=True, blank=True, default=None) phone_number = models.CharField(max_length=128, unique=False, null=True, blank=True, default=None) password = models.CharField(max_length=256, null=False) ... I replace default TokenObtainPairView serialier of SimpleJWT with and work quite good class CustomTokenObtainPairSerializer(serializers.Serializer): usercode = serializers.CharField(max_length=64) password = serializers.CharField(max_length=255) def validate(self, attrs): usercode = attrs['usercode'].upper() password = attrs['password'] # Get user object for validating user = User.objects.filter(usercode=usercode).first() # Validating login request if user is None: raise AuthenticationFailed(f'User not found!') if not check_password(password, user.password): return Response({'message': 'Wrong password!'}) user_data = UserSerializer(user).data tokens = get_tokens_for_user(user) return {'user': user_data, 'tokens': tokens} class CustomTokenObtainPairView(TokenObtainPairView): serializer_class = CustomTokenObtainPairSerializer def get_tokens_for_user(user): refresh = RefreshToken.for_user(user) return { 'refresh': str(refresh), 'access': str(refresh.access_token), } But when I try to get custom token like source Creating tokens manually I got error at RefreshToken.for_user(user) Errors details: AttributeError at /application/api/v1/2024/token/ 'User' object has no attribute 'id' Request Method: POST Request URL: http://127.0.0.1:8000/application/api/v1/2024/token/ Django Version: 5.0.3 Exception Type: AttributeError Exception Value: 'User' object has no attribute 'id' I checked and got that the RefreshToken.for_user require a User model with id is PrimaryKey File "D:\development\py\DJ_Project\venv\Lib\site-packages\rest_framework_simplejwt\tokens.py", line 203, in for_user user_id … -
Creating database in PostgreSQL following Django installation
Forgive me my indolence, but I was following Django installation based on this manual https://idroot.us/install-django-opensuse/ up until to the point where you need to create new database using createdb mydatabase. I am using OpenSuse Tumbleweed Release 20240320 and I have tried this in Python virtual environment. Now, It is giving an obvious error when using createdb mydatabase: "Connection to server on socket "/run/postgresql/.s.PGSQL.5432" failed: No such file or directory. Is the server running locally and accepting connections on that socket?" So I have checked the following: ps -ef | grep postgres It gives me this: root 12831 27003 0 11:18 pts/0 00:00:02 sudo su - postgres root 12833 12831 0 11:18 pts/1 00:00:00 sudo su - postgres root 12834 12833 0 11:18 pts/1 00:00:00 su - postgres postgres 12835 12834 0 11:18 pts/1 00:00:00 -bash postgres 12956 12835 0 11:21 pts/1 00:00:02 yes root 13133 12835 0 11:24 pts/1 00:00:00 sudo su - postgres root 13135 13133 0 11:24 pts/2 00:00:00 sudo su - postgres root 13136 13135 0 11:24 pts/2 00:00:00 su - postgres postgres 13137 13136 0 11:24 pts/2 00:00:00 -bash postgres 14851 13137 99 11:59 pts/2 00:00:00 ps -ef postgres 14852 13137 0 11:59 pts/2 00:00:00 grep … -
Django Load bootstrap modal only after form validation passes
Am trying to pop up a modal window with the terms & conditions, Only when the user accepts the terms and conditions then the data is submitted to the database. I want to validate user input before the modal pops up. Below is my code. individual_account.html <form method="post" class="bg-white shadow-md rounded px-8 pt-6 pb-8 mb-4" id="individualForm"> {% csrf_token %} {% for hidden_field in form.hidden_fields %} {{ hidden_field.errors }} {{ hidden_field }} {% endfor %} <div class="flex flex-wrap -mx-3 mb-6"> <div class="w-full md:w-1/2 px-3 mb-6 md:mb-0"> <label class="block uppercase tracking-wide text-gray-700 text-xs font-bold mb-2" for="{{form.full_name.id_for_label}}"> {{ form.full_name.label }} </label> {{ form.full_name }} {% if form.full_name.errors %} {% for error in form.full_name.errors %} <p class="text-red-600 text-sm italic pb-2">{{ error }}</p> {% endfor %} {% endif %} </div> <div class="w-full md:w-1/2 px-3"> <label class="block uppercase tracking-wide text-gray-700 text-xs font-bold mb-2" for="{{form.id_passport_no.id_for_label}}"> {{ form.id_passport_no.label}} </label> {{ form.id_passport_no }} {% if form.id_passport_no.errors %} {% for error in form.id_passport_no.errors %} <p class="text-red-600 text-sm italic pb-2">{{ error }}</p> {% endfor %} {% endif %} </div> </div> <!-- Button trigger modal --> <button type="button" class="bg-yellow-700 text-white rounded-none hover:bg-white hover:text-blue-900 hover:border-blue-900 shadow hover:shadow-lg py-2 px-4 border border-gray-900 hover:border-transparent" data-bs-toggle="modal" data-bs-target="#exampleModal"> Create Account </button> <!-- Modal --> <div class="modal fade" … -
Django Template render annotated data along with Model data in UI for Many to Many relationship objects
I am looking for a solution to show a Models data elements along with this annotated data, e.g. I have a TestRun model which has M2M relationship with TestCases, so on the UI page for testruns list page want to show TsetRun data along with the count of testcases grouped by its status. e.g. TestRun.ID = 1, TestRun.Name = Regression Total TCs in TR = 4 Passed TC = 2 | Blocked TC = 1 | Failed TC = 1 along with a table for each run record to show the above 4 testcases like TC_ID|TC_NAME|TC_STATUS| 1 |TC_101 | Passed | 4 |TC_102 | Passed | 5 |TC_105 | Failed | 7 |TC_107 | Blocked | I have following models class TestRun(models.Model): testcases = models.ManyToManyField(TestCase, through="TestRunCases") project = models.ForeignKey(Project, related_name="project_testruns", on_delete=models.PROTECT) name = models.CharField(max_length=255) class TestRunCases(models.Model): testcases = models.ForeignKey(TestCase, on_delete=models.CASCADE) testrun = models.ForeignKey(TestRun, on_delete=models.CASCADE) testcase_status = models.ForeignKey(TestCaseStatus, null=True, default=1, on_delete=models.PROTECT) I want to show the count of test cases for each run with status, e.g. For TestRun.id=1, Total TC#=3,Passed=2, Failed=1, template eg. provided below I tried using following in my views, using CBV def get_context_data(self, **kwargs): context = super().get_context_data(**kwargs) context["testcases"] = ( TestRunCases.objects.filter(testrun_id__in=testrun_qs) .values("testrun_id", "testcase_status__status_value") .annotate(status_count=Count("id")) ) return context And … -
Delete an instance before saving a new one (Django model save method)
I want to limit my model's records to a maximum of 10 rows per user (the model has a foreign key to user model). What is the best practice for that? I thought about overriding save method, perform a check, and delete before saving: def save(self, *args, **kwargs): if MyModel.objects.filter(user=self.user).count() >= 10: oldest_record = MyModel.objects.filter(user=self.user).order_by('created_at').first() oldest_record.delete() super().save(*args, **kwargs) But I wonder if it is a good solution, if it's better (and what's the way to do it) to enforce that at database level, and potential problems when same user saves two instances at the same time (though very unlikely). Any experiences with something similar? -
How to wait until the receive function is not invoked (set the client input in kc.input())?
I am trying to build a Python IDE using the Jupyter client kernel. My problem is: Not being able to provide the client input in the kc.input() that I receive after sending the prompt: : await self.send(text_data=json.dumps({'input_request':mseg["content"]["prompt"]})) need help here if msg["msg_type"] == "execute_input": mseg = kc.get_stdin_msg(timeout=1) await self.send(text_data=json.dumps({'input_request': mseg["content"]["prompt"]})) ***I want it to wait until it doesn't receive input (invoke the receive function)*** print("Stored input:", self.input_received) kc.input(5) I try to declare the kc = BlockingKernelClient() in the class so can use in if i received any input but kernel get stop till then. Full Code import json from channels.generic.websocket import AsyncWebsocketConsumer from jupyter_client import BlockingKernelClient from jupyter_client import KernelManager class CodeExecutionConsumer(AsyncWebsocketConsumer): input_received = '' def __init__(self, *args, **kwargs): super().__init__(*args, **kwargs) async def connect(self): await self.accept() async def disconnect(self, close_code): pass async def receive(self, text_data): await super().receive(text_data) data = json.loads(text_data) code = data.get('code', '') input_text = data.get('input','') if input_text: print("input text:",input_text) await self.handle_input(input_text) else: result = await self.execute_code(code) print(code,result) # await self.send(text_data=json.dumps({'result': result})) async def handle_input(self, input_text): print("Received input:", input_text) self.input_received = input_text async def execute_code(self, code): kc = BlockingKernelClient() kc.load_connection_file(connection_file="./confs/c1.json") kc.start_channels() try: msg_id = kc.execute(code) while True: msg = kc.get_iopub_msg(timeout=1) if msg["msg_type"] == "stream" and msg["content"]["name"] == "stdout": result … -
Improving Django Application Performance: Comparing Blocking and Non-blocking Implementations
I encountered an unexpected error (apr_socket_recv: Connection reset by peer (54)) while load testing my Django application with Apache Benchmark (ab). This error occurs when I increase the load to 50 concurrent requests. Surprisingly, even with 20 concurrent requests, there's no significant performance improvement with non-blocking (Can see same throughput as of blocking) The application consists of two implementations: one using a blocking approach with the default WSGI server and the other utilizing a non-blocking asynchronous approach with ASGI and the Daphne server. The blocking implementation relies on synchronous requests with the requests library, while the non-blocking approach utilizes aiohttp within an asynchronous view function. Both implementations aim to make POST requests to an external API endpoint and return responses. Despite expecting better performance with the asynchronous approach, the error persists and the performance remains stagnant. I'm seeking insights into the root cause of this error and potential solutions to improve performance under heavier loads. Additionally, any advice on optimizing the asynchronous implementation or suggestions for better load-testing strategies would be greatly appreciated I'm using ab as a benchmarking tool. The command which I used for benchmarking: ab -c 50 -n 600 -s 800007 -T application/json "http://127.0.0.1:8001/test" Blocking Code: from … -
Spinner and page reset after views.py completes processing | DJANGO
I have a Django web application where users can generate and download Excel files. To provide feedback to users while the file is being generated, I've implemented a spinner animation using HTML and JavaScript. However, I'm facing difficulty in stopping the spinner animation after the file download is complete. Here's my HTML and JavaScript code for the spinner: <style> .spinner-container { display: none; position: fixed; top: 50%; left: 50%; transform: translate(-50%, -50%); z-index: 9999; } .spinner { width: 50px; height: 50px; border: 5px solid rgba(0, 0, 0, 0.1); border-left-color: #333; border-radius: 50%; animation: spin 1s linear infinite; } @keyframes spin { to { transform: rotate(360deg); } } </style> <button type="submit" onclick="showSpinner()">GENERATE</button> <div id="spinner" class="spinner-container"> <div class="spinner"></div> </div> <script> function showSpinner() { document.getElementById("spinner").style.display = "block"; } function hideSpinner() { document.getElementById("spinner").style.display = "none"; } </script> And here's my Django views.py code for downloading the file: from django.http import HttpResponse import pandas as pd def downloadFile(request): try: # Generate the Excel file with pd.ExcelWriter('NEW-DOWNLOAD.xlsx', engine='openpyxl') as excel_file_path: # Write dataframes to sheets dataframes = { 'SUMMARY': data, 'CHART': CHART } for sheet_name, df in dataframes.items(): df.to_excel(excel_file_path, sheet_name=sheet_name, index=True) # Read the entire file as bytes with open('NEW-DOWNLOAD.xlsx', 'rb') as f: file_data = f.read() … -
no_color in overridden django command does not work
I have overridden django check command in ~/<project_name>/commands/management/commands/check.py looking like this: from django.core.management.commands import check class Command(check.Command): help = 'My Customized Version of the Original check Command' def handle(self, *args, **options): print('>>> Running customized check') options['deploy'] = True options['no_color'] = True super(Command, self).handle(*args, **options) Running manage.py check 2>/tmp/check-output triggers the command, but the problem here is in spite of setting 'no_color', the output is still colored and I have to run it as manage.py check --no-color 2>/tmp/check-output -
Django (REST) backend server hosting using Google Cloud
This is my first time trying to host a backend server to any cloud platform and I am trying to host it using Google Cloud. This is a pet project of mine and the frontend of my webapp is alreday hosted by myself using firebase. My issue is I tried depolying the cloud app for my backend, but I am getting a 500 server error even though the files were uploaded without any issues. Another thing is I am quiet not sure about my file structure. [Backend File Strucutre](https://i.stack.imgur.com/PLAtJ.png) [API folder](https://i.stack.imgur.com/AGGKQ.png) [enchant_ease_backend File](https://i.stack.imgur.com/AQ4hH.png) [My backend folder](https://github.com/ThisalHerath/express-hello-world) I tried removing my requirements.txt file since in the Google cloud app engine dashboard I got few errors with my dependencies but id did not worked out and I spent almsot few hours watching tutorials but nothing worked out. Can someone guide me through the hosting process or tell me what i have done wrong or something that need to be changed? -
Django data is not being stored on Postgres Db
Up until January, my Django app was saving data to this DB but now it is not working. The migrations pass and declare ok on the CLI but it doesn't get saved in the DB. It still works with SQLite3 DB but I get this error { "error": "'NoneType' object has no attribute 'rsplit'" } I did not make any big change to the settings prior to this -
in Django i'm trying to rendering a list of objects from a different models in a class based detail view
I have two models Vendors and Products. Products has a foreign key of vendors. What I'm trying to do is when you go to a detail view of vendor it shows then vendor model information then a list of Products from that vendor. I currently just testing flow and getting to know django so a lot this code is very generic and i know i need to clean it up. Here is my models class Vendor(models.Model): name = models.CharField(max_length=126, unique=True, blank=True, null=True) contact_number = models.CharField(max_length=126, blank=True, null=True) address = models.CharField(max_length=126, blank=True, null=True) email = models.EmailField(max_length=126, blank=True, null=True) is_active = models.BooleanField(default=True) def __str__(self): return self.name def productFilepath(instance, filename): year = datetime.now().strftime("%Y/") return os.path.join(instance.vendors.name, year, filename) class Product(models.Model): vendors = models.ForeignKey(Vendor, on_delete=models.CASCADE) collection = models.CharField(max_length=126, unique=True, blank=True, null=True) product = models.CharField(max_length=126, blank=True, null=True) size = models.CharField(max_length=126, blank=True, null=True) vendor_price = models.DecimalField(max_digits=7, decimal_places=2, blank=True, null=True) retail_price = models.DecimalField(max_digits=7, decimal_places=2, blank=True, null=True) sku = models.CharField(max_length=126, unique=True, blank=True, null=True) year = models.PositiveSmallIntegerField(blank=True, null=True) quarters_in_year = { 'q1': 'Q1', 'q2': 'Q2', 'q3': 'Q3', 'q4': 'Q4', } quarter = models.CharField(max_length=2, choices=quarters_in_year.items(), blank=True, null=True) image = models.FileField(upload_to=productFilepath, blank=True, null=True) here are my views class VendorDetailView(DetailView): model = Vendor template_name = 'deliveries/vendor_detail.html' class Productlist(ListView): model = Product template_name = …