Django community: Django Q&A RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Error in connecting websockets when i push the code to server
I have implemented the Django Channel for the real time messages between Group users. It is working fine on the local system but when i push this to server, I am getting the error WebSocket connection to 'ws://nailsent.developmentrecords.com/ws/chat/13/' failed: Error during WebSocket handshake: Unexpected response code: 404 (anonymous) @ 13:465 This is my script <script> const currentDate = new Date(); // Get the month abbreviation const month = new Intl.DateTimeFormat('en-US', { month: 'short' }).format(currentDate); const day = currentDate.getDate(); const year = currentDate.getFullYear(); let hours = currentDate.getHours(); const ampm = hours >= 12 ? 'p.m.' : 'a.m.'; hours = hours % 12 || 12; // Convert 24-hour to 12-hour format // Get the minutes const minutes = currentDate.getMinutes(); // Combine all parts into the desired format const formattedTime = `${month}. ${day}, ${year}, ${hours}:${minutes} ${ampm}`; const card = document.querySelector('.card-body'); const sendMessageInput = document.getElementById('sendMessageInput'); const sendButton = document.getElementById('sendButton'); const group_id = "{{ group_id }}"; const userImg = "{{user_image}}" const username = "{{request.user.username}}"; const chatSocket = new WebSocket(`wss://${window.location.host}/ws/chat/${group_id}/`); chatSocket.onopen = function (event) { console.log('WebSocket connection established.'); }; document.addEventListener("keydown", (e)=>{ if (e.keyCode === 13){ sendMessage(); } }) // Event listener for send button click sendButton.addEventListener('click', sendMessage); scrollToBottom(); // Event listener for incoming messages if ("Notification" … -
How to run Django api's asynchronously
I have a long-running API in Django. When this long-running API is invoked by user1, the other APIs get blocked for user1 until that long-running API call gets resolved. But at the same time for other users, those APIs work well. class CreateOrderAPIView(APIView): def post(self, request): # Creates order # Some third-party services are invoked (Takes so long) return Response(order_data, status=201) Example Now, when the above API is called by user1, the other API calls get blocked for user1 until the long-running call is completed. However, the other users can invoke the APIs at the same time. I don't want to go with the celery/redis approach for my long-running tasks for now. Is there a way to resolve this issue? -
CSFR error when trying to use the django function send_email
I'm trying to send an email from Django running on AWSAppRunner resource. I know the email is the error since I have been testing it with and without it. It works when I comment the send_email function, and it does not work when I uncomment that function. I get a CSFR Error " Forbidden (403) CSRF verification failed. Request aborted. Help Reason given for failure: Origin checking failed - null does not match any trusted origins. In general, this can occur when there is a genuine Cross Site Request Forgery, or when Django’s CSRF mechanism has not been used correctly. For POST forms, you need to ensure: Your browser is accepting cookies. The view function passes a request to the template’s render method. In the template, there is a {% csrf_token %} template tag inside each POST form that targets an internal URL. If you are not using CsrfViewMiddleware, then you must use csrf_protect on any views that use the csrf_token template tag, as well as those that accept the POST data. The form has a valid CSRF token. After logging in another browser tab or hitting the back button after a login, you may need to reload the page … -
guide me with learning Django 2024 version with resources
Certainly! Here's a suggestion you can post on Stack Overflow: "I've been following a 2023 Django tutorial series on YouTube but encountered persistent errors despite trying various troubleshooting methods. Could anyone recommend comprehensive learning resources or provide a roadmap for mastering Django? Any assistance would be greatly appreciated." -
launch.json unit-tests Django
I have made tests in Django, and configured launch.json to run from in vscode, but when I make an error in the tests, I get a red error warning. I would like to have an error in the tests, logging only in the console, as it happens in PyCharm, can this be done? My launch.json "version": "0.2.0", "configurations": [ { "name": "Python Debugger: Django", "type": "debugpy", "request": "launch", "program": "${workspaceFolder}\\manage.py", "args": [ "runserver" ], "django": true }, { "name": "Cats Tests", "type": "debugpy", "request": "launch", "program": "${workspaceFolder}\\manage.py", "args": [ "test", "cats.tests" ], "django": true, } ] I also ran into the problem that my launch.json "type": "debugpy", kinda has "python", but when I write it, vscode says return as it was -
creating a virtual environment and file part onvscode
pipenv install django is not creating a virtual environment for me ,i am trying to create a virtual environment via my cmd on my windows , with the command "pipenv intall django", it install django but dont create the enironment , what should i do? and my file part seem not to be working pipenv intall django was supposed to download django and create an environment but it didnt ..... and copying and pasting a file part on my vscode it says invalid interpreter ....commmand used was "pipenv --venv..." got the file part and append bin\python but it didnt work -
Django / DRF: AttributeError: '__proxy__' object has no attribute '_delegate_text'
I am using Django==5.0.1 and djangorestframework==3.14.0 I have created a Django model that uses gettext_lazy for the verbose field name. However, when I try to serialize it using drf serializers.ModelSerializer and try to repr it, i get an AttributeError: 'proxy' object has no attribute '_delegate_text'. It seems that django.utils.functional used to have a class attribute cls._delegate_text that no longer exists. However, the smart_repr function in rest_framework.utils.representation is still trying to access it. Is this only relevant for the repr() function or would it effect my app otherwise? Does anyone know how to solve this issue? My model: from django.utils.translation import gettext_lazy as _ class CustomUser(AbstractUser): email = models.EmailField(_("email address"), unique=True) .... class CustomUserSerializer(serializers.ModelSerializer): class Meta: model = CustomUser fields = ["email", "first_name", "last_name"] read_only_fields = ["email", "first_name", "last_name"] DRF smart_repr: def smart_repr(value): if isinstance(value, models.Manager): return manager_repr(value) if isinstance(value, Promise) and value._delegate_text: value = force_str(value) value = repr(value) # Representations like u'help text' # should simply be presented as 'help text' if value.startswith("u'") and value.endswith("'"): return value[1:] # Representations like # <django.core.validators.RegexValidator object at 0x1047af050> # Should be presented as # <django.core.validators.RegexValidator object> return re.sub(' at 0x[0-9A-Fa-f]{4,32}>', '>', value) error code: serializer = CustomUserSerializer() print(repr(serializer)) Traceback (most recent call last): … -
TypeError: Abstract models cannot be instantiated (Django)
I have abstract models A and B and a child model C. class A(models.Model): field1 = models.CharField(max_length=24) class Meta: abstract = True class B(models.Model): field1 = models.CharField(max_length=24) class Meta: abstract = True def make_A(self): A(field1=self.field1).save() class C(B): pass If I try to run C.make_A() I get TypeError: Abstract models cannot be instantiated error. So I am forced to re-write make_A method on the child. Is there a way to write a method that instantiates A under abstract B? -
DJango join on two fields
Basically I have three models in django: Car(models.Model): id = models.BigAutoField(primary_key=True) company_id = models.ForeignKey(Company, models.DO_NOTHING) type_id = models.ForeignKey(Type, models.DO_NOTHING)' Type(model.Model): id = models.BigAutoField(primary_key=True) size = models.CharField(max_length=1024, blank=True, null=True) Vendor(model.Model): id = models.BigAutoField(primary_key=True) company_id = models.ForeignKey(Company, models.DO_NOTHING) type_id = models.ForeignKey(Type, models.DO_NOTHING) vendor_priority = models.CharField(max_length=1024, blank=True, null=True) i also have the code my_cars = Car.objects.filter(cars_filter) What I wish to do is to join the information from ventor to my_cars so that I could access the vendor_priority information, I would have to create a join on type_id and company_id, keeping my existing filters. In SQL what I want to do would akin to: select * from cars left join vendor on cars.company_id = vendor.company_id and cars.type_id = vendor.type_id where cars_filter = cars_filter; -
Why doesn't the post editing page open, django?
Code that works correctly when editing a post. But after adding the AbstractUser model, something went wrong. приложения publication: views.py: @login_required def edit_post(request, post_slug): post = get_object_or_404(Userpublication, slug=post_slug) if request.user != post.author: messages.error(request, 'You cannot edit this post') return redirect('feeds', post_slug=post.slug) if request.method == 'POST': form = PostEditForm(request.POST, instance=post) if form.is_valid(): form.save() messages.success(request, 'The post has been successfully edited!') # Setting flash message return redirect('feeds', post_slug=post.slug) # Redirect to the post view page else: form = PostEditForm(instance=post) return render(request, 'publication/edit_post.html', {'form': form}) def get_edit_url(self): return reverse('edit_post', kwargs={'post_slug': self.slug} publication application forms.py: from django import forms from .models import Userpublication class PostEditForm(forms.ModelForm): class Meta: model = Userpublication fields = ['content'] publication application models.py: from django.db import models from autoslug import AutoSlugField #AutoSlugField from django.urls import reverse from django.contrib.auth.models import User from django.conf import settings from user.models import ProfileUser # ProfileUser class PublishedManager(models.Manager): def get_queryset(self): return super().get_queryset().filter(is_published=1).order_by('-time_create') class Userpublication(models.Model): author = models.ForeignKey( ProfileUser, on_delete=models.CASCADE, related_name='publications', blank=True, null=True, ) slug = AutoSlugField(max_length=255, unique=True, populate_from='content') content = models.TextField('', blank=True) time_create = models.DateTimeField('time_create', auto_now_add=True) time_update = models.DateTimeField('time_update', auto_now=True) is_published = models.BooleanField('is_published', default=True) objects = models.Manager() published = PublishedManager() def __str__(self): return self.slug class Meta: ordering = ['-time_create'] indexes = [ models.Index(fields=['-time_create']) ] class Meta: verbose_name … -
Embedding Superset dashboards in a Django application - Help needed
Junior developer here, so some answers might need context :) but I thank you in advance for your help. I am trying to embed a Apache Superset dashboard to a Django application and struggling to find any meaningful documentation for the same, including this one: https://github.com/apache/superset/tree/master/superset-embedded-sdk Background: The Django app is running perfectly on localhost:8000 and the Apache Superset is also running perfectly on localhost:8088 (embedding is enabled in Superset). Problem is them working together :( A logged-in user of the Django app needs to be able to see the dashboard created on Apache Superset I have implemented a utility function in the Django app to fetch a guest_token (for a user with Public and Gamma permissions on Superset). This guest_token along with the dashboard embed ID is passed to the template When the page is visited by the user, nothing appears on the page except a small grey screen saying 127.0.0.1 refused to connect Code to fetch guest_token: import requests from django.conf import settings def fetch_guest_token(dashboard_id): url = f"{settings.SUPERSET_SITE_URL}/api/v1/security/guest_token" headers = { "Authorization": f"Bearer {settings.SUPERSET_ADMIN_TOKEN}", "Content-Type": "application/json", } payload = { "user": { "username": "guest_test", "first_name": "Test", "last_name": "User" }, "resources": [{ "type": "dashboard", "id": dashboard_id }], } response … -
Storing files to S3 not working inside Celery worker
I am facing issues with storing files in S3 from django's celery task. I am doing following things Get data from DB Create the XLSX file with BytesIO Storing that file with file.save method of Django code snippate try: excel_file = generate_xlsx_file(sheet_dfs) except Exception as e: logger.exception("Error while generating excel file") return # Save the report report = Report.objects.create() file_name = generate_file_name() # Save the file report.file.save(file_name, ContentFile(excel_file)) at the last line, celery worker just stops and don't process any other tasks as well. Also this code works fine if I run it in django shell -
django: NULL error on model field despite default value
My model class is defined as follows: class Vendor(models.Model): """ ORM representing vendors Relationships: A vendor may have many documents """ id = models.AutoField( primary_key=True, ) name = models.CharField( max_length=255, blank=True, db_default='', default='', ) logo_uri = models.CharField( max_length=255, blank=True, db_default='', default='', ) web_url = models.CharField( max_length=255, blank=True, db_default='', default=None, ) created_on = models.DateTimeField( auto_now_add=True, null=False, ) def __str__(self) -> str: return f"{self.name}" class Meta: ordering = ["created_on"] verbose_name = "vendor" verbose_name_plural = "vendors" I am using MySQL and have checked the database DDL - the default value for specified columns is set as ''. If I insert using a SQL statement directly in MySQL it works fine and default values are assigned as appropriate - INSERT INTO `core_vendor` (`name`, `created_on`) VALUES ('TES', NOW() ); However when I programatically try to insert via django - vendor = Vendor() vendor.name='TES2' vendor.save() I receive an error django.db.utils.IntegrityError: (1048, "Column 'web_url' cannot be null") Though web_url has a default value assigned at django and DB level. Any thoughts on where I am incorrect? -
My JavaScript file will run from one html file, but not from another in the same directory
Both friends.html and homepage.html are in the same folder. Homepage can access friends.js just fine but when I try to access it from friends.html it gives me this error: GET http://127.0.0.1:8000/homepage/static/js/friends.js net::ERR_ABORTED 404 (Not Found) <!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <title>Document</title> {% load static %} <link rel="stylesheet" href="{% static 'css/friends.css' %}"> </head> <body> <div class="ui-wrapper"> <div class="friend_request"> <textarea name="" id="" cols="30" rows="1"></textarea> </div> </div> <script src="../../static/js/jQuery.js"></script> <script src="../static/js/friends.js"></script> </body> </html> <!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <title>Document</title> {% load static %} <link rel="stylesheet" href="{% static 'css/spinner.css' %}"> <link rel="stylesheet" href="{% static 'css/mainpage.css' %}"> <link rel="stylesheet" href="{% static 'css/background.css' %}"> <link rel="stylesheet" href="{% static 'css/output.css' %}"> {% if newuser %} <link rel="stylesheet" href="{% static 'css/instructions.css' %}"> {% endif %} </head> <body> <a href="{% url 'friends' %}"> <button class="title-btn fade-in" id="friends-btn" onclick="friends_tab()">Friends >></button> </a> <!-- django to js variables --> <script data-newuser="{{ newuser }}"> window.CSRF_TOKEN = "{{ csrf_token }}"; const data = document.currentScript.dataset; const isNewUser = data.newuser == 'True'; </script> <script src="../../static/js/jQuery.js"></script> <script src="../static/js/mainpage.js"></script> <script src="../static/js/friends.js"></script> </body> </html> @login_required def friends(request): return render(request, 'friends.html') -
Create a progress bar
I have an education website and I would like to include a progressive strip, if that solves one problem it would have to be a show the progress bar.like that--- enter image description here and my website bar:I want to make this progress bar like the one above, please suggest the steps. enter image description here made a this website HTML+CSS+TAILWIND+DJANGO+POSTGREL+... same as upper please sove this probelm thanks. -
How do i Fix this django.db.utils.DatabaseError
How do i fix Django Database error. I'm using MongoDB with Djongo. Everything was working fine until recently. When it tested it after some days, it doesnt work. i am able to use get method without error, but when i request a post mehtod , i get this django.db.utils.DatabaseError. Internal Server Error: /category Traceback (most recent call last): File "/Users/sangeethsivan/opt/anaconda3/lib/python3.9/site-packages/djongo/cursor.py", line 51, in execute self.result = Query( File "/Users/sangeethsivan/opt/anaconda3/lib/python3.9/site-packages/djongo/sql2mongo/query.py", line 784, in init self._query = self.parse() File "/Users/sangeethsivan/opt/anaconda3/lib/python3.9/site-packages/djongo/sql2mongo/query.py", line 876, in parse raise e File "/Users/sangeethsivan/opt/anaconda3/lib/python3.9/site-packages/djongo/sql2mongo/query.py", line 857, in parse return handler(self, statement) File "/Users/sangeethsivan/opt/anaconda3/lib/python3.9/site-packages/djongo/sql2mongo/query.py", line 928, in _insert query = InsertQuery(self, self.db, self.connection_properties, sm, self._params) File "/Users/sangeethsivan/opt/anaconda3/lib/python3.9/site-packages/djongo/sql2mongo/query.py", line 340, in init super().init(*args) File "/Users/sangeethsivan/opt/anaconda3/lib/python3.9/site-packages/djongo/sql2mongo/query.py", line 62, in init self.parse() File "/Users/sangeethsivan/opt/anaconda3/lib/python3.9/site-packages/djongo/sql2mongo/query.py", line 410, in parse self._fill_values(statement) File "/Users/sangeethsivan/opt/anaconda3/lib/python3.9/site-packages/djongo/sql2mongo/query.py", line 368, in _fill_values raise SQLDecodeError djongo.exceptions.SQLDecodeError: Keyword: None Sub SQL: None FAILED SQL: ('INSERT INTO "RentApp_category" ("type") VALUES (%(0)s)',) Params: (['Wardrobes'],) Version: 1.3.6 The above exception was the direct cause of the following exception: Traceback (most recent call last): File "/Users/sangeethsivan/opt/anaconda3/lib/python3.9/site-packages/django/db/backends/utils.py", line 89, in _execute return self.cursor.execute(sql, params) File "/Users/sangeethsivan/opt/anaconda3/lib/python3.9/site-packages/djongo/cursor.py", line 59, in execute raise db_exe from e djongo.database.DatabaseError The above exception was the direct cause of the following exception: … -
Why am I getting this error when trying to use postgis
When I'm making migrations, I get this error. (project) PS D:\University\FYP\final_project\land_management_system> python manage.py makemigrations Traceback (most recent call last): File "D:\University\FYP\final_project\land_management_system\manage.py", line 22, in <module> main() File "D:\University\FYP\final_project\land_management_system\manage.py", line 18, in main execute_from_command_line(sys.argv) File "D:\University\FYP\final_project\project\Lib\site-packages\django\core\management\__init__.py", line 442, in execute_from_command_line utility.execute() File "D:\University\FYP\final_project\project\Lib\site-packages\django\core\management\__init__.py", line 416, in execute django.setup() File "D:\University\FYP\final_project\project\Lib\site-packages\django\__init__.py", line 24, in setup apps.populate(settings.INSTALLED_APPS) File "D:\University\FYP\final_project\project\Lib\site-packages\django\apps\registry.py", line 124, in populate app_config.ready() File "D:\University\FYP\final_project\project\Lib\site-packages\django\contrib\admin\apps.py", line 27, in ready self.module.autodiscover() File "D:\University\FYP\final_project\project\Lib\site-packages\django\contrib\admin\__init__.py", line 52, in autodiscover autodiscover_modules("admin", register_to=site) File "D:\University\FYP\final_project\project\Lib\site-packages\django\utils\module_loading.py", line 58, in autodiscover_modules import_module("%s.%s" % (app_config.name, module_to_search)) File "C:\Program Files\Python311\Lib\importlib\__init__.py", line 126, in import_module return _bootstrap._gcd_import(name[level:], package, level) ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ File "<frozen importlib._bootstrap>", line 1204, in _gcd_import File "<frozen importlib._bootstrap>", line 1176, in _find_and_load File "<frozen importlib._bootstrap>", line 690, in _load_unlocked File "<frozen importlib._bootstrap_external>", line 940, in exec_module File "<frozen importlib._bootstrap>", line 241, in _call_with_frames_removed File "D:\University\FYP\final_project\land_management_system\core\admin.py", line 3, in <module> from django.contrib.gis.admin import OSMGeoAdmin ImportError: cannot import name 'OSMGeoAdmin' from 'django.contrib.gis.admin' (D:\University\FYP\final_project\project\Lib\site-packages\django\contrib\gis\admin\__init__.py) Here's imports from my admin code: from django.contrib import admin from .models import User, Land, LandTransfers, NFTs, AuthTokens, TaxesFees from django.contrib.gis.admin import OSMGeoAdmin I've tried adding custom path for GEOS and GDAL in settings, still it didn't help: GDAL_LIBRARY_PATH = r"C:\OSGeo4W\bin\gdal308.dll" GEOS_LIBRARY_PATH = r"C:\OSGeo4W\bin\geos_c.dll" -
Django: Link to own AdminSite in template of TemplateView
I defined my own AdminSite in Django 5.0.2 and added some APPs to this AdminSite. This is working and I can access my own admin page via http://127.0.0.1:8080/my-admin/. Now I would like to add the link of this admin-page ("my-admin") to a template of a templateView. (see the ????????? in the main.html file). The link to the standard admin-page is working fine. I am a beginner with Django and tried a few days to get this up&running, but unfortunately I could not find any solution. Could someone give me an hint, please? mydjango/myadmin/admin.py: from django.contrib.admin import AdminSite class EventAdminSite(AdminSite): site_header = 'Test ADMIN' site_titile = 'Test ADMIN PORTAL' index_title = 'WELCOME TO MY ADMIN PORTAL' my_admin_site = EventAdminSite(name = 'my_admin') mydjango/applications/admin.py: from django.contrib import admin from .models import Application from myadmin.admin import my_admin_site class ApplicationAdmin(admin.ModelAdmin): search_fields = ["name", "dest1_protocol","dest1_port"] exclude = ["created","modified"] admin.site.register(Application) my_admin_site.register(Application,ApplicationAdmin) mydjango\mysettings.py: urlpatterns = [ .. path("my-admin/",my_admin_site.urls), .. ] mydjango/main/views.py: from django.shortcuts import render from django.views.generic.base import TemplateView class IndexView(TemplateView): template_name = 'main/index.html' def get_context_data(self, *args, **kwargs): context = super().get_context_data(*args, **kwargs) context['title'] = "Policy-Management" return context mydjango/main/templates/main.html {% load admin_urls %} <!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta http-equiv="X-UA-Compatible" content="IE=edge"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <title>{{ title … -
Vue script in my django project is not showing up
I currently nearly finished a django project. On top of it, I just want to use vue to spare some repetition and discover some features that might better the user interaction experience. I referenced vue through CDN link in my base template <scriptsrc="https://unpkg.com/vue@3/dist/vue.global.js"></script>. And under the link, I tried a demo vue code <script> const { createApp, ref } = Vue createApp({ setup() { const notice = ref('Hello vue!') return { notice } } }).mount('#app') </script> On top of my template I added <div id="app">{{notice}} something</div>. I expect the top of my website to show a "hello vue! something", meaning vue is running properly. But I only get "something". Is CDN way of linking vue not acceptable to django or something else I misdid during the process that makes my vue demo code not working? -
Wagtail: Unwanted wagtail queries on every page
I use Wagtail 5.2 and have on everypage this three queries. Why is Wagtail doing this? Even if I go to www.example.com/admin/ (Default Django admin page) I can see this three queries? Is this the default behavior or I am doing something wrong? Is it possible to cache at least the first query somehow? I guess wagtail is trying to get for each the current site objects. -
Optimizing SimpleJWT to imporove performance
I got a issue with SimpleJWT on my API built in Dajngo, it takes 2 secs to response. I know it doesn't seem like a long time but I really need to improve it. On the Profile table in MySQL database, username and password fields are indexed. I was reading the official documentation but I don't see any advice for improve performance. Someone there with a better knowledge than me that who can help me? settings.py SIMPLE_JWT = { 'ACCESS_TOKEN_LIFETIME': timedelta(minutes=6000), 'ALGORITHM': 'HS256', 'SIGNING_KEY': SECRET_KEY, } urls.py (cutted) from rest_framework_simplejwt.views import (TokenObtainPairView, TokenRefreshView) urlpatterns = [ path('', include('api.urls')), path('token/', TokenObtainPairView.as_view(), name='token_obtain_pair') ] I tried indexing the username and password fields on the Profile table. -
I am trying to update a value in my django model but its not getting updated
I have created a view that scans the report_file which is a excel sheet and checks the previous value and compares it with the new value and then calculates the percentage difference. This takes function only executes whenever the report_file gets updated. But for some reason when I try to save the percentage difference it does not get saved. My new value gets saved but the percentage does not. And I have also kept print statements which are printing the correct values. Below is my views.py: @login_required(login_url='my-login') def update_testcase(request, pk): testcase = get_object_or_404(TestCase, pk=pk, user=request.user) if request.method == 'POST': form = TestCasesForm(request.POST, request.FILES, instance=testcase) if form.is_valid(): # Save the form form.save() # Read the uploaded .xlsx file excel_file = testcase.report_file.read() # Extract the total number of test cases using the function from xlsx_utils.py total_test_cases = extract_total_test_cases(excel_file) print(total_test_cases) # Calculate the percentage increase previous_total_test_cases = testcase.total_test_cases print(previous_total_test_cases) if previous_total_test_cases: percentage_increase = ((total_test_cases - previous_total_test_cases) / previous_total_test_cases) * 100 else: percentage_increase = None print(percentage_increase) # Update the model instance with the total number of test cases and percentage increase testcase.total_test_cases = total_test_cases testcase.increase_percentage = percentage_increase testcase.save() return redirect('writer:my-testcases') else: form = TestCasesForm(instance=testcase) context = {'UpdateTestCaseForm': form} return render(request, 'writer/update-testcase.html', context) below is … -
Django error" Its showing template doesnot exists"
check the below iamges.I'm new to django I just tried to run a project downloaded from internet. -
Steam screenshot parser
for a long time I wanted to know how to make a parser or maybe something else so that I could add screenshots from my Steam profile to my site. That is, I do not want to download them, but to collect links to screenshots like this: https://steamuserimages-a.akamaihd.net/ugc/2265940142968960301/6F3FBB0765789516872B71DDDF0C3042E4354F2E/. And then process them on your website. Because I haven't seen something like this through the SteamAPI, and it seems I haven't seen the libraries either, but maybe I wasn't looking for it well. Therefore, I will be glad if you 'throw' something. I make the site on Django -
Gunicorn not able to bind django project
I installed gunicorn inside virtual environment for running a django project in Ubutu 22 and tried to bind the project URL. But the below error appear and I am not able to bind. Can anybody please help me fix this error. Thanks python --version Python 3.10.12 (venv_django_proj) django@ubuntu-Virtual-Machine:~/django_proj/django_proj$ gunicorn django_proj.wsgi [2024-02-19 18:59:13 +0530] [25811] [INFO] Starting gunicorn 20.1.0 [2024-02-19 18:59:13 +0530] [25811] [INFO] Listening at: http://127.0.0.1:8000 (25811) [2024-02-19 18:59:13 +0530] [25811] [INFO] Using worker: sync [2024-02-19 18:59:13 +0530] [25812] [INFO] Booting worker with pid: 25812 [2024-02-19 18:59:13 +0530] [25812] [ERROR] Exception in worker process Traceback (most recent call last): File "/usr/lib/python3/dist-packages/gunicorn/arbiter.py", line 589, in spawn_worker worker.init_process() File "/usr/lib/python3/dist-packages/gunicorn/workers/base.py", line 134, in init_process self.load_wsgi() File "/usr/lib/python3/dist-packages/gunicorn/workers/base.py", line 146, in load_wsgi self.wsgi = self.app.wsgi() File "/usr/lib/python3/dist-packages/gunicorn/app/base.py", line 67, in wsgi self.callable = self.load() File "/usr/lib/python3/dist-packages/gunicorn/app/wsgiapp.py", line 58, in load return self.load_wsgiapp() File "/usr/lib/python3/dist-packages/gunicorn/app/wsgiapp.py", line 48, in load_wsgiapp return util.import_app(self.app_uri) File "/usr/lib/python3/dist-packages/gunicorn/util.py", line 384, in import_app mod = importlib.import_module(module) File "/usr/lib/python3.10/importlib/__init__.py", line 126, in import_module return _bootstrap._gcd_import(name[level:], package, level) File "<frozen importlib._bootstrap>", line 1050, in _gcd_import File "<frozen importlib._bootstrap>", line 1027, in _find_and_load File "<frozen importlib._bootstrap>", line 1006, in _find_and_load_unlocked File "<frozen importlib._bootstrap>", line 688, in _load_unlocked File "<frozen importlib._bootstrap_external>", line 883, in …