Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Django gettext not working properly with django rest
I'm having some weird bug with gettext while using a ModelSerializer, I cannot get the translated charfield choice for all of the choices, some choices work but others don't I even tried to run another makemessages command but the same inconsistent result. this is the problematic field status= models.CharField( max_length=50, default="pending", choices=[ ('pending', _('Pending')), ('initiated', _('Initiated')), ('completed', _('Completed')) ] ) -
Get ElasticSearch suggestion based on filtered data in Django
I am using django-elasticsearch-dsl for integrating elastic search. I have an API that returns name suggestions using elastic search suggest feature. It's working as expected but the issue is I can't apply a specific filter. For example, I want to get suggestions for the published products only. #Document class ProductDocument(Document): status = fields.IntegerField() meta = fields.ObjectField( properties={ "is_published": fields.BooleanField(), "full_name": fields.TextField( analyzer=html_strip, fields={ "raw": fields.KeywordField(), "suggest": fields.Completion(), } ), }, ) search = ProductDocument.search() search = search.filter("match", meta__is_published=True) completion = { 'field': "meta.full_name.suggest", 'size': 10, 'fuzzy': {'fuzziness': "auto:4,8"}, } suggest = search.suggest("auto_complete","abc", completion=completion) But it return products with is_published=False. Is there any way to achieve this? -
Django And Windows 2016 IIS Server
I have at work a local Windows 2016 IIS Server. How can I configure it to recognize a live instance of my Django project? -
Django translation.activate not working in middleware
I'm attempting to implement an auto language switcher in Django based on the client's IP address. For testing purposes, I've created a middleware to set the language to French ('fr'). class SetFrenchLanguageMiddleware: def __init__(self, get_response): self.get_response = get_response def __call__(self, request): user_language = 'fr' translation.activate(user_language) request.LANGUAGE_CODE = translation.get_language() response = self.get_response(request) response.set_cookie('django_language', user_language) print("language set to ", user_language) return response When I access a page, I see "language set to fr" printed in the console, indicating that the middleware is executed. However: The content is still displayed in English, the default language. The URL prefix doesn't change to "/fr/". Could someone help me understand why this isn't working as expected and guide me on how to resolve the issue? -
I need to create a button in html
Good time of day. I have a Field and a button that changes a record in the Database when clicked.I want to not have this field, and when I press the button, I go to the already filled field, and I can customize it, and then save it by pressing the button. Here is my code, I hope it will help in some way.I would also be grateful for help in improving the code, I'm a beginner. today.html <title>Todoist</title> <h1>Сегодня</h1> <h2>Задачи</h2> <form method="POST" action="{% url 'todoist:add' %}" >{% csrf_token %} <input type="text" name='tasks' pattern=".{2,}" required title='Минимум два символа!!!'> <button type="submit" class="save btn btn-default">Добавить задачу</button> </form> {% for todo in todos%} <div> <p> {{todo.tasks}}</p> <a href={% url 'todoist:delete' today_id=todo.id%}>Удалить</a> <form action="{% url 'todoist:update' today_id=todo.id%}" method="post"> {% csrf_token %} <input type="text" name='tasks'> <button type="submit" class="save btn btn-default">Изменить</button> </form> </div> {% endfor %} views.py from django.shortcuts import render,redirect from .models import Today from django.views.decorators.http import require_http_methods def index(request): todos = Today.objects.all() return render(request, 'today.html', {'todos':todos}) @require_http_methods(['POST']) def add(request): tasks = request.POST["tasks"] task = Today(tasks=tasks) task.save() return redirect('todoist:index') def delete(request, today_id): todo = Today.objects.get(id=today_id) todo.delete() return redirect('todoist:index') def update(request, today_id): todo = Today.objects.get(id=today_id) todo.tasks = request.POST.get('tasks') todo.save() return redirect('todoist:index') -
Django: create dynamic attributes related to objects
In my models I have a few "masterdata" models. These contain the most relevant / standardized values. For different purposes I need different "attributes" / "variables" related to these master data. I dont want to create a variable for each possibility in the master model. Say e.g. I have the model Material. It will contains some basic variables. My rationale is to have a seperate model, Material_Attributes. This would contain a foreign key to Material, and allow for example to store attribute "packing" with value "cartons". At the model I'm a bit in doubt whether these attributes and options should be stored in a third model. But in this case, it would relate to Material only. I might also want to store an attribute to objects from model Customers. I could build the same logic, but it would be rather static (need to do for each model), or perhaps I can do a work around with GenericForeignKeys to allow even the model to be dynamic. Anybody encountered something similar in the past, and how to go about? I'm a bit struggling how to go about. What would be a logic step to go about? -
Django - Alert user if exiting before submitting form
I have a page of my application that has a form. How can I alert users if they attempt to exit the program without submitting the form? Ideally, I would like to do so without using JavaScript, if possible. -
Exporting Data from Django Template to Excel
I wish to do just that: Export my context data on a template to Excel, using XlsxWriter or anything of the kind. The user would click on a button or anchor on the template. If I use a url path to call a view, some sort of HttpResponse is expected. I have no idea if or how this can be done through some sort of custom tag, either (I saw this suggested elsewhere). Any ideas? Or better yet, does anyone have a project on GitHub that has anything like this? Thanks in advance. I tried calling a url path, that would in turn call a view. But the view needs to return an HttpResponse at least. So this leaves me with 2 uncertain possibilities: Can a url path simply call a module, completely independent of views.py? If I do call a view, could it return something like a response to the currently-rendered template? (like "file created!", for instance. I don't want to leave the template. -
im getting error while gitlab ci pipeline runs
i am using python:3.10.12-alpine as image in my gitlab ci/cd and this is my gitlab-ci file: default: image: python:3.10.12-alpine before_script: - apk update - apk add make automake gcc g++ subversion - pip install --upgrade pip - python -m pip install --upgrade pip - python -m pip install -r requirements.txt migrations: stage: build script: - python manage.py makemigrations - python3 manage.py makemigrations myapp - python manage.py migrate and this is the error that i get when pipeline runs: Installing build dependencies: started Installing build dependencies: finished with status 'done' Getting requirements to build wheel: started Getting requirements to build wheel: finished with status 'error' error: subprocess-exited-with-error × Getting requirements to build wheel did not run successfully. │ exit code: 1 ╰─> [24 lines of output] /bin/sh: pkg-config: not found /bin/sh: pkg-config: not found Trying pkg-config --exists mysqlclient Command 'pkg-config --exists mysqlclient' returned non-zero exit status 127. Trying pkg-config --exists mariadb Command 'pkg-config --exists mariadb' returned non-zero exit status 127. Traceback (most recent call last): File "/usr/local/lib/python3.10/site-packages/pip/_vendor/pyproject_hooks/_in_process/_in_process.py", line 353, in <module> main() File "/usr/local/lib/python3.10/site-packages/pip/_vendor/pyproject_hooks/_in_process/_in_process.py", line 335, in main json_out['return_val'] = hook(**hook_input['kwargs']) File "/usr/local/lib/python3.10/site-packages/pip/_vendor/pyproject_hooks/_in_process/_in_process.py", line 118, in get_requires_for_build_wheel return hook(config_settings) File "/tmp/pip-build-env-nx4qgfyo/overlay/lib/python3.10/site-packages/setuptools/build_meta.py", line 341, in get_requires_for_build_wheel return self._get_build_requires(config_settings, requirements=['wheel']) File "/tmp/pip-build-env-nx4qgfyo/overlay/lib/python3.10/site-packages/setuptools/build_meta.py", line … -
python not rendering context in data view
I have created a custom report in python (using logic I have used in another app that I know works). However, in this particular app it doesn't appear to be rendering the context that I referring to with the render in my view. I can see that it is printing out the query in the python parser but the issue is that it is not rendering in the template. Models.py class NegativeBehaviour(models.Model): behaviour = models.CharField(max_length=250, blank=True, unique=True, null=True, choices=NegativeBehaviourType) behaviourdesc = models.TextField(max_length=2500) subjects = models.CharField(max_length=250, choices=Subjects, default=None) module = models.CharField(max_length=250, choices=Modules, default=None) students = models.ForeignKey(CustomUser, related_name = "Negative_Behaviour_Students", on_delete = models.CASCADE) staff = models.ForeignKey(CustomUser, related_name = "Negative_Behaviour_Teachers", on_delete = models.CASCADE) C1 = BehaviourManagerC1() C2 = BehaviourManagerC2() C3 = BehaviourManagerC3() C4 = BehaviourManagerC4() C5 = BehaviourManagerC5() class Meta: verbose_name = "Behaviour", verbose_name_plural = "Behaviours" def __str__(self): return self.behaviour return str(self.user.id) class PositiveBehaviour(models.Model): behaviour = models.CharField(max_length=250, blank=True, unique=True, null=True, choices=PositiveBehaviourType) behaviourdesc = models.TextField(max_length=2500) subjects = models.CharField(max_length=250, choices=Subjects, default=None) module = models.CharField(max_length=250, choices=Modules, default=None) students = models.ForeignKey(CustomUser, related_name = "Positive_Behaviour_Students", on_delete = models.CASCADE) staff = models.ForeignKey(CustomUser, related_name = "Positive_Behaviour_Teachers", on_delete = models.CASCADE) A1 = BehaviourManagerA1() A2 = BehaviourManagerA2() A3 = BehaviourManagerA3() class Meta: verbose_name = "Behaviour", verbose_name_plural = "Behaviours" def __str__(self): return self.behaviour … -
Django how to design the editting page of a plugin made by CMSPlugin and CMSPluginBase?
I am implementing a plugin to show the information of a publication, in the normal editting page, there's three button in the right down corner 'Cancel' 'Delete' 'Save', the plugin is created using CMSPlugin and CMSPluginBase, is it possible for me to add new buttons with them? I tried adding a button, but I can only add attributes to the class defined in the cms_plugins.py. The button can only be added in the form, not on the window. -
File upload - File does not exist when file exceeds that FILE_UPLOAD_MAX_MEMORY_SIZE
Stumbled upon this error when upgrading from Django 4.1. to 4.2.4. ... and it's a weird one. The error occurs when I upload a file that is larger than FILE_UPLOAD_MAX_MEMORY_SIZE (set to 5MB). I have two development environments set up. One is local dev server (just normal py manage.py runserver), the other one is running under Docker(Windows) + Alpine linux + Apache2 + mod_wsgi which is also still a 'development' environment. This error occurs only under Docker environment and only when file exceeds max memory size. Under all other circumstances the upload works - even when file exceeds memory limit on local dev server. The error: Saving new order file to: customer_name/_web_portal/PendingOrders/7935/zip_03.zip Internal Server Error: /b2b_api/orders/ Traceback (most recent call last): File "/usr/local/lib/python3.11/site-packages/django/core/handlers/exception.py", line 55, in inner response = get_response(request) ^^^^^^^^^^^^^^^^^^^^^ File "/usr/local/lib/python3.11/site-packages/django/core/handlers/base.py", line 197, in _get_response response = wrapped_callback(request, *callback_args, **callback_kwargs) ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ File "/usr/local/lib/python3.11/site-packages/django/views/decorators/csrf.py", line 56, in wrapper_view return view_func(*args, **kwargs) ^^^^^^^^^^^^^^^^^^^^^^^^^^ File "/usr/local/lib/python3.11/site-packages/rest_framework/viewsets.py", line 125, in view return self.dispatch(request, *args, **kwargs) ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ File "/code/api/views.py", line 352, in dispatch return super().dispatch(request, *args, **kwargs) ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ File "/usr/local/lib/python3.11/site-packages/rest_framework/views.py", line 509, in dispatch response = self.handle_exception(exc) ^^^^^^^^^^^^^^^^^^^^^^^^^^ File "/usr/local/lib/python3.11/site-packages/rest_framework/views.py", line 469, in handle_exception self.raise_uncaught_exception(exc) File "/usr/local/lib/python3.11/site-packages/rest_framework/views.py", line 480, in raise_uncaught_exception raise exc … -
Django cant find the current path when it mentions the available paths on the error too
Request Method: GET Request URL: http://127.0.0.1:8000/playground/hello Using the URLconf defined in storefront.urls, Django tried these URL patterns, in this order: 1- admin/ 2- playground/playground/hello The current path, playground/hello, didn’t match any of these. Here it is showing the available paths and when i put the available path playground/hello it says it cant be found My playground/urls.py from django.urls import path from . import views app_name = "playground" urlpatterns = [ path('playground/hello', views.say_Hello) ] My playground/views.py from django.shortcuts import render from django.http import HttpResponse # Create your views here. def say_Hello (request): return HttpResponse ('Hello World') My Django project/urls.py from django.contrib import admin from django.urls import path, include print('came in main urls') urlpatterns = [ path('admin/', admin.site.urls), path('playground/', include ('playground.urls')) ] -
Form is not processed
I'm writing my store in Django. When it comes to filling out the order form, even if it is empty, the page about `successful payment` is still displayed. Water code: views.py from django.shortcuts import get_object_or_404, redirect, render from django.contrib import messages from django.contrib.auth.decorators import login_required from .models import * from .forms import ShippingAddressForm # Create your views here. def store(request): products = Product.objects.all() return render(request, 'store.html', {'products': products}) @login_required def cart(request): items = CartItem.objects.filter(user=request.user) total_quantity = sum([item.quantity for item in items]) total_price = sum([item.product.price * item.quantity for item in items]) return render(request, 'cart.html', {'items': items, 'total_quantity': total_quantity, 'total_price': total_price}) @login_required def add_to_cart(request, product_id): product = Product.objects.get(id=product_id) item, created = CartItem.objects.get_or_create(product=product, user=request.user) if not created: item.quantity += 1 item.save() return redirect('store') @login_required def remove_from_cart(request, product_id): item = get_object_or_404(CartItem, pk=product_id) if item.quantity > 1: item.quantity -= 1 item.save() else: item.delete() return redirect('cart') @login_required def checkout(request): items = CartItem.objects.all() total_price = sum([item.product.price * item.quantity for item in items]) if request.method == 'POST': form = ShippingAddressForm(request.POST) if form.is_valid(): # Create a new Order instance and associate with the user order = Order.objects.create(customer=request.user) # Associate each cart item with the order for item in items: item.order = order item.save() # Clear the cart items.delete() # … -
django-axes not saving ip-address
I have a django app running behind gunicorn+nginx. These packages are installed: django-axes 6.0.5 django-ipware 5.0.0 This is my config: AXES_FAILURE_LIMIT = 5 AXES_COOLOFF_TIME = 1 AXES_IPWARE_PROXY_COUNT = 1 AXES_IPWARE_META_PRECEDENCE_ORDER = ('HTTP_X_FORWARDED_FOR',) AXES_LOCKOUT_PARAMETERS = [["username", "ip_address"]] request.META.get('HTTP_X_FORWARDED_FOR') returns my ip-address. If I test it on dev server it saves 127.0.0.1 but in production ip address field stays empty. What am I doing wrong? -
aiogram: how to connect an inline keyboard from a function of another file with a bot file if this function will work in another code
Project (connection between DRF and bot with endpoints): -bot-directory (not in django project) : services.py and main.py in it -folders of django apps, manage.py etc. My function from services.py from bot directory def get_items_kb(): keyboard = InlineKeyboardMarkup() button1 = InlineKeyboardButton('Подтвердить', callback_data="yes") button2 = InlineKeyboardButton('Отклонить', callback_data="no") keyboard.row(button1, button2) return keyboard async def register_manager(CHAT_ID: str): bot = Bot(token='same') fake = Faker() username = fake.user_name() password = fake.password() await bot.send_message(CHAT_ID, f'Подтвердите:{username}\n{password}', reply_markup=get_items_kb()) Using of this function in django-signals (signals.py) @receiver(pre_save, sender=BotUser) def bot_user_manager_changed(sender, instance, **kwargs): if instance.id is not None: previous = BotUser.objects.get(id=instance.id) if not previous.manager and instance.manager: register_manager_sync = async_to_sync(register_manager) register_manager_sync(instance.user_id) main.py with bot in bot directory (in the same directory as the function, but different file) storage = MemoryStorage() TOKEN='same' bot = Bot(TOKEN) dp = Dispatcher(bot, storage=storage) @dp.callback_query_handler(lambda query: query.data == 'yes', state="*") @dp.callback_query_handler(lambda query: query.data == 'no', state="*") async def activate_manager_handler(callback_query: CallbackQuery, state: FSMContext): ... if __name__ == '__main__': executor.start_polling(dp,skip_updates=True) So all I want to do is get this inline keyboard to work and be caught by the handler when the function runs from django signals. Now, the function send a message, but inline-keyboard doesn't work. Expectation: Example of work: I change manager field to True in django-admin -> signal … -
React Native with Django backend how to make sure sure that only users with passed token can access images?
I am building a react native app with Django backend. In the app I let the users upload images which are stored in a models.FileField(). The problem I just noticed is that anyone can access the images from the backend server if they have the right link which raises privacy issues. How would the python and React Native code look like for making sure images that go into can be obtained only with passing a "POST" request which has a "user" and a "token" and how to put those images to be displayed with ? Thank you -
How to download a file from Azure FileShare with python?
How can i download a file from Azure Fileshare using python but i can't modify metadata in new file on local machine? When i download file using FileService or ShareFileClient (azure-storage or azure-storage-file libraries) it change creation date and modified date, so it download new file with metadata changed. I need to keep original metadata in downloaded file. #DOWNLOAD A FILE USING FILES SHARE AND SHAREFILECLIENT account_name = "account_name changed" account_key = "account_key changed" share_name = "share_name changed" file_name = "test.png" # Initialize the ShareServiceClient service_client = ShareServiceClient(account_url=f"https://{account_name}.file.core.windows.net", credential=account_key) # Get a reference to the file file_client = service_client.get_share_client(share_name).get_directory_client(None).get_file_client(file_name) print(file_client) file_props = file_client.get_file_properties() print(file_props) file_metadata = file_props.metadata print(file_metadata) local_file_path = "./test.png" I also try with external apps like rclone and it didn't work. -
How to filter a many-to-many field (not primary key) in a Django queryset for serialization with Django REST framework
Given two models with a many-to-many relationship between them. class Collection(models.Model): title = models.CharField(max_length=200, unique=True, verbose_name="Title") class Content(models.Model): author = models.CharField(max_length=200, unique=True, verbose_name="Author") collection = models.ManyToManyField(Collection, verbose_name="Collection") public = models.BooleanField(default=True, verbose_name="Public") How can I filter the Collection to only list Content where public == True? serializers.py: class ContentSerializer(serializers.ModelSerializer): class Meta: model = Content fields = ["author"] class CollectionSerializer(serializers.ModelSerializer): content_set = ContentSerializer(many=True, read_only=True) class Meta: model = Collection fields = [ "title", "content_set", ] view.py: class CollectionViewSet(viewsets.ReadOnlyModelViewSet): queryset = Collection.objects.all() serializer_class = CollectionSerializer permission_classes = [permissions.AllowAny] def get_queryset(self): return Collection.objects.filter(content_set__enable=True) # Not working as expected Desired output: [ { "title": "Foo", "content_set": [ { "author": "Jane Doe" } ] } ] -
Saleor custom url creation
I need to create a custom defined url like slug based on that some user data would be shown on the screen from the database but without authentication in saleor. from saleor.graphql.utils import get_current_user, create_login_and_password_url from saleor.core.utils.urlresolvers import reverse urlpatterns = [ path("my-custom-url/", my_custom_url, name="my-custom-url"), ] -
Django container CSRF verification fails
I made a container of my Django application and when I log in the app I get this error: Origin checking failed - https://127.0.0.1:8443 does not match any trusted origins. When I run the app in my pc I can log in without any issue. This error only occurs in the container. I declared in my compose file to trust the ip but still get the same error: DJANGO_CSRF_TRUSTED_ORIGINS: https://127.0.0.1:8443 -
how to deal with models in django
i have a problem how to create an login and register for a model that i create but nothing work good i try this for login def login_user(request): if request.user.is_authenticated: messages.success(request, "You are Already logged in ") redirect('/') else: if request.method == 'POST': form = login_client(request.POST) if form.is_valid(): email = form.cleaned_data['email'] password = form.cleaned_data['password'] client = authenticate(request, email=email, password=password) if client is not None: login(request, client) return redirect("/") else : form = login_client() return render(request, 'Login.html', {"form":form}) and for the register page i try this def register_user(request): if request.user.is_authenticated: messages.success(request, "You are Already logged in") return redirect("/") else : if request.method == 'POST': form = addNewClient(request.POST) if form.is_valid(): user = form.save() return redirect('login') else : form = addNewClient() return render(request, 'signup.html', {"form":form}) and this is the model in the file models.py class Clients(models.Model) : created_at = models.DateField(auto_now_add=True) idClient = models.AutoField(primary_key=True) first_name = models.CharField(max_length=80) last_name = models.CharField(max_length=80) email = models.CharField(max_length=120, unique=True) username = models.CharField(max_length=120, unique=True) password = models.CharField(max_length=100) def __str__(self): return self.username -
Error After Uninstall in Shopify App Using Django
I am taking reference from https://github.com/Shopify/shopify_django_app repository to make a shopify app. The problem is that the app installs properly and works fine but the problem is that if we access App URL after it is uninstalled from shopify store, it returns the following error. I believe the error is because of the 'shop_login_required' decorator in shopify_app.decorator.py file. This decorator is used in login view in home.views.py file. Full Error Log:- Internal Server Error: / Traceback (most recent call last): File "D:\app\venv\lib\site-packages\pyactiveresource\connection.py", line 286, in _open http_response = self._handle_error(self._urlopen(request)) File "D:\app\venv\lib\site-packages\pyactiveresource\connection.py", line 316, in _urlopen return urllib.request.urlopen(request, timeout=self.timeout) File "C:\Users\royal\miniconda3\lib\urllib\request.py", line 216, in urlopen return opener.open(url, data, timeout) File "C:\Users\royal\miniconda3\lib\urllib\request.py", line 525, in open response = meth(req, response) File "C:\Users\royal\miniconda3\lib\urllib\request.py", line 634, in http_response response = self.parent.error( File "C:\Users\royal\miniconda3\lib\urllib\request.py", line 563, in error return self._call_chain(*args) File "C:\Users\royal\miniconda3\lib\urllib\request.py", line 496, in _call_chain result = func(*args) File "C:\Users\royal\miniconda3\lib\urllib\request.py", line 643, in http_error_default raise HTTPError(req.full_url, code, msg, hdrs, fp) urllib.error.HTTPError: HTTP Error 401: Unauthorized During handling of the above exception, another exception occurred: Traceback (most recent call last): File "D:\app\venv\lib\site-packages\django\core\handlers\exception.py", line 55, in inner response = get_response(request) File "D:\app\venv\lib\site-packages\django\core\handlers\base.py", line 197, in _get_response response = wrapped_callback(request, *callback_args, **callback_kwargs) File "D:\app\shopify_django_app\shopify_app\decorators.py", line 12, in … -
How do I fix this error where I want to render templates which have static files
{% load static %} include 'accounts/navbar.html' %} block content %} endblock %} Our footer ` I wanted to render a page and it brought the following output. Invalid block tag on line 8: 'static,'. Did you forget to register or load this tag? Request Method: GET Request URL: http://127.0.0.1:8000/ Django Version: 4.2.4 Exception Type: TemplateSyntaxError Exception Value: Invalid block tag on line 8: 'static,'. Did you forget to register or load this tag? Exception Location: C:\Python311\Lib\site-packages\django\template\base.py, line 568, in invalid_block_tag Raised during: accounts.views.home Python Executable: C:\Python311\python.exe Python Version: 3.11.4 Python Path: ['D:\My_django_stuff\crm', 'C:\Python311\python311.zip', 'C:\Python311\DLLs', 'C:\Python311\Lib', 'C:\Python311', 'C:\Users\PATRICK -BITS\AppData\Roaming\Python\Python311\site-packages', 'C:\Python311\Lib\site-packages', 'C:\Python311\Lib\site-packages\vboxapi-1.0-py3.11.egg'] Server time: Fri, 11 Aug 2023 11:15:54 +0000 CRM ` -
Getting Unauthenticated warnings despite using permissions.AllowAny
This is my APIView as follows: class VerifyEmail(APIView): serializer_class = EmailVerificationSerializer token_param_config = openapi.Parameter( 'token', in_=openapi.IN_QUERY, description='Description', type=openapi.TYPE_STRING ) @permission_classes([permissions.AllowAny]) @swagger_auto_schema(manual_parameters=[token_param_config]) def get(self, request): token = request.GET.get('token') try: payload = get_payload(request) user = User.objects.get(id=payload['user_id']) if not user.is_verified: user.is_verified = True user.save() return Response({'email': 'Successfully activated'}, status=status.HTTP_200_OK) except jwt.ExpiredSignatureError as identifier: return Response({'error': 'Activation Expired'}, status=status.HTTP_400_BAD_REQUEST) except jwt.exceptions.DecodeError as identifier: return Response({'error': 'Invalid token'}, status=status.HTTP_400_BAD_REQUEST) It is asking for authentication despite me mentioning AllowAny. The complete code is hosted here