Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Why can't I deploy project (passenger wsgi)
When I change the passenger_wsgi.py to import <project_name>.wsgi application = <project_name>.wsgi.application I encounter with below error: Web application could not be started by the Phusion Passenger(R) application server. Please read the Passenger log file (search for the Error ID) to find the details of the error. I change wsgi.py in project to: os.environ["DJANGO_SETTINGS_MODULE"] = "project.settings" -
Django : Locally save an instance of a Model
Using signals, I try to track the difference between the old instance of an object and the new instance when the Model is saved. I tried this : But logically in the model_post_init_handler method, it's a reference of the object that is stored in __original_instance. So, instance.__original_instance.is_used and instance.is_used will always be the same. How could I store a "snapshot" of the object when he is initiated, so that I will be able to track what is edited ? -
Integrating Microsoft Forms Authentication in Python Django: Troubleshooting Terminal Error
To integrate the Microsoft Forms authentication flow into my Python Django project for accessing various forms URLs and storing form details and responses, I'm employing the provided MS Forms authentication code within my project's backend. Additionally, I've configured my project to run within a Docker container. The MS Forms authentication code snippet, enclosed below, outlines the process: import json import os import django.core.management.base import requests from azure.identity import DefaultAzureCredential, InteractiveBrowserCredential, AzureCliCredential # Custom Django command definition class Command(django.core.management.base.BaseCommand): def handle(self, *args, **options): # Select one of the credential objects to obtain an access token # cred = AzureCliCredential() # e.g., via `az login` cred = InteractiveBrowserCredential() # cred = DefaultAzureCredential() # Request an access token with the specified scope scope = "https://forms.office.com/.default" token = cred.get_token(scope) print("===============================") print(f"{token.expires_on = }") print("===============================") tenantId = "tenant id" groupId = "group id" formId = "form id" # Provide the access token in the request header headers = {"Authorization": f"Bearer {token.token}"} # Retrieve all Forms for a Microsoft 365 Group url = f"https://forms.office.com/formapi/api/{tenantId}/groups/{groupId}/forms" list_response = requests.get(url, headers=headers) print(f"All Forms: {list_response.json()}") # Retrieve details for a specific group form url = f"https://forms.office.com/formapi/api/{tenantId}/groups/{groupId}/forms('{formId}')" list_response = requests.get(url, headers=headers) print(f"Form Detail: {list_response.json()}") # Retrieve questions from a group form … -
How do I write tests for my django-extensions cron job?
I have a cron job in my Django app that's defined as a MinutelyJob (from django-extensions). How do I write tests for the job? The module documentation is quite sparse, and doesn't tell me how to call the job from code as opposed to the command line. I don't want to write test code that depends on undocumented interfaces. Alternatively, should I reimplement the job using a different module? I only have the one job so Celery is a bit heavyweight for my use case. -
How can I customize Django Rest Framework documentation without using decorators?
I'm currently working on a Django project and utilizing Django Rest Framework (DRF) for building APIs. I've integrated drf-pectacular for automatic API documentation generation, but I'm finding that using decorators to customize the documentation is making my codebase messy. I'm interested in exploring alternative approaches to customize my DRF documentation without relying heavily on decorators. Could someone provide guidance on how to achieve this? I'm specifically looking for methods or techniques that allow me to customize the documentation while keeping my code clean and maintainable. Any suggestions, examples, or best practices would be greatly appreciated. Thank you! -
How to Handle and Send Various File Types (Images, Videos, Audios, PDFs, Documents) in a Django Chat App Using WebSockets and Django REST Framework
I'm working on a chat application where I need to handle and store various types of files such as images, videos, audios, PDFs, and documents using Django and Django REST framework. I have a WebSocket consumer with events like connect, disconnect, and receive. In the receive event, I'm trying to handle video files. Here's a simplified version of my code: # consumers.py async def video(self, event): stream = File(BytesIO(event['file']), name=event['file_name']) data = JSONParser().parse(stream) event['file'] = data await self.send(text_data=json.dumps(event)) # serializers.py class MessageSerializer(serializers.ModelSerializer): image = Base64ImageField(required=False) file = MyBase64FileField(required=False) class Meta: model = ChannelMessages fields = '__all__' I'm facing issues with sending video files over the WebSocket. What changes do I need to make in my code to handle video files properly and send them over the WebSocket? Additionally, I'm looking for a solution that allows me to handle and send other file types like images, audios, PDFs, and documents as well. -
How to serve images from backend to frontend
I have an application with following three different docker containers:- Frontend(react) Back-end(django) Nginx for serving static files from frontend, I am trying to access nginx website in Kubernetes (minikube). all other data is being served from backend container but only image is not being sent Can someone please help. debug is true and MEDIA_URL = ‘/media/’ MEDIA_ROOT = os.path.join(BASE_DIR ,“/app/media”) I have kept the name of django app as django-service, should I change the following lines in setttings.py file to django-service as well ? ROOT_URLCONF = 'backend.urls' WSGI_APPLICATION = 'backend.wsgi.application' here is entrypoint.sh file with same name #!/bin/sh gunicorn backend.wsgi:application --bind 0.0.0.0:8000 and following is deploment resources # Django Deployment apiVersion: apps/v1 kind: Deployment metadata: name: django-app spec: replicas: 1 selector: matchLabels: app: django-app template: metadata: labels: app: django-app spec: containers: - name: django-container image: ash414/e-cart-backend:v1.0 ports: - containerPort: 8000 # Django Service apiVersion: v1 kind: Service metadata: name: django-service labels: app: django-app spec: selector: app: django-app ports: - protocol: TCP port: 8000 targetPort: 8000 # Nginx Deployment apiVersion: apps/v1 kind: Deployment metadata: name: nginx-app labels: app: nginx-app spec: replicas: 1 selector: matchLabels: app: nginx-app template: metadata: labels: app: nginx-app spec: containers: - name: nginx-container # Not working images # … -
How to implement preview page with files Django?
I have my News model: class News(models.Model): subject = models.CharField(max_length=30) text = models.TextField() created = models.DateTimeField(auto_now_add=True) I also have File model to store files and NewsFile model to connect models to each other: class File(models.Model): file = models.FileField( 'файл' ) class NewsFile(models.Model): file = models.ForeignKey( File, on_delete=models.CASCADE, verbose_name='файл', related_name='news_files' ) news = models.ForeignKey( News, on_delete=models.CASCADE, verbose_name='новость', related_name='files' ) Here is my news form: class MultipleFileInput(forms.ClearableFileInput): allow_multiple_selected = True class MultipleFileField(forms.FileField): def __init__(self, *args, **kwargs): kwargs.setdefault("widget", MultipleFileInput()) super().__init__(*args, **kwargs) def clean(self, data, initial=None): single_file_clean = super().clean if isinstance(data, (list, tuple)): result = [single_file_clean(d, initial) for d in data] else: result = single_file_clean(data, initial) return result class NewsForm(forms.ModelForm): files = MultipleFileField(required=False) class Meta: model = News fields = ('subject', 'text') I want to make a page with a preview of the news and buttons to publish or edit the news. I have started implementing publish button, I can't pass files with form. My view: def form_valid(self, form): files = form.cleaned_data.get('files') if self.request.GET.get('save') == 'true': res = super().form_valid(form) for file in files: file_obj = File.objects.create(file=file) NewsFile.objects.create(news=self.object, file=file_obj) return res img_files = [] non_img_files = [] for file in files: if file.name.split('.')[-1] in settings.IMAGE_FORMATS: img_files.append(file) else: non_img_files.append(file) images = [] for file in img_files: … -
Google Authentication Not Appearing in Django Project
Body: I am trying to set up Google authentication in my Django project using django-allauth, but the Google login option is not appearing on my login page. I suspect I might be missing a configuration step or setting. I have confirmed the site ID is correct by checking the link: http://127.0.0.1:8000/admin/sites/site/3/change/ Could someone help me identify what I might be missing or doing wrong? Here are the relevant parts of my settings.py: SOCIALACCOUNT_PROVIDERS = { "google": { "app": [ { "client_id": "myid", "secret": "mysecret", }, ], "SCOPE": [ "profile", "email", ], "AUTH_PARAMS": { "access_type": "online", }, } } SITE_ID = 3 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', 'allauth.account.middleware.AccountMiddleware', 'livereload.middleware.LiveReloadScript', ] TEMPLATES = [ { 'BACKEND': 'django.template.backends.django.DjangoTemplates', 'DIRS': [TEMPLATES_DIR], 'APP_DIRS': True, 'OPTIONS': { 'context_processors': [ 'core.views.site_settings', 'django.template.context_processors.debug', 'django.template.context_processors.request', 'django.contrib.auth.context_processors.auth', 'django.contrib.messages.context_processors.messages', ], }, }, ] LOGIN_REDIRECT_URL = 'login' # Redirect after login LOGOUT_REDIRECT_URL = 'home' # Redirect after logout -
Speeding up Django's total record count calculation for a site with 20 million records MySQL
I've encountered a problem with my Django website. Given that my database contains more than 20 million records, the operation of counting the total number of data (count) becomes extremely slow. I am using the following queries: company_count_query = f"SELECT COUNT(DISTINCT cs.OGRN) AS total_companies {company_from_clause} WHERE {company_match_condition} {email_condition} {capital_condition} {date_condition} {company_okved_condition}" ip_count_query = f"SELECT COUNT(DISTINCT ip.OGRNIP) AS total_ips {ip_from_clause} WHERE {ip_match_condition} {imail_condition} {ip_okved_condition}" How can I optimize these queries or use other methods to speed up the calculation of the total number of records? Thank you for your help! I tried to optimize the query structure by adding indexes to the columns on which filtering is performed, hoping to improve the performance of the counting operation. I expected that this would reduce the query execution time and speed up the data processing. However, in practice, the query execution time remained high and the counting operation still takes too long. -
How do I retrieve more than 10k document in elasticsearch?
I'm completely new to ELK and trying to retrieve 40k documents. the search_after depends on the previous batch of results and wasn't useful for me. GET twitter/_search { "query": { "match": { "title": "elasticsearch" } }, "search_after": [1463538857, "654323"], "sort": [ {"date": "asc"}, {"tie_breaker_id": "asc"} ] } how to retrieve more than 10k documents? -
Django reverse ForeignKey returns None
I have Student and Mark models in different apps of one project. # project/study # models.py class Mark(models.Model): ... student = models.ForeignKey( "students.Student", on_delete=models.PROTECT, related_name="marks", related_query_name="mark", ) # project/students # models.py class Student(models.Model): ... # views.py class StudentDetailView(DetailView): queryset = Student.objects.prefetch_related("marks") template_name = "students/one_student.html" context_object_name = "student" # one_student.html ... <p>{{ student.marks }}</p> ... Output of html is "study.Mark.None" That is my problem. I tried making ManyToOneRel field on student, select_related, making custom view func, but that does not help. Reverse ForeignKey brings None. I watched related questions - can't understand answers, because they are unrelated directly to my situation. I'm expecting to get all Student's marks. What am I doing wrong? -
Django admin inlines that has multilanguage field , TabbedTranslationAdmin does not work correctly
i have a django project, i use django-modeltranslation for translation fields. it have two model with one-to-many relation and i use django admin with inline for @admin.register(News) class NewsAdmin(nested_admin.NestedModelAdmin, TabbedTranslationAdmin): inlines = (NewsImageInline,) and image inline is: class NewsImageInline(nested_admin.NestedTabularInline,TranslationTabularInline ): model = NewsImage extra = 1 but in admin, tabularinline not work and show all of fields in one row -
Nginx is active but I don't see static files
I have a django project. Settings.py: STATIC_URL = 'static/' STATIC_ROOT = 'static' MEDIA_URL = '/media/' MEDIA_ROOT = BASE_DIR / 'media' I've made collectstatic and everything worked fine. Now static folder on my server with all the files. Nginx: enter image description here I had porblems with nginx, cause I changes name in sites_available and it started to give errors, so I reinstalled it and now everything is fine: nginx.service - A high performance web server and a reverse proxy server Loaded: loaded (/lib/systemd/system/nginx.service; enabled; vendor preset:> Active: active (running) since Wed 2024-05-01 14:47:13 UTC; 11min ago Docs: man:nginx(8) Process: 6843 ExecStartPre=/usr/sbin/nginx -t -q -g daemon on; master_proce> Process: 6844 ExecStart=/usr/sbin/nginx -g daemon on; master_process on; (c> Main PID: 6845 (nginx) Tasks: 2 (limit: 1026) Memory: 3.1M CPU: 60ms CGroup: /system.slice/nginx.service ├─6845 "nginx: master process /usr/sbin/nginx -g daemon on; master> └─6846 "nginx: worker process" "" "" "" "" "" "" "" "" "" "" "" ""> May 01 14:47:13 23210 systemd[1]: nginx.service: Deactivated successfully. May 01 14:47:13 23210 systemd[1]: Stopped A high performance web server and a r> May 01 14:47:13 23210 systemd[1]: Starting A high performance web server and a > May 01 14:47:13 23210 systemd[1]: Started A high performance … -
403 Error when renewing Let's Encrypt Certbot using Django and Apache. I have 6 days to renew
When running the certbot renew command I first change my firewall permissions to allow connections on port 80, I put Cloudflare into Development Mode, then I run the renewal command. However this time I received a 403 Forbidden error trying to access the url example.com/.well-known/acme-challenge/funnylettersandstuff. I don't remember certbot needing this url but I only do this once a year for just one of my websites because for whatever reason I never got this configuration to auto renew. So here I am now trying to figure out what is causing this error. I have reviewed my virtual host configuration file and I cannot see any reasons this could be occuring. I also have modsecurity enabled but I doubt that's the issue since I cannot find any related errors in the modsecurity logs. Do I need to do something to Django to make this work? Certbot failed to authenticate some domains (authenticator: apache). The Certificate Authority reported these problems: Domain: example.com Type: unauthorized Detail: During secondary validation: 2a06:98c1:3120::1: Invalid response from http:// example.com/.well-known/acme-challenge/funkylettersandnumbers: 403 sudo iptables -P INPUT ACCEPT sudo iptables -P FORWARD ACCEPT sudo iptables -P OUTPUT ACCEPT sudo iptables -t nat -F sudo iptables -t mangle -F sudo iptables … -
Python Celery route task using hostname
I'm currently utilizing Celery for task management within my application, and I'm facing a challenge regarding task distribution to specific workers based on their unique hostnames. In my use case, I'm deploying multiple worker containers for a particular application. These containers are required to connect to various VPNs for specific requests or processing tasks. The challenge arises from the dynamic nature of container deployment, where each container's hostname is unique and dynamically assigned and it is stored on database with metadata information to be used by the application to select which worker should run a particular task. Given this scenario, I'm seeking a solution to send tasks directly to a specific worker based on it's hostname. This would ensure efficient task distribution, even in dynamic deployment environments where workers may connect to different VPNs dynamically and have different hostname each time. The logic to select the worker is already in place. The logic to create container/worker is already in place. The logic to requeue a task that is sorted to an invalid queue is already in place. Scenario Workers Worker01 (hostname=a333) connected to VPN 1 Worker02 (hostname=b999) connected to VPN 2 Worker03 (hostname=c777) connected to VPN 3 Worker04 (hostname=c444) connected … -
Why my Elasticsearch request doesn't show any hits?
I have dockerized Django project. I want to use Elasticsearch, so I choosed django-elasticsearch-dsl. My steps were: In my Django project's settings file (settings.py), I configured the Elasticsearch connection settings. ELASTICSEARCH_DSL = { 'default': { 'hosts': ["http://localhost:9200"], }, } Created a file named documents.py my Django app. In this file, I defined Elasticsearch documents that correspond to my Django models. from django_elasticsearch_dsl import Document from django_elasticsearch_dsl.registries import registry from .models import Filmwork @registry.register_document class FilmWorkDocument(Document): class Index: name = 'film' settings = {'number_of_shards': 1, 'number_of_replicas': 0} class Django: model = Filmwork fields = ['title', 'description'] So then I indexed data from my Django model into Elasticsearch by using command python3 manage.py search_index --rebuild. I used this command outside docker, it showed: File "/Users/ArtemBoss/Desktop/artem_yandex_repo/venv/lib/python3.10/site-packages/psycopg2/__init__.py", line 122, in connect conn = _connect(dsn, connection_factory=connection_factory, **kwasync) django.db.utils.OperationalError: could not translate host name "database" to address: nodename nor servname provided, or not known At the same time, when I'm trying to index data inside django container it shows: File "/usr/local/lib/python3.10/site-packages/elastic_transport/_node/_http_urllib3.py", line 202, in perform_request raise err from None elastic_transport.ConnectionError: Connection error caused by: ConnectionError(Connection error caused by: NewConnectionError(<urllib3.connection.HTTPConnection object at 0x7f9150762b60>: Failed to establish a new connection: [Errno 111] Connection refused)) Anyway Index was successfully … -
CSRF verification failed. Request aborted. Origin checking failed
Here is my setup: localhost (Windows 11) - Nginx listening on port 80 and 443, 80 is NOT automatically redirected to 443 each proxy_passed to http://wsgi-server where wsgi-server=127.0.0.1:8080 - waitress_wsgi running as a service on port 8080 Here is Django config: <!-- email_test.html --> <!-- ... --> <form action="{% url 'identity:email_test' %}" method="post"> {% csrf_token %} {{ email_form }} {% translate 'Send email' as submit_translated %} <!-- I use django_bootstrap5 --> {% bootstrap_button button_type="submit" content=submit_translated extra_classes='w-100'%} </form> # settings.py ---------- MIDDLEWARE = { # ... 'django.middleware.csrf.CsrfViewMiddleware', # ... } # forms.py ------------- class EmailTestForm(forms.Form): email = forms.EmailField( # help_text=password_validation.password_validators_help_text_html(), label=_('Email'), max_length=128, ) # views.py ------------- def email_test(request): context = {} context.update(template_globals()) if request.method == "POST": email_form = EmailTestForm(request.POST) if email_form.is_valid(): email_obj = EmailMessage(subject='Hello', body='Email body', from_email='noreply@nutrihub.hnet', to=[email_form.cleaned_data.get('email')]) email_obj.send(fail_silently=False) else: email_form = EmailTestForm() context['email_form'] = email_form return render(request, "identity/email_test.html", context) Here are my test resuts when I visit the URL on browser: py manage.py runserver (default port 8000), browser http://127.0.0.1:8000, empty settings.CSRF_TRUSTED_ORIGINS: Works fine. Browser http://localhost or http://127.0.0.1 or https://localhost or https://127.0.0.1 with individual entry not in settings.CSRF_TRUSTED_ORIGINS: CSRF error. Browser http://localhost or http://127.0.0.1 or https://localhost or https://127.0.0.1 with individual entry not settings.CSRF_TRUSTED_ORIGINS: Works fine. Browser https://mymachine.net with this entry in … -
Import Error while using python manage.py migrate command
Recently, i forked some source code from github to use as a basis for a project that i'm using to learn Django. As per the deployment instructions, i tried to use this command for the database in my terminal: python manage.py migrate Yet i keep getting this error: ImportError: cannot import name 'force_text' from 'django.utils.encoding' (C:\Users\afric.virtualenvs\Online-Examination-System-aZtpAN9a\lib\site-packages\django\utils\encoding.py) the error stems from the terminal trying to proccess this command: from django.utils.encoding import force_bytes, force_text, DjangoUnicodeDecodeError can anyone please help me solve this? -
What's the best approach to keeping data consistent in a django-based app used in parallel by three or four users?
I'm making a Django app using a postgresql database for a family who need to coordinate their grocery purchases. Say one person has on their mobile device a full list of the groceries and is in the supermarket, buying and ticking each item off the list. His partner decides to stop at another shop and begins buying the items on the same list. How would you approach ensuring that they don't buy double or, more importantly, that they don't end up messing up the data entirely? A simple first-come, first-served lock, giving the second user only read-only rights? Or is there a more flexible way? And if the best way is a lock, how much does postgresql do for you? -
Django: Pass model ID to url using bootstrap modal
I'm trying to create a delete confirmation dialog using bootstrap 5 modals in my Django project. {% extends 'base.html' %} {% block content %} <div class="col-md-6 offset-md-3"> {% if messages %} {% for message in messages %} <div class="alert alert-success alert-dismissible fade show" role="alert"> {{ message }} <button type="button" class="btn-close" data-bs-dismiss="alert" aria-label="Close"></button> </div> {% endfor %} {% endif %} </div> <h1>Service Overview</h1> <br/> <div class="d-grid gap-2 justify-content-md-end"> <a class="btn btn-primary" href="{% url 'add_service' %}">Add service</a> <br/> </div> <table class="table table-hover table-bordered"> <thead class="table-secondary"> <tr> <th class="text-center" scope="col">#</th> <th scope="col">Name</th> <th scope="col">Description</th> <th class="text-center" scope="col">Cost</th> <th class="text-center" scope="col">Created at</th> <th class="text-center" scope="col">Updated at</th> <th class="text-center" scope="col">Status</th> <th class="text-center" scope="col">Actions</th> </tr> </thead> <tbody> {% for service in services %} <tr> <td class="text-center">{{ service.id }}</td> <td>{{ service.name }}</td> <td>{{ service.description}}</td> <td class="text-center">{{ service.cost }} AED</td> <td class="text-center">{{ service.created_date }}</td> <td class="text-center">{{ service.updated_date }}</td> {% if service.status == "ACTIVE" %} <td class="text-center"> <span class="badge text-bg-success" style="font-size:0.7em;">{{ service.status }}</span> </td> {% elif service.status == "INACTIVE"%} <td class="text-center"> <span class="badge text-bg-danger" style="font-size:0.7em;">{{ service.status }}</span> </td> {% endif %} <td class="text-center"> <!--Update--> <a href="{% url 'service_record' service.id %}" class="text-decoration-none"> <button type="button" class="btn btn-warning btn-sm" data-bs-toggle="tooltip" title="Update service"> <i class="bi bi-pencil-fill"></i> </button> </a> <!--Delete modal--> <!-- Button trigger … -
Django URL 404 - 1 week spent debugging with GPT4, Claude luck. One specific function is just NOT resolving
Issue Summary: I'm facing an issue where the /LS/mark-text-responses/ URL in my Django application is not being found when an AJAX request is sent to the mark_text_responses view. This issue is occurring in the user-facing part of my application, specifically in the JavaScript code that sends the AJAX request. I'm receiving a 404 Not Found error, indicating that the URL is not being resolved correctly. Relevant JavaScript Code: **javascript ** function submitWorksheet(event, activityIndex) { event.preventDefault(); const worksheetForm = event.target; const worksheetQuestionsData = worksheetForm.querySelector('.worksheet-questions').textContent; let worksheetData = {}; try { worksheetData = JSON.parse(worksheetQuestionsData); } catch (error) { console.error('Error parsing worksheet data:', error); return; } // ... (code omitted for brevity) ... if (question.type === 'text_response') { const textResponse = worksheetForm.querySelector(`textarea[name="response_${index + 1}"]`).value; const feedbackElement = document.getElementById(`text-response-feedback-${index + 1}`); // Make an AJAX request to the server to get feedback on the text response fetch('/lessons/mark-text-responses/', { method: 'POST', headers: { 'Content-Type': 'application/json', 'X-CSRFToken': document.querySelector('input[name="csrfmiddlewaretoken"]').value }, body: JSON.stringify({ activity_id: '{{ activity.id }}', question_index: index, text_response: textResponse }) }) .then(response => response.json()) .then(data => { if (data.feedback) { feedbackElement.textContent = data.feedback; } else { console.error('Error:', data.error); feedbackElement.textContent = 'Error processing text responses.'; } }) .catch(error => { console.error('Error:', error); feedbackElement.textContent = 'Error processing text … -
A "django.core.exceptions.SuspiciousFileOperation" error is occurring despite setting everything up correctly
Currently attempting to serve all of my static files via whitenoise. Funnily enough, the function itself works a treat. It seeks out all the directories labelled static in all of my Django apps. However, why is Django consistently returning the django.core.exceptions.SuspiciousFileOperation exception in my traceback, and why is this returning this just one css file. Logic would dictate that seeing as this css file is among other .css files in the same directory, Django seems to have some sort of personal vendetta against this one file. On the face it it, what Django is doing is completely illogical. My settings are as follows: pip install whitenoise settings.py INSTALLED_APPS = [ .... 'django.contrib.staticfiles', .... ] BASE_DIR = Path(__file__).resolve().parent.parent STATIC_URL = 'static/' STATIC_ROOT = BASE_DIR / "staticfiles" STATICFILES_DIRS = [ BASE_DIR / "static/libraries/assets/brand-assets", BASE_DIR / "static/libraries/assets/images", BASE_DIR / "static/libraries/assets/vectors", BASE_DIR / "static/libraries/assets/videos", BASE_DIR / "static/libraries/css", BASE_DIR / "static/libraries/js", BASE_DIR / "static/main", BASE_DIR / "legal/static", BASE_DIR / "blog/static", BASE_DIR / "events/static", BASE_DIR / "careers/static", BASE_DIR / "media/static", BASE_DIR / "static", ] My file directory is as follows: PROJECT NAME-| Root-| settings.py careers-| static-| careers.css media-| static-| media.css blog-| static-| blog.css legal-| static-| legal.css static-| main-| xxx.css xxx.css libraries-| css # <- location of … -
401 unauthorized Django Rest API Login
Im having problems with my login API Endpoint, it was working the last time I checked, now after working blindly for a few hours it doesnt work anymore and i don´t know what i´ve done :) Register is working smoothly, the user also gets created in the db and is visible in the admin panel. The same credentials are not working for the login. I´ve posted the code below, thanks for the help in advance views.py #register new users @api_view(['POST']) def register_user(request): if request.method == 'POST': serializer = UserSerializer(data= request.data) if serializer.is_valid(): serializer.save() return Response(serializer.data,status=status.HTTP_201_CREATED) return Response(serializer.data,status=status.HTTP_400_BAD_REQUEST) #userlogin with authentication tokens @api_view(['POST']) def user_login(request): if request.method == 'POST': email = request.data.get('email') password = request.data.get('password') user = None if not user: user = authenticate(email = email, password=password) if user: #token creation for the logged in user token, _ = Token.objects.get_or_create(user=user) return Response(user.getDetails(), status=status.HTTP_200_OK) # type: ignore return Response({'error': 'Invalid credentials'}, status=status.HTTP_401_UNAUTHORIZED) models.py class CustomUser(AbstractUser): # username = models.CharField(max_length = 25 ,default = 'No name',unique = True) username = None email = models.EmailField(default ="no email",unique = True) first_name = models.CharField(max_length = 25 ,default = 'No name') last_name = models.CharField(max_length = 25, default = 'No surname') password = models.CharField(max_length = 25,default = "no … -
Deployment not found error on deploying django project on cpanel
I have an issue in deploying my django project to cpanel after creating the python setup on cpanel pointing my subdomain to the setup project .I get 404(deployment not found) error once i click the url how can i fix that i expect the project should show the passenger_wsgi.py IT Works Screen on click of the url