Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Django AdminDocs with Uppercase App Names
I am trying to implement Django's Admin Docs (django.contrib.admindocs) into my project. I've now realized that the best practice for app names is to be lower case, as the generated urls default to a lowercase url name. For example, my app name is Projects: Stores all Project entries, related to :model:`Projects.Project` On the admin page, the generated url leads to admin/doc/models/projects.project/ instead of admin/doc/models/Projects.project/ Is there an easy way to resolve this without having to rename every app in my project? When manually changing the url to the app name (uppercase), the page works as intended. -
Getting error while writing the dynamic URL in Django
I am trying to build a webapp using Django and in that I wanna add the delete functionality but when I put the id the URL in the template, it gives an error saying Reverse for 'remove_items' with arguments '('',)' not found. 2 pattern(s) tried: ['remove_items/(?P<rem_id>[0-9]+)/\\Z', 'remove_items/\\Z'] Below is the view. def dashboard_home(request): password_items = PasswordItem.objects.all() space = Space.objects.all() context = {'space':space, 'password_items':password_items} return render(request, 'dashboard_home.html', context) def remove_items(request, rem_id): passitem = PasswordItem.objects.get(pk=rem_id) passitem.delete() return redirect('dashboard_home') Below is the link for delete from the template. <a class="dropdown-item remove-item-btn" href="{% url 'remove_items' password_items.id %}"> <i class="ri-delete-bin-fill align-bottom me-2 text-muted"></i> Delete </a> Below is the url that I am using. path('remove_items/<int:rem_id>/', views.remove_items, name='remove_items'), I don't know why I am getting this error. It seems all good to me. -
Who can explain me how to make login by token without password using rest framework django and simple-jwt?
I have simple problem and can't solve it. I have sigle page site looks something like that <div id="login"></div> <div id="leaderboard_win" style="display: none;"></div> <div id="before_start"></div> <div id="game"></div> <div id="rules_text" class="bg-info"></div> When you go to the site i want to check token. var token = localStorage.getItem("my_game_token"); $.ajax({ url: "http://127.0.0.1:8000/api/v1/verify_player/", type: "POST", headers: { "Authorization": "Bearer " + token } }).done(function(data) { console.log(data) }).fail(function(xhr) { if (xhr.status === 401) { $('#login').show() $('#leaderboard_win').remove() $('#before_start').remove() $('#game').remove() } }) If the token exists then return the player's name and best time and remove #login accordingly and show before start. If the token does not exist or wrong then as shown above. And wait until the user enters data. $.ajax({ url: "http://127.0.0.1:8000/api/ego/verify_player/", type: "POST", data: { name : $("#player_name").val(), phone_number : $("#player_phone").val(), }, }).done(function(data) { console.log(data) // window.location.reload() }) if name and phone number exists in db give new token and save in local storage and return the player's name and best time and remove #login accordingly and show before start. if not exists create new player and return token. what i have now. managers.py from django.contrib.auth.models import UserManager as DefaultUserManager class UserManager(DefaultUserManager): def create_user(self, phone_number, name, password=None, **extra_fields): if not phone_number: raise ValueError('The Phone Number … -
How Do I Pass HIdden HTML Value From One Page To Another?
I know there are many variations of answers here but none that seem to fit my use case. I'm using Django.....I am trying to pass a page number from one page to another when I click on an tag. I have defined the hidden input on both HTML pages...but can't seem to figure out how to get the value.... Here's my View... def get_context_data(self, **kwargs): context = super(ListView, self).get_context_data(**kwargs) page_number = self.request.GET.get('page') context['page_number'] = page_number return context Here's my HTML... First HTML Page <form method="POST" id="forms"> <table> <td><a href="{% url 'Main:notify_update' pk=notify.id %}">{{ notify.new_vacation_calendar.status }}</a></td> <input type="hidden" id="page_number" value="{{ page_number }}"> </table> </form> The above renders correctly.... My second page.... <form method="POST"> <button type="button" class="button67">Button</button> <input type="hidden" id="page_number"> </form> My Javascript... $(document).ready(function (){ $('.button67').on('click', function (event) { var page = document.getElementById("page_number").value; console.log(page); }); When I try to process the second page....the value isn't being passed and I can't figure out what I'm missing. I'm used to passing values via the URL...but can't seem to figure out how to do this without using the URL. Thanks in advance for any tips on what I'm doing incorrectly. -
How to check if static files are loaded with prodcution environment?
I have dockerized a django app. And "everything" seems to work. The docker containers are up and running. And I can access the django admin url. But I try to figure out how to check if the static files will be loaded if I will deploy it on the azure environment. Because at the moment I am testing the production environment still on localhost. And even when I am setting the debug to 1. The static files are not loading. So this is the docker compose file: version: "3.9" services: web: build: context: ./ dockerfile: Dockerfile.prod restart: always command: gunicorn Welzijn.wsgi:application --bind 0.0.0.0:8000 volumes: - static_volume:/web/staticfiles - media_volume:/web/media expose: - 8000 environment: - DEBUG=1 env_file: - ./.env.prod proxy: build: ./proxy restart: always depends_on: - web ports: - 1337:80 volumes: - static_volume:/web/staticfiles - media_volume:/web/media volumes: static_volume: media_volume: And part of settings.py file: SECRET_KEY = os.environ.get('SECRET_KEY') DEBUG = os.environ.get('DEBUG') == "1" ALLOWED_HOSTS = ['*'] ALLOWED_HOSTS.extend( filter( None, os.environ.get('ALLOWED_HOSTS', '').split(" "), ) ) CSRF_TRUSTED_ORIGINS = ["http://localhost:1337"] STATIC_URL = '/static/' MEDIA_URL = '/media/' STATIC_DIRS = [ (BASE_DIR, 'static') ] STATICFILES_DIRS =[BASE_DIR / 'static'] STATIC_ROOT = BASE_DIR /'staticfiles/' MEDIA_ROOT = BASE_DIR /'media' and in the env.prod I also setted DEBUG=1 And I am using the … -
Django Channels not receiving the event raised from library
This is my Consumer Class. from channels.generic.websocket import WebsocketConsumer,AsyncWebsocketConsumer from channels.layers import get_channel_layer import asyncio import random import json class TradeSession(AsyncWebsocketConsumer): async def connect(self): print("In Consumer Now") self.room_name = "test_consumer" self.room_group_name = "test_consumer_group" await self.channel_layer.group_add(self.room_name, self.channel_name) await self.accept() async def disconnect(self, close_code): print("Disconnected Now") await self.channel_layer.group_discard(self.room_group_name, self.channel_name) raise channels.exceptions.StopConsumer() async def receive(self, text_data=None, bytes_data=None): print("Data Recieverd") pass async def send_number(self, event): print("in Send number Send event",event) number = event["price"] print("Actuly sending now ",number) await self.send(text_data=json.dumps({"price": number})) Following Is my Communicator liberary from where I am trying to raise an event. from channels.layers import get_channel_layer from asgiref.sync import async_to_sync import asyncio class Communicator: def __init__(self): pass def send_data_to_channel_layer(self, data, group_name): group_name = "test_consumer_group" print("In liberary sending data") channel_layer = get_channel_layer() print("Sendiong now to group",group_name) async_to_sync(channel_layer.send)(group_name, { "type": "send.number", "price": data['price'], }) # print("Message sent to group") In the logs I can see till the point - Sendiong now to group",group_name And after this log I see nothing on the console To add to to this My websocket is working fine And i have verified that from the client as well I am using redis-channel for the internal communication for channals This is the configuration for the same CHANNEL_LAYERS = { "default": … -
Django migrate uses wrong database backend for some migrations
Summary Consider a project with two local database configurations, called 'sqlite' (default) and 'postgresql'. Running migrate --database=postgresql successfully migrates the first few migrations to postgresql, then, suddenly, starts using the wrong database backend, resulting in the following error: sqlite3.OperationalError: no such table: myapp_mymodel Background Working on a legacy Django 3.2 project with over ten apps and over two-hundred migrations in total. The project is configured to use PostgreSQL in production, but uses SQLite for local testing. Now, for consistency, I want to configure the project to use PostgreSQL locally as well, instead of SQLite. So, here's what I did: created a brand new PostgreSQL database on the local dev system, configured for Django added a database configuration called 'postgresql' to the local settings file, in addition to the 'default' SQLite configuration (see example below) DATABASES = { 'default': { 'ENGINE': 'django.db.backends.sqlite3', ..., }, 'postgresql': { 'ENGINE': 'django.db.backends.postgresql_psycopg2', ..., }, } tested and verified the database and corresponding Django configuration ran python manage.py migrate --database=postgresql That's where things went wrong. Problem The first hundred migrations (approx.) were applied properly, but then Django ran into an error: Running migrations: Applying myapp.0002_copy_data_from_mymodel...python-BaseException Traceback (most recent call last): ... sqlite3.OperationalError: no such table: myapp_mymodel … -
django.utils.formats.date_format returning messy result
In Django 1.11, given a datetime.datetime object, e.g. datetime.datetime(2023, 8, 24, 16, 50, 5, 685162, tzinfo=<DstTzInfo 'Europe/Bucharest' EEST+3:00:00 DST>) I am trying to format it to 24.08.2023 by invoking: from django.utils.formats import date_format date_format(date, 'NUMERICAL_DATE_FORMAT') Instead of the expected result, I get: Aug.1692885005AugAugustR1CPMFalse_ThuPMEESTAugust_August+0300RAugPMEEST As per the Django docs, I've defined NUMERICAL_DATE_FORMAT = 'd.m.Y' in my FORMAT_MODULE_PATH. What am I missing? -
Reset password for user who registered with Social Auth (Google) [Django, Djoser, Social Auth]
I am trying to using custom model with Djoser JWT endpoint but I want to reset the password for those user who register with Google OAuth. When I am using the API endpoint the password reset mail is not getting send to mail. Any suggestion is appreciated. I tried to alter the reset password to get the email ID but i am not able to fetch the Email ID from custom user model. -
problem with internal files in django command line
I started learning django and ran into a problem I wanted to add products via the command line, but ran into a problem: Traceback (most recent call last): File "C:\Program Files\JetBrains\PyCharm 2023.2\plugins\python\helpers\pydev\pydevconsole.py", line 364, in runcode coro = func() File "", line 6, in File "C:\Users\dratyti\OneDrive\Рабочий стол\store-server\venv\lib\site-packages\django_init_.py", line 19, in setup configure_logging(settings.LOGGING_CONFIG, settings.LOGGING) File "C:\Users\dratyti\OneDrive\Рабочий стол\store-server\venv\lib\site-packages\django\conf_init_.py", line 82, in getattr self.setup(name) File "C:\Users\dratyti\OneDrive\Рабочий стол\store-server\venv\lib\site-packages\django\conf_init.py", line 63, in _setup raise ImproperlyConfigured( django.core.exceptions.ImproperlyConfigured: Requested setting LOGGING_CONFIG, but settings are not configured. You must either define the environment variable DJANGO_SETTINGS_MODULE or call settings.configure() before accessing settings. I tried to find information on the internet, but I didn't find anything -
django-jsignature on a modal not showing until I change the screen size
I'm trying to get a Django-signature form into a modal but the pad were to sign isn't loading. The modal and the rest of the form, buttons and whatnot are there and fine. If I then change the size screen, either changing the actual size of the browser or by entering responsive design mode/toggle device toolbar on web developer tools, the pad will appear and work fine. Its probably a size/resize issue with the library but I seem to get stuck here. PS. all is fine if don't use modal but a full html page instead. The code: test.html : (loading the modal with a btn call to htmx) <button type="button" class="btn btn-primary" hx-get="{% url 'tools:test_signature' %}" hx-target="#modal-fullscreen-signature-content" hx-trigger="click"> Launch signature </button> view.py : (not checking for post or anything, its juts a test to make the signature work) def test_signature(request): signform = forms.SignatureForm() context = {'signform': signform,} return render(request, 'tools/test_signature.html', context) forms.py: from jsignature.widgets import JSignatureWidget class SignatureForm(forms.ModelForm): class Meta: model = Signature fields = "__all__" modal: <div class="modal fade" id="modal-fullscreen-signature" data-bs-backdrop="static" data-bs-keyboard="false" tabindex="-1" aria-labelledby="staticBackdropLabel" aria-hidden="true"> <div class="modal-dialog modal-fullscreen"> <div class="modal-content"> <div class="modal-body" id="modal-fullscreen-signature-content"> </div> <div class="modal-footer"> <button id="save_btn" hx-post="{% url 'tools:test_signature' %}" type="button" class="btn btn-secondary" data-bs-dismiss="modal">Save</button> <button type="button" … -
My app named store does not get recognized to migrate
When migrating, my app 'store' seems to not be recognized. It is already installed inside setting.py but still states "No installed app with label 'store'"enter image description here When migrating the _0001_initial.py was also not created automatically under migrations. -
Templatetag not working in Django 4.2 template IF condition
I have a Django 4.2 project. For an extra Templatetag I created this simple_tag. @register.simple_tag(takes_context=True) def user_help(context): # True if HELP is ON for user u = context['request'].user if u.needs_help: return True else: return False In the HTML template, I try to catch that Tag in an IF statement, to display help to the user, if needed, like this: <p>{% user_help %}</p> {% if user_help %} <h2>Some help text</h2> {% endif %} Although the p-statement shows True in the rendered template, the If condition part of the template is not shown...? What am I getting wrong here? -
CSRF cookie not set in Django POST
I have searched many of the SO questions and answers on this topic but cannot solve my problem. My js is based on this answer xxx.js import Cookies from 'js-cookie'; async function sendDataToAPI(uri, params) { let url = buildURI(uri, params); let endpoint = `${process.env.API_DOMAIN}${url}/`; try { const response = await fetch(endpoint, { method: "POST", credentials: 'include', headers: {'X-CSRFToken': Cookies.get('csrftoken')}, body: JSON.stringify({ data: params, }), } ); const data = await response.json(); return data; ... settings.py ... CSRF_TRUSTED_ORIGINS = [ 'http://localhost:8888' ] CORS_ORIGIN_ALLOW_ALL = False CORS_ORIGIN_WHITELIST = ( 'http://localhost:8888', ) CORS_ALLOW_HEADERS = [ "X-CSRFToken", ] CORS_ALLOW_CREDENTIALS = True ... INSTALLED_APPS = [ ..., 'corsheaders', ... ] MIDDLEWARE = [ 'corsheaders.middleware.CorsMiddleware', ... ] I get ther error WARNING:django.security.csrf:Forbidden (CSRF cookie not set.) -
Serving a simple static asset in Django
I know this looks like a duplicate, but at this point I must have seen and tried every other solution to no avail, so I'm adding my question to the long list of existing questions in this vein. I don't have a ton of experience with Django, but I have an API on v3.2.16 of the framework to which I'd like to inject a static version file that I can reach through the browser. As this is an API, there are no other static assets that need to be served so I may not need the full django.contrib.staticfiles treatment (although I have tried it). What I'm looking for is the simplest possible way that I can create a directory from which Django will be able to serve a single static asset that I'll place during the application's build process. I've tried a bunch of staticfiles stuff over the last day or so, but am currently trying a simple implementation of: STATIC_URL = '/static/' STATICFILES_DIRS = ( os.path.join(settings.SITE_ROOT, 'assets'), ) Where the settings.SITE_ROOT value is /code on my container and /code/assets exists on the server. No matter what solution I've tried - including setting the STATIC_ROOT to that same directory and … -
ImportError: allauth needs to be added to INSTALLED_APPS
I've been following this tutorial on the django for apis book by William Vincent. I need to use django-allauth. I've installed it in my venv, added it to installed apps and done all the necessary things according to the installation instructions on the Documentation. On running python manage.py migrate , the error comes back as ImportError: allauth needs to be added to INSTALLED_APPS. This is my settings.py in the relevant areas INSTALLED_APPS = [ "django.contrib.admin", "django.contrib.auth", "django.contrib.contenttypes", "django.contrib.sessions", "django.contrib.messages", "django.contrib.staticfiles", "django.contrib.sites", # 3rd party libraries "rest_framework", "corsheaders", "rest_framework.authtoken", "allauth", "allauth.account", "allauth.socialaccount", "dj_rest_auth", "dj_rest_auth.registration", # Local "accounts", "posts", ] ...... TEMPLATES = [ { "BACKEND": "django.template.backends.django.DjangoTemplates", "DIRS": [], "APP_DIRS": True, "OPTIONS": { "context_processors": [ "django.template.context_processors.debug", "django.template.context_processors.request", "django.contrib.auth.context_processors.auth", "django.contrib.messages.context_processors.messages", "django.template.context_processors.request", ], }, }, ] .... AUTHENTICATION_BACKENDS = [ "django.contrib.auth.backends.ModelBackend", "allauth.account.auth_backends.AuthenticationBackend", ] I appreciate the help in advance. I tried checking the documentation, checked all the commas were put in the appropriate place. Looked for similar situations on reddit and stackoverflow but coudln't find anything along that line. -
Selected categories not showing in django
I'm learning how to make Django websites, simple for now. It is necessary that the category of each account is displayed through the p tag, and all through the rest a. Following the results of all categories are links How it should look As a result is displayed tags.py register = template.Library() @register.simple_tag def get_category(filter=None): if not filter: return Category.objects.all() else: return Category.objects.filter(slug_fields=filter) @register.simple_tag(name="hypixel_accaunts") def get_accaunt(): return hypixel.objects.all() @register.inclusion_tag('product/hyp_cats.html') def show_category(sort=None, cat_selected=0): if not sort: category = Category.objects.all() else: category = Category.objects.order_by(sort) return {'category': category, 'cat_selected' : cat_selected} From hyp_cats.html {% for c in category %} {% if c.slug_fields == cat_selected %} <p>{{ c.name }}</p> {% else %} <a href="{{ c.get_absolute_url }}">{{ c.name }} </a> {% endif %} {% endfor %} From main templates {% get_category as get_cats %} {% if cat_selected == 0 %} <p>All accaunts</p> {% else %} <a href="{% url 'hype' %}">All accaunts</a> {% endif %} {% show_category '-name' cat_selected %} <br> {% block content %} {% endblock %} From views.py def show_acc(request, acc_id): accaunt = get_object_or_404(hypixel, nickname=acc_id) contex = { 'accaunt': accaunt, 'cat_selected' : accaunt.cat, } return render(request,'product/hype_accaunt.html', context=contex) From models.py class Category(models.Model): name = models.CharField(max_length=50, db_index=True) slug_fields = models.SlugField(max_length=255,unique=True, db_index=True, verbose_name="URL") def __str__(self): return self.name … -
how to solve Veem payment gateway 'createpayment' error:50000000
i am using veem payemnt gatway for online payments. when i hit the endpoint i am gettting error {"code":50000000,"message":"Value is unexpected: NZ","timestamp":"2023-08-24T12:05:10.825","fileName":"VeemResponseHandler.java","lineNumber":89} import requests import uuid url = "https://sandbox-api.veem.com/veem/v1.1/payments" payload = { "amount": { "currency": "USD", "number": 12345 }, "payee": { "countryCode": "US", "type": "Incomplete", "businessName": "aaaa", "email": "jawadkhan31849@gmail.com", "firstName": "JAWAD", "lastName": "KHAN", "phone": "+9266364644" }, "approveAutomatically": True, "attachments": [ { "type": "ExternalInvoice", "name": "test.txt", "referenceId": "123456" } ] } headers = { "accept": "application/json", "content-type": "application/json", "authorization": "Bearer e340f2cc-5124-44c7-b1f5-0737bcd9df35", "X-REQUEST-ID": str(uuid.uuid4()) } response = requests.post(url, json=payload, headers=headers) print(response.text) -
Django smart-select ChainedModelChoiceField not working properly
I need to have a dependent dropdown box using smart-select where I filter by Country, State, City and finally Area. These are the relevant models: class Country(models.Model): tenant = models.ForeignKey(Tenant, on_delete=models.PROTECT) country_name=models.CharField(max_length=50) is_active=models.BooleanField(default=True) class State(models.Model): country=models.ForeignKey(Country, on_delete=models.CASCADE) state_name=models.CharField(max_length=50) is_active=models.BooleanField(default=True) class City(models.Model): state=models.ForeignKey(State, on_delete=models.CASCADE) city_name=models.CharField(max_length=50) is_active=models.BooleanField(default=True) class Area(models.Model): city=models.ForeignKey(City, on_delete=models.CASCADE) area_name=models.CharField(max_length=50) is_active=models.BooleanField(default=True) And this is what I have tried in Forms: class CountryFormChoiceField(ModelChoiceField): def label_from_instance(self, obj): return obj.country_name class HomeForm(forms.Form): #some other fields country_name=CountryFormChoiceField(queryset=Country.objects.filter(is_active=True), label='Select Country') state_name=ChainedModelChoiceField('common','State','country_name','country','common','Country','country',show_all=False,auto_choose=False) city_name=ChainedModelChoiceField('common','City','state_name','state','common','State','state',show_all=False,auto_choose=False) area_name=ChainedModelChoiceField('common','Area','city_name','city','common','City','city',show_all=False,auto_choose=False) But in the site, only the country field has values in the dropdown, and even after selecting a country the other fields are not showing any options. This is the template: {% load has_group %} {% block content %} <div class="home"> {% if request.user|has_group:"Organization" %} <h1>Signed in as Organization</h1> {% else %} <h1>Welcome to Gamefront</h1> <form action="" method="post" class="homeform"> {% csrf_token %} <table> {{ form.media.js }} {{ form.as_table }} </table> <input type="submit" value="Submit" class="btn btn-outline-primary"> </form> {% endif %} </div> {% endblock %} What could be the issue? -
CSRF verification failed. Request aborted when i upgraded my django to the latest
I have been developin a quiz app in django 3.8 and it was working rather well but when i updated to the latest django the code is breaking. The code is supposed to calculate the marks of the the student after they submit the answers after which it redirects to view the results.. here is my views.py code for that particular functionality def calculate_marks_view(request): if request.COOKIES.get('course_id') is not None: course_id = request.COOKIES.get('course_id') course=QMODEL.Course.objects.get(id=course_id) total_marks=0 questions=QMODEL.Question.objects.all().filter(course=course) for i in range(len(questions)): selected_ans = request.COOKIES.get(str(i+1)) actual_answer = questions[i].answer if selected_ans == actual_answer: total_marks = total_marks + questions[i].marks student = Student.objects.get(user_id=request.user.id) result = QMODEL.Result() result.marks=total_marks result.exam=course result.student=student result.save() return HttpResponseRedirect('view-result') And this is the django html code to display the options and the questions and the submit answers {% extends 'student/studentbase.html' %} {% block content %} {%load static%} <head> <link href="//netdna.bootstrapcdn.com/bootstrap/3.0.0/css/bootstrap.min.css" rel="stylesheet" id="bootstrap-css"> <script src="//netdna.bootstrapcdn.com/bootstrap/3.0.0/js/bootstrap.min.js"></script> <script src="//code.jquery.com/jquery-1.11.1.min.js"></script> <link href="https://fonts.googleapis.com/css2?family=Quicksand:wght@300;400;500;600;700&display=swap" rel="stylesheet"> <style type="text/css"> body, p, a, h1, h2, h3, h4, h5, h6 { font-family: 'Quicksand', sans-serif; } </style> </head> <div class="jumbotron my-4"> <form class="form" autocomplete="off" onsubmit="return saveAns()" action="/student/calculate-marks" method="POST"> {% csrf_token %} <h2 style="text-align: center;">Topic: {{course.course_name}}</h2> {% for q in questions%} <h3 class="text-danger">{{ forloop.counter }}. {{q.question}}</h3><h4 style="text-align: right;">[{{q.marks}} Marks]</h4> <input type="hidden" name="csrfmiddlewaretoken" value="C24rUotmdHawVQJL3KrqiWxvti8UffOFYUc8TRbZtLt36AVLdP3jbkzUVe3beRAa"> <div class="form-check … -
Not able to install django-filetransfers for python 2.7.18
I am not able to install django-filetransfers for python 2.7.18, I have the same installed in other machine but since I am migrating the project to the new machine I am trying to install it. Please help. pip install django-filetransfers DEPRECATION: Python 2.7 reached the end of its life on January 1st, 2020. Please upgrade your Python as Python 2.7 is no longer maintained. pip 21.0 will drop support for Python 2.7 in January 2021. More details about Python 2 support in pip can be found at https://pip.pypa.io/en/latest/development/release-process/#python-2-support pip 21.0 will remove support for this functionality. ERROR: Could not find a version that satisfies the requirement django-filetransfers (from versions: none) ERROR: No matching distribution found for django-filetransfers -
Django delete folder when session ends
I am creating a directory using the session key and uploading files to it. I want to delete this directory once the user ends the session by closing the tab. def upload_pdf(self, request, form): files = form.cleaned_data["file_field"] # Get or Create Directory Path(f'{PDF_PATH}{request.session.session_key}').mkdir(parents=True, exist_ok=True) for f in files: try: pdf_handler = PdfWriter() pdf_handler.append(f) file_path = f'{PDF_PATH}{request.session.session_key}/{f}' pdf_handler.write(file_path) messages.add_message(request, messages.SUCCESS, f'<b>{f}</b> Uploaded <a href="my-file-view/{file_path}/" target="_blank">View</a>') except: messages.add_message(request, messages.WARNING, f"<b>{f}</b> not Uploaded - not a PDF file") return super().form_valid(form) How can I run a command at session close? -
ReactJS and NPM problem due to week Internet connection
I'm from Iran and due to week Internet connection the "NPM" command doesn't work for me. I want to work with Django rest_framework and I need ReactJS. I couldn't use "npm install -g create-react-app" and I go to github and found its repository. I cloned that repo but I'm not sure that's enough or NOT and yet, I don't know how to use this repo in my project :( ..... If anyone already use "React repo", please help me out. Thanks. -
Is it okay to have multiple ingress connecting to a service in K8s?
We have a multi-tenant Django application that has a deployment with 5 replicas. In front of that deployment, we have a service. and we connected almost 2k ingress to that service. so we tried with a single service after a while we witnessed that load balancing between pods its not working properly and one of our pods hit the cpu limit frequently yet others has a medium to low workload. U can see cpu usage of our pods in below: also u can see the metric container_network_receive_bytes_total in this pic: we dont have any sticky session or session affinity or websockets or anything in our application in order to prefer one pod to another. I was wondering if we should have a service for each one of them or if a single service is okay. I should mention that we us traefik as our load balancer. -
django project on Ubuntu running nginx unable to upload files
I keep getting this error while trying to upload a file via the django admin 2023/08/24 10:51:09 [warn] 4147#4147: *1 a client request body is buffered to a temporary file /var/cache/nginx/client_temp/0000000001, client: 172.71.98.67, server: 72.167.132.218, request: "POST /ran-admin/blog/post/add/ HTTP/1.1", host: "redaid-nigeria.org", referrer: "https://redaid-nigeria.org/ran-admin/blog/post/add/" 2023/08/24 10:52:02 [error] 4147#4147: *10 open() "/usr/share/nginx/html/server-status" failed (2: No such file or directory), client: 127.0.0.1, server: localhost, request: "GET /server-status?auto HTTP/1.1", host: "localhost" 2023/08/24 10:52:02 [error] 4147#4147: *11 open() "/usr/share/nginx/html/nginx_status" failed (2: No such file or directory), client: 127.0.0.1, server: localhost, request: "GET /nginx_status HTTP/1.1", host: "localhost" 2023/08/24 10:53:28 [warn] 4147#4147: *18 a client request body is buffered to a temporary file /var/cache/nginx/client_temp/0000000002, client: 172.71.98.159, server: 72.167.132.218, request: "POST /ran-admin/blog/post/add/ HTTP/1.1", host: "redaid-nigeria.org", referrer: "https://redaid-nigeria.org/ran-admin/blog/post/add/" 2023/08/24 10:58:06 [warn] 4147#4147: *25 a client request body is buffered to a temporary file /var/cache/nginx/client_temp/0000000003, client: 172.70.46.67, server: 72.167.132.218, request: "POST /ran-admin/blog/post/add/ HTTP/1.1", host: "redaid-nigeria.org", referrer: "https://redaid-nigeria.org/ran-admin/blog/post/add/" Initially I could upload smaller files and only got this error for large files (> 1MB). Now, the error shows for even files as small as 2KB. Please advice My /etc/nginx/sites-available/domainwww .conf file is server { listen 80; server_name 72.167.132.218 redaid-nigeria.org www.redaid-nigeria.org; location = /favicon.ico { access_log off; log_not_found off; } location /static/ …