Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
How can I access the IIS `REMOTE_USER` environment variable inside of an httpPlatformHandler process?
Background I am trying to set up a Django application to use Windows Authentication via IIS. The Django documentation says that you can authenticate with the REMOTE_USER environment variable set by IIS. We deploy our Django applications via httpPlatformHandler, which requires that any environment variables be declared outright in order to be passed. I'm assuming this is also the case with the REMOTE_USER because when I print os.environ.get("REMOTE_USER"), it's None. Question Does anyone know of a way to dynamically pass the REMOTE_USER environment variable through to the httpPlatform process? Is that even the right way to approach it? I'm assuming the environment variable would change for each user that attempted to access the process, am I barking up the wrong tree entirely? Things I've Tried I've tried setting an environment variable to be <environmentVariable name="REMOTE_USER" value="%REMOTE_USER%" /> But that just sets it to be literally %REMOTE_USER%, which is not what we want. I've also tried %HTTP_REMOTE_USER% which doesn't work either. I've tried setting forwardWindowsAuthToken to true, but that just adds an unrelated header that Django isn't looking for. Any help, suggestions, or anything would be greatly appreciated! -
django login doesnt redirects without refresh the page
Im a frontend developer and Im working on a login page with a backend team that uses Django. in my login.html file there is a form that gets phone number and password from user. Im getting the user inputs from the from through javascript and after validation send it to backend through a fetch request. but there is a problem. the backend guy said that:"I get the phone number and password correctly through your request and redirects the page to the new url if password and phone number was true and Django redirects correctly but the browser doesnt go to the new page and I should refresh the browser. when I refresh the browser it goes to the new page correctly". I searched in stackoverflow and checked similar Django redirect issues but none of them was my problem. I also asked Gemini but it didnt give me any good response. I provide both Django redirect code and my Javascript and html code: // ================================================ from validation: const form = document.querySelector("form"); const phoneRegEx = /^09\d{9}$/; const formData = new FormData(); form.addEventListener("submit", (event) => { event.preventDefault(); const phone_value = document.querySelector(".phone").value; const passwordValue = document.querySelector(".password").value; document.querySelector(".phone").classList.remove("notValid"); document.querySelector(".password").classList.remove("notValid"); document.querySelector(".password-empty-error").style.display = "none"; document.querySelector(".phone-empty-error").style.display = "none"; … -
Why an HTML/ JS Button is working on PC browser but not on mobile devices?
I am developing a django web app, and I have a particular button which is for purchasing a subscription through stripe. the button is working fine on PC and desktop browsers, but not on mobile devices (Iphones). I tried to enable pop-ups, but it didn't work. this is the code below: <style> .subscription-container { display: flex; justify-content: space-around; margin-bottom: 20px; } @media screen and (max-width: 768px) { .subscription-container { flex-direction: column; } } </style> <script> console.log("Sanity check!"); // Get Stripe publishable key fetch("/sciences/config/") .then((result) => { return result.json(); }) .then((data) => { // Initialize Stripe.js const stripe = Stripe(data.publicKey); // Event handler for 14-day subscription document.querySelector("#submitBtn14").addEventListener("click", () => { // Get Checkout Session ID for 14-day subscription fetch("/sciences/create-checkout-session/") .then((result) => { return result.json(); }) .then((data) => { console.log(data); // Redirect to Stripe Checkout return stripe.redirectToCheckout({sessionId: data.sessionId_14day}) }) .then((res) => { console.log(res); }); }); // Event handler for 1-day subscription document.querySelector("#submitBtn1").addEventListener("click", () => { // Get Checkout Session ID for 1-day subscription fetch("/sciences/create-checkout-session/") .then((result) => { return result.json(); }) .then((data) => { console.log(data); // Redirect to Stripe Checkout return stripe.redirectToCheckout({sessionId: data.sessionId_1day}) }) .then((res) => { console.log(res); }); }); }); </script> </head> <!DOCTYPE html> <html> <head> <meta charset="utf-8"> <meta name="viewport" content="width=device-width, initial-scale=1"> … -
How do I get the IP address of the server hosting the iframe I provided?
I have a django application, this application contains a form and i have another server which running php. In the PHP server, i created a html template which includes an form as iframe from my Django server. When i tried to get PHP server's IP Adress, Django returns me the IP of Client. But i want to server's IP adress. Can anyone to help me? I shared the middleware codes which i use for get server's IP Address below. from django.http import HttpResponseForbidden import time class IframeHostMiddleware: def __init__(self, get_response): self.get_response = get_response def __call__(self, request): allowed_hosts = [ '172.16.3.55', '111.111.111.111', 'localhost', ] headers_order = [ 'HTTP_X_REAL_IP', # Standard header for the real IP 'HTTP_X_FORWARDED_FOR', # Forwarded IP (could be a list) 'HTTP_X_CLIENT_IP', # Alternate header for client IP 'HTTP_CF_CONNECTING_IP', # Cloudflare header for client IP 'HTTP_X_CLUSTER_CLIENT_IP', # Other standard header for client IP 'HTTP_FORWARDED', # Standard forwarded header (RFC 7239) 'REMOTE_ADDR', # Fall back to the web server's connection ] ip = None for header in headers_order: value = request.META.get(header) if value: # If it's the X-Forwarded-For header, it could contain multiple IPs if header == 'HTTP_X_FORWARDED_FOR': value = value.split(',')[0] ip = value.strip() break referer = request.META.get('HTTP_X_FORWARDED_FOR') client = … -
Django channels giving error with "async_to_sync(channel_layer.send)('test_channel', {'type': 'hello'})"
I'm trying the django channels tutorial. im at the part where we are making sure that the channel layer can communicate with redis. i've already run the following commands- $ docker run --rm -p 6379:6379 redis:7 $ python3 -m pip install channels_redis # mysite/settings.py # Channels ASGI_APPLICATION = "mysite.asgi.application" CHANNEL_LAYERS = { "default": { "BACKEND": "channels_redis.core.RedisChannelLayer", "CONFIG": { "hosts": [("127.0.0.1", 6379)], }, }, } im supposed to run this-> $ python3 manage.py shell >>>import channels.layers >>>channel_layer = channels.layers.get_channel_layer() >>>from asgiref.sync import async_to_sync >>>async_to_sync(channel_layer.send)('test_channel', {'type': 'hello'}) >>>async_to_sync(channel_layer.receive)('test_channel') {'type': 'hello'}` but i keep getting error that it cannot connect with redis at line ">>>async_to_sync(channel_layer.send)('test_channel', {'type': 'hello'})" ive run the tutorial commands but it keeps on showing error that it cannot connect to redis. there are so many lines of error. i asked gpt and it told that it cannot connect to redis -
If POST request are csrf protected by default What is the purpose of @method_decorator(csrf_protect) in Django?
I think all POST, PUT, DELETE requests is CSRF protected by default in DRF, But I saw in some tutorial videos that they are using @method_decorator(csrf_protect) on some class-based views with POST and DELETE request, so I did it same. But now I'm thinking what is the purpose of doing that when these request is CSRF protected by default? @method_decorator(csrf_protect, name='dispatch') class LogoutView(APIView): def post(self, request, format=None): try: auth.logout(request) return Response({'success': 'Logged out.'}) except Exception as e: print(e) return Response({'error': 'Something went wrong.'}) -
How do I access media folder in django + tailwind
I cant use images on my webpage from my media folder in my django project here is how my directory looks: here is my code: {% load static tailwind_tags %} <!DOCTYPE html> <html lang="en"> <head> <title>Login</title> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <meta http-equiv="X-UA-Compatible" content="ie=edge"> <link rel="preconnect" href="https://fonts.googleapis.com"> <link rel="preconnect" href="https://fonts.gstatic.com" crossorigin> <link href="https://fonts.googleapis.com/css2?family=Rubik:ital,wght@0,300..900;1,300..900&display=swap" rel="stylesheet"> {% tailwind_css %} </head> <body> <div class="w-full h-[100vh] flex justify-center items-center bg-BG"> <div class="flex flex-col items-start gap-7 py-3 px-8 bg-darkBG rounded-[0.25rem]"> <h1 class="text-white text-[1.5rem] font-rubik font-[400]"> Proceed with your <br><span class="font-[500]">LOGIN!</span> </h1> <img src="/media/login_img.png" alt=""> </div> </div> </body> </html> this is my settings.py: STATIC_URL = 'static/' STATICFILES_DIRS = [BASE_DIR / '../theme/static'] MEDIA_ROOT = BASE_DIR / 'media' MEDIA_URL = '/media/' -
JWT authentication not working in django rest framework
I have the following project urls.py: urlpatterns = [ path('admin/', admin.site.urls), path('api/token/', TokenObtainPairView.as_view(), name='token_obtain_pair'), path('api/token/refresh/', TokenRefreshView.as_view(), name='token_refresh'), path('api/token/verify/', TokenVerifyView.as_view(), name='token_verify'), path("cadence/", include("cadence.urls")), ] settings.py file: INSTALLED_APPS = [ 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'cadence', 'rest_framework_simplejwt', 'rest_framework' ] REST_FRAMEWORK = { 'DEFAULT_PERMISSION_CLASSES': ( 'rest_framework.permissions.IsAuthenticated', ), 'DEFAULT_AUTHENTICATION_CLASSES': ( 'rest_framework_simplejwt.authentication.JWTAuthentication', ) } 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', ] SIMPLE_JWT = { 'AUTH_HEADER_TYPES': ('JWT',), "ACCESS_TOKEN_LIFETIME": timedelta(days=30), "REFRESH_TOKEN_LIFETIME": timedelta(days=2), } app urls.py: urlpatterns = [ path('', PlaylistViews.as_view()), path('api/playlist/get_all_playlists/', PlaylistViews.get_all_playlists, name='get_all_playlists'), ] PlaylistModel.py: class Playlist(models.Model): name = models.CharField(max_length=255) class Meta: db_table = 'playlists' PlaylistViews.py: class PlaylistViews(APIView): authentication_classes = [JWTAuthentication] permission_classes = [IsAuthenticated] def get(self, request): content = {'message': 'Hello, World!'} return Response(content) def post(self, request): try: serializer = PlaylistSerializer(data=request.data) if serializer.is_valid(): serializer.save() return Response({'message': 'Playlist added successfully.', 'data': serializer.data}, status=status.HTTP_201_CREATED) return Response({'message': 'Failed to add playlist.', 'errors': serializer.errors}, status=status.HTTP_400_BAD_REQUEST) except Exception as error: return Response({'error': str(error)}, status=status.HTTP_500_INTERNAL_SERVER_ERROR) @api_view(['GET']) def get_all_playlists(request): try: playlists = Playlist.objects.all() serializer = PlaylistSerializer(playlists, many=True) return Response(serializer.data) except Exception as error: return Response({'error': str(error)}, status=status.HTTP_500_INTERNAL_SERVER_ERROR) When i call the following api: http://localhost:8000/api/token/, i am getting the token, and when i use it in any other api call i get the following error: "Authentication credentials were not provided." … -
Why does django continue to use the old admin namespace alongside the new custom admin url?
I'm developing a django app. I wish to change the admin url with an environment variable. Here is how I retrieve it in urls.py: import os admin_url = os.getenv('SUPERUSER_URL', 'custom-admin/') # Default is 'custom-admin/' if no key is set # Also, the environment variable has a slash at the end In the urlpatterns it is defined as such: urlpatterns = [ path(admin_url, admin.site.urls), # more views... ] Whenever I try to access my admin panel, I can do so with no issue using the new name. But the issue is two things: Once I have accessed the admin panel, anytime I try to access a model linked to the panel, it will redirect to the url that django's original admin namespace associates it self with. E.g. admin/users instead of custom-admin/users The second issue is that I can still access the admin panel using the original name 'admin' I am not using any custom admin template, I simply have defined a bunch of models to be used with the admin site in admin.py. Here's a snippet of my admin.py file, in case you need to see how I'm implementing them: from django.contrib import admin from .models import User, Foo from django.contrib.auth.admin … -
Deploying Django Channel Application with Nginx and Daphne
I am trying to deploy a Django Channel Application with Daphne and Nginx. I am getting 502 Bad Gateway error when I try to access the application from a Browser. I am using AWS EC2 Ubuntu instance to host the web application. Following is my nginx config file. upstream channels-backend {server localhost:8000;} server { listen 80; server_name 52.77.249.57; location = /favicon.ico { access_log off; log_not_found off; } location / { proxy_pass http://channels-backend; proxy_http_version 1.1; proxy_set_header Upgrade $http_upgrade; proxy_set_header Connection "Upgrade"; proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for; proxy_set_header Host $http_host; proxy_redirect off; } } Following is my daphne.service file. [Unit] Description=daphne daemon Requires=daphne.socket After=network.target [Service] Type=simple User=root WorkingDirectory=/home/ubuntu/project ExecStart=/home/ubuntu/project/env/bin/daphne -b 0.0.0.0 -p 8000 chat_service.asgi:application [Install] WantedBy=multi-user.target Do you have any idea to solve the issue ? -
post method not allowed using Django REST Framework API Key
def get_permissions(self): """ Override the default permissions for the view. """ try: if 'bot' in self.request.path: print(f'post cheque') return [HasAPIKey()] # Return the custom permission classes for the current action. return [permission() for permission in self.serializers_permission_by_action[self.action][1]] except KeyError: # If the current action is not found in serializers_permission_by_action, # default to using the standard permissions. return super().get_permissions() api_key1 = 'YOtxWIRR.OGgGvTaND1OEKJYvDtLAmBnR8tFFFTxz' headers = {'X-Api-Key': api_key1 } Method post not working in the DRF API Key i am getting the results for get method but for post method it is saying method not allowed -
Django multi language
I want my Django site to be available in both English and Azerbaijani languages. This is how I wrote the codes for it. However, I do not know what is true. Is there an alternative? Does this method affect the speed of the site? in my view : def change_Lang(request): referer = request.META.get('HTTP_REFERER') lang = request.GET.get("pylang", "en") pylang = request.session.get("pylang", None) if lang != "az" and lang != "en": lang = "en" if pylang == None: request.session["pylang"] = lang if pylang != lang: request.session["pylang"] = lang if referer: return HttpResponseRedirect(referer) return redirect("home") in my templatetag: @register.simple_tag def pylang(value, en, az): if value == "en": return en elif value == "az": return az else: return en in my template : {% load pylang %} {% pylang request.session.pylang "About - PyTerminator.com" "Haqqımızda - PyTerminator.com" %} I want to know if this method has a negative effect on the speed of the site? What is the alternative? Suggest better options. Thanks in advance) -
Django renaming log level to 3 character format
In python, using logging module, the log level format can be changed with: logging.addLevelName(logging.DEBUG, 'DBG') How can I do it in Django? My (working) logging configuration in settings.py: LOGGING: dict[Any, Any] = { 'version': 1, 'formatters': { 'app_log_format': { 'format': '%(asctime)s [%(levelname)s] %(message)s', 'datefmt': '%Y-%m-%d %H:%M:%S', }, }, 'handlers': { 'file': { 'level': 'DEBUG', 'class': 'logging.FileHandler', 'filename': current_log_path, 'formatter': 'app_log_format', }, }, 'loggers': { '': { 'handlers': ['file'], 'level': 'INFO', 'propagate': True, }, }, } Thanks -
How To Order Alphanumeric CharFields in Django
i have a model for menu items that has a CharField for the numbers as some of them have sub variants that have a letter suffix fx. 25, 26, 27, 27a, 28... how do i order the objects after the menu number with the suffix taken into account after? so this list [1g, 14, 2g, 27a, 27, 33, 33b] would be [1g, 2g, 14, 27, 27a, 33, 33b] when just using order_by it defaults to the first number so [27, 4 0, 27a] comes out as [0, (2)7, (2)7a, 4] -
Django exception, NoReverseMatch
I'm learning django on a small project called BlogPost from a python's book. This is a very simple project on its own - user can add a post with title and text. I'm trying to add functionality of editting existed entries via views.py function called "edit_entry" and i receive exception which i can't overcome: NoReverseMatch at /edit_entry/6/ Request URL: http://127.0.0.1:8000/edit_entry/6/ Raised during: blogs.views.edit_entry Reverse for 'edit_entry' with arguments '('',)' not found. 1 pattern(s) tried: ['edit_entry/(?P<object_id>[0-9]+)/\Z'] Does anybody know what could be a proble? Here is my code: models.py from django.db import models from django.contrib.auth.models import User # Create your models here. class BlogPost(models.Model): """Create data model""" topic = models.CharField(max_length=100) text = models.TextField() date_added = models.DateTimeField(auto_now_add=True) class Meta: ordering = ['-date_added'] def __str__(self): return self.topic forms.py from django.forms import ModelForm from .models import BlogPost class NewEntryForm(ModelForm): class Meta(): model = BlogPost fields = ['topic','text'] labels = {'topic':'Topic', 'text': 'Text'} urls.py from django.urls import path from . import views app_name = 'blogs' urlpatterns = [ path('', views.index, name='index'), path('entries/', views.entries, name='entries'), path('new_entry/', views.new_entry, name='new_entry'), path('edit_entry/<int:object_id>/', views.edit_entry, name='edit_entry')] views.py from django.shortcuts import render, redirect from django.http import request from .models import BlogPost from .forms import NewEntryForm # Create your views here. def index(request): … -
Navigating through apps in django
After spending one full day trying to fix this problem, I finally ask here. Sorry if this is obvious to the Django purists! I have this project with (currently) 2 apps, called intro and rules. The intro app contains a button that should redirect to rules. Currently, for some reason that I cannot understand, clicking the button redirects to the intro page itself. Does someone see the mistake here? Following are the relevant code parts: HTML template for the button: <div class="button-container" action="{% url 'rules:index' %}"> <form class = "Demo_questionnaire""> {% csrf_token %} <button type="submit">New game</button> </form> </div> Project settings: INSTALLED_APPS = [ "django.contrib.admin", "django.contrib.auth", "django.contrib.contenttypes", "django.contrib.sessions", "django.contrib.messages", "django.contrib.staticfiles", 'intro', 'rules', ] URL configuration for the project: urlpatterns = [ path("admin/", admin.site.urls), path("intro/", include("intro.urls", namespace="intro")), path("rules/", include("rules.urls", namespace="rules")), ] URL configuration for intro: app_name = "intro" urlpatterns = [ path("", views.index, name="index"), ] URL configuration for rules: app_name = "rules" urlpatterns = [ path("", views.index, name="index"), ] Thank you in advance, and sorry if the answer is obvious :( -
Django: using two related fields / foreign keys at once
I have three models: class Team(models.Model): team_id = models.AutoField() team_name = models.CharField() class Game(models.Model): game_id = models.AutoField() home_team = models.ForeignKey(Team, on_delete=models.CASCADE) away_team = models.ForeignKey(Team, on_delete=models.CASCADE) class TeamBoxScore(models.Model): game = models.ForeignKey(Game, on_delete=models.CASCADE, related_name='game_boxscore') team = models.ForeignKey(Team, on_delete=models.CASCADE, related_name='team_boxscore') # some stats here What I want to do is, for every Game instance, access the TeamBoxScore that matches both the Game instance and the Team instance referenced by home_team/away_team. Is there a way that I can have game.home_team.team_boxscore reference only the boxscore for that game_id? Or, conversely, can I specify which game.game_boxscore I want to return (the one that matches home_team or the one that matches away_team)? I want to minimize queries and avoid long iterative solutions. I've tried annotating the fields from each TeamBoxScore instance to every Game (referencing the game_boxscore related field), but that ends up doubling the size of the queryset and placing the values from the home boxscore and the away boxscore in separate instances. I've tried going through the team_boxscore related field, but that returns every boxscore for that team (game.home_team.team_boxscore). I've further tried to groupby these annotated values and just return the sum, but this is both inelegant and takes too long (and could be wrong!) … -
Django believes that there is a "SuspiciousFileOperation". This is not true
Django has a belief that there is a SuspiciousFileOperation error when this just is not the case. My fully reproducible setup is below. It continues to return this error despite the fact that: I have installed and set up Whitenoise correctly, as well as in the Middleware and InstalledApps, in the settings.py filw, as well as the following: INSTALLED_APPS = [ 'django.contrib.staticfiles', ] MIDDLEWARE = [ "whitenoise.middleware.WhiteNoiseMiddleware", ] STATIC_ROOT = BASE_DIR / "staticfiles" STATIC_URL = 'static' STATICFILES_DIRS = [ BASE_DIR / "static" ] Despite the fact that I have correctly set up the static config in my root urls.py folder, as follows: from django.conf import settings from django.conf.urls.static import static from django.views.static import serve urlpatterns = [ ...... ] # Only for development. Do not use this in production. if settings.DEBUG: urlpatterns += static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT) urlpatterns += static(settings.STATIC_URL, document_root=settings.STATIC_ROOT) My directory is as follows: <PROJECTNAME> <ROOTFOLDER> settings.py urls.py <APP NAME> static file.css static libraries css image-video-hero.css staticfiles libraries css image-video-hero.css Therefore, there is no reason as to why Django should have an issue with this, however, when I run the command of python manage.py collectstatic command, I still get the trace back of: File "<FILEPATH>\<PROJECTNAME>\.venv\Lib\site-packages\django\utils\_os.py", line 31, in safe_join raise … -
Django, exists subquery always returns False
I faced an issue, that my subquery returns False, even it should return True. from wagtail.models import WorkflowState, Page, Workflow import pytest def test_filter_pages(user): page = PageFactory.create( owner=user, live=False, latest_revision_created_at=timezone.now(), ) WorkflowState.objects.create( content_type=ContentType.objects.get_for_model(Article), base_content_type=ContentType.objects.get_for_model(Page), object_id=str(page.pk), workflow=Workflow.objects.get(name="Moderators approval"), status=WorkflowState.STATUS_IN_PROGRESS, requested_by=user, ) workflow_states = WorkflowState.objects.filter( status=WorkflowState.STATUS_IN_PROGRESS, object_id=str(OuterRef("pk")) ) queryset = ( Page.objects.select_related("owner", "latest_revision") .annotate(workflow_state_status=Exists(workflow_states)) .filter(owner=user) ) lists_ids = [ page.id for page in queryset if page.workflow_state_status ] assert lists_ids != 0 In this test there is only one page, which should have workflow state. But test fails with list_ids = 0. What is wrong here? Moreover, when I try to replace workflow_state_status with simple WorkflowState.objects.filter( object_id=self.pk, status=WorkflowState.STATUS_IN_PROGRESS, ).exists() everything works correct (except database queries) -
Django stopped updating static files
Django does not upload static files Hey guys, I am head to you because I have a problem I can’t fix. I am on localhost and Django does not apply modifications I have made on static files, although the file is changed. So to start here what I have done so far: clearing browsers caches rebooting the server step 1&2 of best answer: stackoverflow.com/questions/27911070/django-wont-refresh-staticfiles changing browser deleting pycache files Nothing seems to work, if you had an explanation on how to fix this but mostly WHY this happens, would be so nice ! 😊 -
DJANGO Compute number of hours the user spend per day
I have Clocking table in database. I wanted to count the users' time spend per day. For example 2024-03-21, user 1 spend 6.8 hours, the next day he spend n number of hours and so on (['6.8', 'n', ... 'n']) user date timein timeout 1 2024-03-21 10:42 AM 12:00 PM 1 2024-03-21 01:10 PM 06:00 PM 1 2024-03-22 01:00 PM 05:47 PM ... ... ... ... This is my models.py class EntryMonitoring(models.Model): user = models.ForeignKey('User', models.DO_NOTHING) timein = models.CharField(max_length=15, blank=True, null=True) timeout = models.CharField(max_length=15, blank=True, null=True) date = models.DateField(null=False) I wanted to get the list of hours spend per day, that would be really useful for me in plotting charts. Thank you in advance! -
How to restart gunicorn when used with config file
I am using gunicorn to server a django application. I am using a config file and starting gunicorn using the command gunicorn -c config/gunicorn/dev.py I want to know how to restart gunicorn. i am not able to use sudo systemctl restart gunicorn command which gives the below message: Failed to restart gunicorn.service: Unit gunicorn.service not found. I am very sure that gunicorn is running as i am able to use the application on the web. What is the way to restart gunicorn in this case. Below is the config file of gunicorn: # Django WSGI application path in pattern MODULE_NAME:VARIABLE_NAME wsgi_app = "someapp.wsgi:application" # The granularity of Error log outputs loglevel = "debug" # The number of worker processes for handling requests workers = 2 # The socket to bind bind = "0.0.0.0:8000" # Restart workers when code changes (development only!) reload = True # Write access and error info to /var/log accesslog = errorlog = "/var/log/gunicorn/dev.log" # Redirect stdout/stderr to log file capture_output = True # PID file so you can easily fetch process ID pidfile = "/var/run/gunicorn/dev.pid" # Daemonize the Gunicorn process (detach & enter background) daemon = True -
Python code to connect to FTP /convert my code in way that it uses FTP instead of SFTP
please help to write code to connect ftp using python download fresh files from specfic directory load those file in Mysql database ,mark them processed after downloading file from ftp ,after loading them into mysql database If any one can provide python script for this -
What are the key technologies and concepts involved in backend web development? [closed]
Key Technologies: Programming Languages: Backend development can be done using various languages, such as: Node.js: JavaScript runtime built on Chrome's V8 engine, popular for its non-blocking, event-driven architecture. Python: Known for its simplicity and readability, often used with frameworks like Django and Flask. Java: Offers platform independence and is commonly used in enterprise applications. Frameworks: Frameworks provide a structured way to build web applications. Some popular backend frameworks include: Express.js (Node.js): Minimalistic and flexible, ideal for building APIs and web apps. Django (Python): High-level framework for rapid development, follows the DRY (Don't Repeat Yourself) principle. Spring (Java): Comprehensive framework for Java, offering features like dependency injection and MVC architecture. Databases: Backend development involves interacting with databases to store and retrieve data. Common databases include: SQL Databases: Such as MySQL, PostgreSQL, and SQLite, used for structured data. NoSQL Databases: Such as MongoDB and Cassandra, used for unstructured or semi-structured data. Key Concepts: RESTful APIs: Representational State Transfer (REST) is a design pattern for creating scalable web services, commonly used in backend development. Authentication and Authorization: Implementing secure user authentication and authorization mechanisms to protect backend resources. Server-Side Rendering (SSR) vs. Client-Side Rendering (CSR): Understanding the difference between rendering techniques and when … -
Is it possible to add a "InputField" in ChoiceField in Django?
I'm in the process of developing a form that aligns with a database model. One of the fields in this form requires users to select from a range of options. Initially, I implemented this using Django's ChoiceField. However, I'm exploring the possibility of allowing users to input their own option if it's not available in the predefined choices. Is there a way to integrate this?