Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Django Project Stuck at Login Page
I'm very new to Django and I am trying to create an booking website. I want that after login it should redirect to my booking.html page, but instead, I had this login page always keep heading back to login page over and over again This is my login.html : {% extends 'base.html' %} {% block content %} {% load static %} <link rel="stylesheet" type="text/css" href="{% static 'css/signin.css' %}"> <!-- jQuery --> <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js"></script> <!-- Bootstrap Bundle with Popper --> <script src="https://maxcdn.bootstrapcdn.com/bootstrap/4.5.2/js/bootstrap.bundle.min.js"></script> <div class="row justify-content-center"> <div class="col-md-4"> <div class="login-container"> {% if session.success %} <div class="alert alert-success alert-dismissible fade show" role="alert"> {{ session.success }} <button type="button" class="btn-close" data-bs-dismiss="alert" aria-label="Close"></button> </div> {% endif %} {% if session.loginError %} <div class="alert alert-danger alert-dismissible fade show" role="alert"> {{ session.loginError }} <button type="button" class="btn-close" data-bs-dismiss="alert" aria-label="Close"></button> </div> {% endif %} <div class="row justify-content-center"> <div class="wow fadeInUp" data-wow-delay="0.1s"> <main class="form-signin"> <div class="wrapper"> <div class="logo"> <img src="{% static 'img/logo.png' %}"> </div> <br> <div class="text-center mt-4 name"> Login Dulu Yuk </div> <br> <form id="loginForm" action="{% url 'login' %}" method="post"> {% csrf_token %} <div class="p-3 mt-3"> <div class="form-floating form-field d-flex align-items-center"> <input type="text" name="username" class="form-control rounded {% if form.errors.username %}is-invalid{% endif %}" id="username" placeholder="Username" autofocus required> <label for="username">Username</label> {% if … -
django - is UniqueConstraint with multi fields has same effect as Index with same field?
I wrote a django model that you can see below, I want to know having the UniqueConstraint is enough for Search and Selecting row base on user and soical type or I need to add the Index for them. if yes what is the different between them becuse base on my search the UniqueConstraint create an Unique Index on DB like posgresql. model: class SocialAccount(Model): """Social account of users""" added_at: datetime = DateTimeField(verbose_name=_("Added At"), auto_now_add=True) user = ForeignKey( to=User, verbose_name=_("User"), db_index=True, related_name="socials", ) type = PositiveSmallIntegerField( verbose_name=_("Type"), choices=SocialAcountType, ) class Meta: constraints = UniqueConstraint( # Unique: Each User Has Only one Social Account per Type fields=( "user", "type", ), name="user_social_unique", ) # TODO: check the UniqueConstraints is enough for index or not indexes = ( Index( # Create Index based on `user`+`type` to scan faster fields=( "user", "type", ), name="user_social_index", ), ) base on the above description I searched but I can't find any proper document to find how django act and we need extra index for them if they are a unique togher already? Note: I know there are some other questions that are similar but they can't answer my question exactly -
Error on calling .delete and update methods django
I have a stage model defined as below. When I try to perform delete operation I am getting below error. For other models, delete is working fine. previously I have been using django 2.2. After Upgrade I am seeing this error. from djangodeletes.softdeletes import ( SoftDeletable, SoftDeleteManager, SoftDeleteQuerySet, ) class Stage(SoftDeletable, models.Model): name = models.CharField(max_length=50) stage_type = models.CharField( choices=STAGE_TYPE_CHOICES, null=True, blank=True, max_length=50, ) close_stage_type = models.CharField( choices=CLOSE_STAGE_TYPE, null=True, blank=True, max_length=20, ) sequence = models.IntegerField(null=True, blank=True) pipeline = models.ForeignKey( Pipeline, null=True, blank=True, on_delete=models.CASCADE, related_name="pipeline_stages", ) created_by = models.ForeignKey( "accounts.User", on_delete=models.SET_NULL, null=True, related_name="stage_created_by", ) modified_by = models.ForeignKey( "accounts.User", on_delete=models.SET_NULL, null=True, related_name="stage_modified_by", ) created_at = models.DateTimeField(auto_now_add=True) modified_at = models.DateTimeField(auto_now=True) objects = SoftDeleteManager.from_queryset(SoftDeleteQuerySet)() def __str__(self): return str(self.id) Stage.objects.get(id = 1240).delete() File "/home/srinivas/design_studio_app_1/design_studio_app/prac.py", line 50, in <module> stage.delete() File "/home/srinivas/design_studio_app_1/.venv/lib/python3.8/site-packages/djangodeletes/softdeletes/models.py", line 78, in delete for (field, value), instances in instances_for_fieldvalues.items(): AttributeError: 'list' object has no attribute 'items'``` I am using below versions Python 3.8.18, Django 4.2.9, djangodeletes 0.43 what could be the issue? -
What is the best approach to preserve GET parameters in django?
I have a ListView which I display using HTML <table> element. Each column is a field on model, while each row is a particular model instance. For this view I implemented search over multiple model fields (via GET form with query parameter search), filtering for each model field (via GET forms with query parameters filter--{{ field.name }}-{{ filter-type }}) and ordering over multiple fields (via query parameter order). I am planning to add pagination and ability for user to set page size (so soon two more query parameters). My question is: is there a simple approach to handle preserving existing unchanged GET values in both anchors and GET forms? For context: All three can be active at the same time, so paths can look like all of: /example/ /example/?filter--service_expires_at-datetime_from=2024-02-27T09%3A31&filter--service_expires_at-datetime_to= /example/?filter--username-icontains=abc&search=test /example/?order=-username,service_expires_at&search=test&filter--username-icontains=abc Search and filters have both links (to clear search or particular filter) and GET forms (to set search or particular filter). Order has links, which modify order GET parameter to either add ASC or DESC sort (or remove both) over particular column. My problem is that preserving GET parameters got quite cumbersome - for example, when I want to change order value, I need to take care to preserve … -
(Error) OSError: (WinError 6) The handle is invalid, when running python manage.py shell, I do not understand what is happening?
models.py file # Create your models here. class Flight(models.Model): origin = models.CharField(max_length=64) destination = models.CharField(max_length=64) duration = models.IntegerField(null=False) Then I run python manage.py shell in terminal python manage.py shell Python 3.8.0 (tags/v3.8.0:fa919fd, Oct 14 2019, 19:37:50) [MSC v.1916 64 bit (AMD64)] Type 'copyright', 'credits' or 'license' for more information IPython 8.12.3 -- An enhanced Interactive Python. Type '?' for help. In [1]: from flights.models import Flight Cancelling an overlapped future failed future: <_OverlappedFuture pending overlapped=<pending, 0x1af989b8430> cb=[BaseProactorEventLoop._loop_self_reading()]> Traceback (most recent call last): File "C:\Users\jaina\AppData\Local\Programs\Python\Python38\lib\asyncio\windows_events.py", line 66, in _cancel_overlapped self._ov.cancel() OSError: [WinError 6] The handle is invalid Above error happens, How can I resolve this, please help. -
In my template i'm trying to hide alert massage div if the notification item is None
{% if not notfication in alert %} <div style=" background: no-repeat; "> <div class=""> <span>None</span> </div> </div> {% else %} <div class="marquee-area"> <div class="marquee-wrap"> {% for notfication in alert %} <span>{{ notfication.title }}</span> {% endfor %} </div> </div> {% endif %} When I try to test it, regardless of whether there is data or not, I get Nothing her text -
Can anyone help me to reach out Lead Python Developer
I have been looking candidates with 8+ years of experience with 5+ core Python Developer and AI/ML experience too. I have used Github, Naukri, and LinkedIn, but I'm struggling to find the right candidate. Can you suggest a better way to target people with specific domain, role, or software experience? 6 years of experience, 5+ years in bringing to life web applications, mobile applications, and machine learning frameworks. Hands on work experience with: Python, R, Django, Flask, JavaScript (ES6), React, Node.js, MongoDB, Elasticsearch, Azure, Docker, Kubernetes, Microservices Good knowledge of caching technologies like Redis and queues like Kafka, SQS, MQ etc. Knowledge of Big Data, Hadoop would be a plus -
Package Django app without moving it to an external folder
We are working in a Django project with many applications. Our idea is to package them individually to use in other projects (like plugins). Is there any way to package an application without moving it to an external folder (like documentation explains)? We tried to add a setup.py file inside app folder and run python setup.py sdist. The command creates the dist/ and .egg-info/ folders, but then when we install the tar.gz in a new Django project using pip, it seems that the package itself is not installed, but only the .egg-info folder. Our current folder structure is: project/ app/ __init__.py admin.py apps.py models.py serializers.py setup.py tests.py urls.py views.py ... manage.py requirements.txt -
Combine and sum hours user spent per day
I am trying to sum all hours the user spent per day. I used this line of code: from django.db.models import F, Sum from django.db.models.functions import TruncDate Clocking.objects.filter(clockout__isnull=False, user=nid).values(date=TruncDate('clockin')).annotate(total=Sum(F('clockout') - F('clockin'))).order_by('clockin')) I have this result which calculates the hours into seconds. But if the user is clocking n times per day, how can I sum those hours or seconds in one date? <QuerySet [{'date': datetime.date(2024, 5, 7), 'total': datetime.timedelta(seconds=14418)}, {'date': datetime.date(2024, 5, 7), 'total': datetime.timedelta(seconds=9)}, {'date': datetime.date(2024, 5, 8), 'total': datetime.timedelta(seconds=9)}, {'date': datetime.date(2024, 5, 8), 'total': datetime.timedelta(seconds=3609)}]> -
Django `db_table` not renaming table
This question is (surprisingly) unlike similar ones, which ask about doing this dynamically, or ask how to do it in the first place. This question regards those suggestions not working as expected. Brief summary of situation: We made a series of Django apps as part of an API used in a real web app. We named those apps in ways that made sense at the time, e.g., "organizations" and "authentication". Now, we are packaging these apps as a distributable library, so a third party can install our apps in their API. The client already has apps named "organizations" and "authentication", causing conflicts (because Django apps must have unique names). Because we are creating the reusable library, we are renaming our apps from organizations to mycompany_organizations with corresponding model renames from Organization to MyCompanyOrganization to make them unique and distinguishable. I have made a series of migrations following this guide to create a new app and move the models over without losing data. Everything worked until someone added a new app that referenced our Organization (now named MyCompanyOrganization) model. This migration results in relation my_company_orgaanization does not exist, despite multiple foreign keys already pointing to my_company_organizations.organization and working fine. I inspected … -
Django: ModuleNotFoundError: No module named 'dotenv'
I see hundreds with this issue, but the answers to other posts aren't working for me. I'm simply trying to use dotenv and an .env file to hide sensitive data like an email password. I've tried this and it didn't work: pip uninstall dotenv pip uninstall python-dotenv pip install python-dotenv Error Traceback: Traceback (most recent call last): File "C:\PythonProjects\VoterSay7\venv\lib\site- packages\django\core\management\base.py", line 412, in run_from_argv self.execute(*args, **cmd_options) File "C:\PythonProjects\VoterSay7\venv\lib\site- packages\django\core\management\commands\runserver.py", line 74, in execute super().execute(*args, **options) File "C:\PythonProjects\VoterSay7\venv\lib\site- packages\django\core\management\base.py", line 458, in execute output = self.handle(*args, **options) File "C:\PythonProjects\VoterSay7\venv\lib\site- packages\django\core\management\commands\runserver.py", line 81, in handle if not settings.DEBUG and not settings.ALLOWED_HOSTS: File "C:\PythonProjects\VoterSay7\venv\lib\site- packages\django\conf\__init__.py", line 102, in __getattr__ self._setup(name) File "C:\PythonProjects\VoterSay7\venv\lib\site- packages\django\conf\__init__.py", line 89, in _setup self._wrapped = Settings(settings_module) File "C:\PythonProjects\VoterSay7\venv\lib\site- packages\django\conf\__init__.py", line 217, in __init__ mod = importlib.import_module(self.SETTINGS_MODULE) File return _bootstrap._gcd_import(name[level:], package, level) File "<frozen importlib._bootstrap>", line 1030, in _ gcd_import File "<frozen importlib._bootstrap>", line 1007, in _ find_and_load File "<frozen importlib._bootstrap>", line 986, in _ find_and_load_unlocked File "<frozen importlib._bootstrap>", line 680, in _ load_unlocked File "<frozen importlib._bootstrap_external>", line 850, in exec_module File "<frozen importlib._bootstrap>", line 228, in _ call_with_frames_removed File "C:\Users\mattk\Box\WeConsent\VoterSay10\settings.py", line 14, in <module> import dotenv ModuleNotFoundError: No module named 'dotenv' from settings.py: import dotenv from dotenv import load_dotenv -
dj-rest-auth RegisterView interfering with my signal and preventing it from updating user model
I want to update my custom user model after a user verifies their email using a signal but it does not work and the Django DEBUG page throws a NoReverseMatch error from allauth.account.signals import email_confirmed from django.dispatch import receiver @receiver(email_confirmed) def email_confirmed_(request, email_address, **kwargs): user = email_address.user user.is_active = True user.save() This is my signal code. The is_active field is set to False by default and should only become True upon the user verifying their account. After adding this signal it doesn't change the is_active field of a verified user to True and I get this error: (NoReverseMatch at /api/users/registration/ Reverse for 'account_inactive' not found. 'account_inactive' is not a valid view function or pattern name.) Image here The problem seems to be coming from the dj-rest-auth RegisterView but I can't seem to understand why and don't know how to fix it. -
How to read file in s3 Bucket using django-sotrages?
I have a Django app that uses DigitalOcean Spaces to store user-uploaded files. The app then transcribes those files and returns the text. However when I try to read the file using the url to the stored file it fails. Here is my views.py: This code saves the file to Spaces if form.is_valid(): uploaded_file = request.FILES['file'] request.session['uploaded_file_name'] = uploaded_file.name request.session['uploaded_file_size'] = uploaded_file.size#add to models session_id = str(uuid.uuid4()) request.session['session_id'] = session_id transcribed_doc, created = TranscribedDocument.objects.get_or_create(id=session_id) transcribed_doc.audio_file = uploaded_file transcribed_doc.save() request.session['uploaded_file_path'] = transcribed_doc.audio_file.url#store url to file #rest of code This code reads the file: file_name = request.session.get('uploaded_file_name') file_path = request.session.get('uploaded_file_path')#store url in 'file_path' variable if request.method == 'POST': try: if not file_name or not file_path: return redirect (reverse('transcribeSubmit')) audio_language = request.POST.get('audio_language') output_file_type = request.POST.get('output_file_type') if file_name and file_path: file_extension = ('.' + (str(file_name).split('.')[-1])) #open file located at DO Spaces and initiate transcription with open(file_path, 'rb') as f: path_string = f.name destination_dir = 'ai_transcribe_output' transcript = transcribe_file(path_string, audio_language, output_file_type, destination_dir) My intention is to transcribe the file directly from the url at DO Spaces or if that is not feasible then instead to temporarily store a copy of the file locally so that it can be transcribed then deleted. I'm using django-storages[s3] to … -
How to use timescaledb's `lttb` function with django queryset?
I have a django project which stores real-time data of a few devices. For this manner I have used timescaledb which is suitable for time series. Timescale offers a few hyperfunctions which I need to use (specifically lttb which is used for downsampling data). For example, this is one of the queries that I am looking to achieve: SELECT time as timestamp, value as value, %s as device_id FROM unnest((SELECT lttb(timestamp, value, %s) FROM core_devicedata where device_id=%s and timestamp between %s and %s)) I can get result of this query as a raw query set by: for data in DeviceData.objects.raw(query): ... I have already tried raw sql queries using django. They work. The thing is they offer no filtering and ordering functionality since they do not return actual queryset. Instead, they return a raw query set. What I am trying to achieve is to run a query like below using only with power of djagno orm. SELECT time as timestamp, value as value, %s as device_id FROM unnest((SELECT lttb(timestamp, value, %s) Any suggestions? If there is no way to do this with django orm itself, would please help me write a modular manager method for this manner? Like I should … -
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