Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Django Admin: How to display currently logged in user's ID on the display list?
I am very new to Django and trying to make my first project. I find it difficult to display currently logged in user's ID on the list in Django admin model. I found a solution of how to get the appriopriate ID thanks to Shang Wang (Django admin: Get logged In users id in django) But I don't know how to display this ID on the list, right next to Patient ID, Unit and Create time (mentioned in the code below). My admin.py looks like this : class GeneralAdmin(admin.ModelAdmin): def save_model(self, request, obj, form, change): obj.user = request.user super(GeneralAdmin, self).save_model(request, form, obj, change) list_display = ('id_patient', 'unit', 'create_time') search_fields = ('id_patient', 'unit', 'create_time') readonly_fields = ('unit', 'Birth_date','create_time',) How to put obj.user's ID into list_display to display it on the list like id_patient, unit, or create_time? -
ValueError: Field 'id' expected a number but got ''
I would like to ask for a little help regarding a code since when I start it tells me this following error: enter image description here Here are the views and code def add(request): cart = get_or_create_cart(request) producto = Producto.objects.get(pk=request.POST.get('product_id')) cart.productos.add(producto) return render(request, 'carts/add.html', { 'producto': producto }) enter image description here enter image description here -
Best practice for serializing different data for a ModelSerializer
I have a model named Client that looks like this: class Client(models.Model): first_name = models.CharField("First Name", max_length=50) last_name = models.CharField("Last Name", max_length=50) email_1 = models.EmailField("Email", max_length=50) phone_1 = models.CharField("Phone", max_length=15) My app receives data from 2 different sources Source A source_a_data = { "first_name": "John", "last_name": "Doe", "email_1": "johndoe@gmail.com", "phone_1": "5555555555" } Source B source_b_data = { "firstName": "John", "lastName": "Doe", "email1": "johndoe@gmail.com", "phone1": "5555555555" } I know that creating a serializer for Source A would look like this: serializers.py class SourceAClientSerializer(serializers.ModelSerializer): class Meta: model = Client fields = "__all__" serializer = SourceAClientSerializer(data=source_a_data) serializer.is_valid(raise_exception=True) serializer.save() Would it make sense to create a new ModelSerializer for source B? Or is there something I'm missing? -
Why I am getting black image while converting to jpeg?
from PIL import Image Image.open("image.tiff").convert("RGB").save("some.jpg", "JPEG", quality=100) I have some images with tiff format and while converting them to JPEG format I am getting whole black images for only some images. Why is that happening to only some images ? -
How to get outdated list in history
I want to get list of outdated processes in history list. the backend in django framework. Can anybody give me hints about it?******************************************************************************************* This is my functions in process_resources.py def get_object_list(self, request): tenant = get_tenant_by_header(request) query = Q(tenant=tenant) if (request.GET.__contains__("outdated")): query.add(~Q(process_status__project_status_name='outdated'), Q.AND) return super(ProcessResource, self).get_object_list(request).filter(query) This is location where I have to make changes in react versions.tsx file. { key: 'status', name: __('status'), fieldName: 'status', minWidth: 180, maxWidth: 180, onRender: (record: Process) => record && ( <Stack horizontal> <Stack.Item> <div className={styles.tagStyles} style={{ backgroundColor: record.status.color }}> <Text className={record.status.color == '#000000' ? styles.textStyles : ''} variant={'smallPlus'}> {__(String(record.status.project_status_name))} </Text> </div> </Stack.Item> <Stack.Item> <TooltipHost content={__('view the process review')} directionalHint={DirectionalHint.bottomCenter}> <IconButton onClick={() => clickProcessReview(record)} iconProps={{ iconName: 'SingleColumnEdit' }} /> </TooltipHost> </Stack.Item> </Stack> ), }, ]; useEffect(() => { getVersions(); }, []); const getVersions = () => { const url = `?outdated=true`; props.searchProcessesAction(url, (res: any) => { res.data.objects.length > 0 && setFetchedProcesses(res.data.objects); }); }; const getOutDatedVersions = () => { return fetchedProcesses.filter((i: Process) => i); }; const renderList = () => { if (fetchedProcesses) { return ( <div className={styles.tableWrapper}> <Stack className={styles.table}> <DetailsList items={getOutDatedVersions()} columns={columnsList} setKey="none" layoutMode={DetailsListLayoutMode.justified} isHeaderVisible={true} selectionMode={SelectionMode.none} /> </Stack> </div> ); } return <></>; }; const renderTable = () => { return ( <DocumentCard className={styles.cardStyles}> … -
Unable to add initial tags using tagulous by post-save signal
Hello to all actually i am a new to coadding and also to stack over flow I apologies if the data provided in wrong way. Just correct me in all the issues. I am Unable to add initial/auto tags tags using tagulous by post-save signal I am working on a project which contains smart phones Brands, models, and their specific firmware files. what i want to do is to while posting a table i want to copy brand name model name and the files title into the tags field along with presets of tags. to do so i am using post save signals from django. and getting the below error. 'list' object has no attribute 'pk' Tagulous verison 1.3 below are the code settings i used Models.py class Skill(tagulous.models.TagTreeModel): class TagMeta: initial = [ "Python/Django", "Python/Flask", "JavaScript/JQuery", "JavaScript/Angular.js", "Linux/nginx", "Linux/uwsgi",] space_delimiter = False autocomplete_view = "resource_skills_autocomplete" class resource(models.Model): title=models.CharField(max_length=100) size=models.CharField( max_length=20, default="") desc=models.TextField(default="") file=models.FileField(default="", blank=True) url= models.URLField(max_length=200, blank=True) Brand = models.ForeignKey(brand,on_delete=models.CASCADE, default="") Model = models.ForeignKey(model,on_delete=models.CASCADE, default="") Categories = models.ForeignKey(category,on_delete=models.CASCADE, default="") update_at=models.DateField(auto_now=True) slug=models.SlugField(max_length=200, null=True,blank=True) Tags = tagulous.models.TagField( to=Skill, help_text="This field does not split on spaces" ) Settings.py SERIALIZATION_MODULES = { 'xml': 'tagulous.serializers.xml_serializer', 'json': 'tagulous.serializers.json', 'python': 'tagulous.serializers.python', 'yaml': 'tagulous.serializers.pyyaml', } Admin.py class … -
How to retrieve detail object from mongodb using classic django urls and views?
I'm working on recording server access log into mongodb database; I'm able to record server access log into mongodb database and also able to list all recorded logs applying django-filter in rest api view. But when I'm wondering if there is a possible way to retrieve log detail so that I can use django provided RetrieveUpdateAPIView. I'm using djongo and my log models is from djongo import models as mongo_models class AccessLog(mongo_models.Model): _id = mongo_models.ObjectIdField() user_id = mongo_models.BigIntegerField(null=True, blank=True) user_email = mongo_models.EmailField(null=True, blank=True) path = mongo_models.CharField(max_length=1024, blank=True, null=True) method = mongo_models.CharField(max_length=10, blank=True, null=True) data = mongo_models.TextField(blank=True, null=True) ip_address = mongo_models.CharField(max_length=45, null=True, blank=True) status_code = mongo_models.IntegerField(null=True, blank=True) flag = mongo_models.BooleanField(default=False) remarks = mongo_models.TextField(null=True, blank=True) created_at = mongo_models.DateTimeField(auto_now_add=True) updated_at = mongo_models.DateTimeField(auto_now=True) And my log list views class AccessLogListView(generics.ListAPIView): permission_classes = (AccessLogPermissions, ) filter_backends = [ filters.SearchFilter, DjangoFilterBackend ] filterset_fields = [ 'user_id', 'user_email', 'method', 'ip_address', 'status_code', 'flag', ] search_fields = [ 'remarks', ] serializer_class = AccessLogSerializer queryset = AccessLog.objects.all() And my detail views as class AccessLogUpdateView(generics.RetrieveUpdateAPIView): permission_classes = (AccessLogPermissions,) lookup_field = '_id' serializer_class = AccessLogUpdateSerializer queryset = AccessLog.objects.all() And urls.py as urlpatterns = [ path('', views.AccessLogListView.as_view(), name='list-access-log'), path('<str:_id>/', views.AccessLogUpdateView.as_view(), name='update-access-log'), ] When I try to get by _id the django throws 404 … -
(mysql.W002) MariaDB Strict Mode is not set for database connection 'default'
Please Help me guys??? I want to integrate laravel web app database to my django project and it gives me this error when I run command migrate it gives me this error (mysql.W002) MariaDB Strict Mode is not set for database connection 'default' HINT: MariaDB's Strict Mode fixes many data integrity problems in MariaDB, such as data truncation upon insertion, by escalating warnings into errors -
Country code flag icon is not showing on form in for loop
I am trying to getting flag icon on every edit form of each datatable row have edit button. but unfortunately I can see flag icon only in 1st row of edit form of datatable grid. and in other rows I am not able to see flag icon. Can you help us how can I modified my javascript so I can see flag icon on every edit form of each row of datatable. NOTE : We have code is in Django Python and the variable is in DTL (djnango Template Language) <!--Edit Model Start from Here--> {% for vr in adduser.adduser.all %} <div class="modal fade" id="userEditModal-{{forloop.counter}}" tabindex="-1" role="dialog" aria-labelledby="largeModal" aria-hidden="true"> <div class="modal-dialog modal-lg modal-dialog-centered"> <div class="modal-content"> <form method="POST" action="{% url 'edituser' vr.id %}" class="needs-validation" novalidate> {% csrf_token %} <div class="modal-header"> <h5 class="modal-title">Edit Contact Data</h5> <button type="button" class="close" data-dismiss="modal" aria-label="Close"> <span aria-hidden="true">&times;</span> </button> </div> <div class="modal-body"> <!--Form Start--> <div class="form-row"> <div class="form-group col-md-6"> <label for="FirstName">First Name<span style="color:#ff0000">*</span></label> <input type="text" class="form-control" name="firstname" id="firstname" placeholder="Type FirstName here...." value="{{vr.f_name}}" required /> <div class="valid-feedback">Valid.</div> <div class="invalid-feedback">Please fill out this field.</div> </div> <div class="form-group col-md-6"> <label for="LastName">Last Name<span style="color:#ff0000">*</span></label> <input type="text" class="form-control" name="lastname" id="lastname" placeholder="Type LastName here...." value="{{vr.l_name}}" required /> </div> <div class="valid-feedback">Valid.</div> <div class="invalid-feedback">Please fill out … -
If users log out will their status change?
In django, if a user logs out, will their status change from 'active' to 'not active? Please, I really need to know. Thanks in advance. -
Implementing Django Dropdown with ForeignKeys
I am trying to implement a django dependent dropdown with help of foreign keys in shopping project CRUD models polls models class Products(models.Model): Categories = models.CharField(max_length=15) sub_categories = models.CharField(max_length=15) Colors = models.CharField(max_length=15) Size = models.CharField(max_length=15) image = models.ImageField(upload_to = 'media/',width_field=None,height_field=None,null=True) title = models.CharField(max_length=50) price = models.CharField(max_length=10) sku_number = models.CharField(max_length=10) prod_details = models.CharField(max_length=300) quantity = models.IntegerField(default=0) isactive = models.BooleanField(default=True) categories models class Categories(models.Model): category_name = models.ForeignKey(Products,on_delete=models.CASCADE) category_description = models.CharField(max_length=10) isactive = models.BooleanField(default=True) I am unable to get the dropdown,where am I going wrong? -
Esignature workflow implementation
I need to implement a form in my application with the frontend in flutter and the backend in django. The form needs to be signed by two people. The workflow will be as follows: User A adds their info in the form and signs it. User B adds their info in the same form and signs it. The issue is that I need the form to be in a single-page pdf but once user A signs the pdf, more information cannot be added by user B. I am using Docusign for the e-signatures. How can I implement this workflow? -
Return a model field in django view set
I have a problem with my views,I'm trying to write a view to return my user membership if user has in site,but I get an error membership model is: class Membership(models.Model): membership_type = models.CharField( choices=MEMBERSHIP_CHOICES, default='Free', max_length=30) price = models.DecimalField(max_digits=10, default=0, decimal_places=3) def __str__(self): return self.membership_type user membership is: class UserMembership(models.Model): user = models.ForeignKey('accounts.User', on_delete=models.CASCADE, related_name='user_membership') membership = models.ForeignKey(Membership, on_delete=models.DO_NOTHING, null=True, related_name='membership', default='Free') def __str__(self): return self.user.email view is: class MembershipView(viewsets.ModelViewSet): model = UserMembership serializer_class = UserMemberShipSerializer def get_queryset(self): user_membership_qs = UserMembership.objects.get(user=self.request.user) if user_membership_qs: membership = user_membership_qs.membership return membership I tried Return Response(membership) too,but didn't work, Error is: object of type 'Membership' has no len() -
Run a PHP script with library inside a python django project
I want to run a php script which uses a library "simonblee/aba-file-generator" in a python project. PHP script can be run easily but I dont know where to install this library, as python will not support it. -
AttributeError: 'JpegImageFile' object has no attribute '_committed'
Here I have a small util function which will convert any images to jpeg and stores into a model But while storing I am getting this error AttributeError: 'JpegImageFile' object has no attribute '_committed' function def convert_and_create_image(): img = Image.open("some_img.tiff").convert("RGB") with BytesIO() as f: img.save(f, format='JPEG') f.seek(0) im = Image.open(f) MyModel.objects.create(image=im) When I create model outside IO block then I got this error AttributeError: 'PixelAccess' object has no attribute '_committed' Outside IO block with BytesIO() as f: img.save(f, format='JPEG') f.seek(0) im = Image.open(f) img = im.load() MyModel.objects.create(image=img) -
why can't delete user in django?
Why can't I delete "User"? Every time I get an object of type "User" and do a .delete() to remove it from the database, it jumps out to me that the "relationship" does not exist (see the images below). below), I don't know how to fix that thing :/ def eliminar_pac_pag(request, pk): user = Usuario.objects.get(pk=pk) return render(request, "eliminar_paciente.html", {"Usuario": user}) def eliminar_paciente(request, pk): u = Usuario.objects.get(id=pk) if request.method == "POST": p = Paciente.objects.get(user_id=pk) turno = Turno.objects.filter(solicitante_id=p.pk, confirmado=True) if not turno.exists(): u.delete() p.delete() messages.success(request, "Se borro al paciente exitosamente!") return redirect("Show_users") else: messages.info( request, "No se puede borrar al paciente por que tiene turnos confirmados") return redirect("Show_users") This is the function I created and below is my models. import datetime from django.db import models from django.contrib.auth.models import AbstractUser from django.contrib.auth.models import (BaseUserManager) from django.core.exceptions import ValidationError from django.contrib.auth.models import AbstractBaseUser from django.conf import settings from django.core.validators import MaxValueValidator, MinValueValidator # Create your models here. from abc import ABC, abstractmethod # Cambiar para que se vea más como elde la página o create superuser def validate_decimal(dni): if not dni.isdecimal(): raise ValidationError(f"El dni debe ser numerico") class CustomUserManager(BaseUserManager): def create_user(self, dni, password, nombre_completo, fecha_nac, email, clave, **extra_fields): if not dni: raise ValueError("El dni … -
Celery beat is sending due tasks but the tasks are not getting executed
Problem statement: The celery beat is sending the scheduled task on time. But the worker is not able to receive the task and execute it. I am using the following celery version django-celery-beat==2.2.0 celery==4.4.0 django-celery==3.3.0 The command is being used for celery-beat celery -A project_path.dev beat -l info --scheduler django_celery_beat.schedulers:DatabaseScheduler The command is being used for celery-worker celery worker -A project_path.dev --pool=solo -Q celery -l info task.py @periodic_task(run_every=(crontab(minute='*/30')), options={'queue': settings.CELERY_QUEUES_DICT["celery-periodic"]}) def celery_task(): print("Executing Task") celery-beat logs: [2022-07-03 23:00:00,501: INFO/MainProcess] Scheduler: Sending due task path.to.celery_task (path.to.celery_task) celery-dev logs: [tasks] . path.to.celery_task I see a couple of other tasks are not getting executed. Can I get some help here to understand the issue? -
await self.disconnect(message["code"]) TypeError: ChatConsumer.disconnect() takes 1 positional argument but 2 were given
consumers.py import json from channels.generic.websocket import AsyncWebsocketConsumer # from asgiref.sync import sync_to_async class ChatConsumer(AsyncWebsocketConsumer): async def connect(self): self.room_name = self.scope['url_route']['kwargs']['room_name'] self.room_group_name ='chat_%s' % self.room_name await self.channel_layer.group_add( self.room_group_name, self.channel_name, ) await self.accept() async def disconnect(self): await self.channel_layer.group_discard( self.room_group_name, self.channel_name, ) routing.py from django.urls import path from room import consumers websocket_urlpatterns=[ path('ws/<str:room_name>/',consumers.ChatConsumer.as_asgi()), ] asgi.py import os from django.core.asgi import get_asgi_application from channels.auth import AuthMiddlewareStack from channels.routing import ProtocolTypeRouter, URLRouter import room.routing os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'djangochat.settings') application = ProtocolTypeRouter({ "http":get_asgi_application(), "websocket":AuthMiddlewareStack( URLRouter( room.routing.websocket_urlpatterns ) ) }) error: Exception inside application: ChatConsumer.disconnect() takes 1 positional argument but 2 were given Traceback (most recent call last): File "C:\Users\dines\Desktop\trying_again\venv\lib\site-packages\channels\staticfiles.py", line 44, in __call__ return await self.application(scope, receive, send) File "C:\Users\dines\Desktop\trying_again\venv\lib\site-packages\channels\routing.py", line 71, in __call__ return await application(scope, receive, send) File "C:\Users\dines\Desktop\trying_again\venv\lib\site-packages\channels\sessions.py", line 47, in __call__ return await self.inner(dict(scope, cookies=cookies), receive, send) File "C:\Users\dines\Desktop\trying_again\venv\lib\site-packages\channels\sessions.py", line 263, in __call__ return await self.inner(wrapper.scope, receive, wrapper.send) File "C:\Users\dines\Desktop\trying_again\venv\lib\site-packages\channels\auth.py", line 185, in __call__ return await super().__call__(scope, receive, send) File "C:\Users\dines\Desktop\trying_again\venv\lib\site-packages\channels\middleware.py", line 26, in __call__ return await self.inner(scope, receive, send) File "C:\Users\dines\Desktop\trying_again\venv\lib\site-packages\channels\routing.py", line 150, in __call__ return await application( File "C:\Users\dines\Desktop\trying_again\venv\lib\site-packages\channels\consumer.py", line 94, in app return await consumer(scope, receive, send) File "C:\Users\dines\Desktop\trying_again\venv\lib\site-packages\channels\consumer.py", line 58, in __call__ await await_many_dispatch( File "C:\Users\dines\Desktop\trying_again\venv\lib\site-packages\channels\utils.py", line 51, in await_many_dispatch … -
Tenant not found at 0.0.0.0 django and django-pgschemas
I am using django-pgschemas for multitenancy in my django app. Django version 3.2, python 3.10.5. I have added static tenants in this way, TENANTS = { "live": { "APPS": [ "django.contrib.auth", "django.contrib.sessions", "django.contrib.admin", 'django.contrib.messages', "app_name", ], "DOMAINS": ["live.domain.com"], "URLCONF": "app.urls", }, "public": { "APPS": [ "django.contrib.contenttypes", "django.contrib.staticfiles", "django_pgschemas", "engine", ], }, "default": { "TENANT_MODEL": "engine.Client", "DOMAIN_MODEL": "engine.Domain", "APPS": [ "django.contrib.auth", "django.contrib.sessions", "app_name_2", ], "URLCONF": "app_2.urls", } } This works perfectly with localhost. I am able to access live.localhost:8000 but when I deploy it on digitalocean using docker or apache I get the page not found error. No tenants found at http://0.0.0.0:9000. I have added the domain name in my ALLOWED_HOSTS but it doesn't seem to recognize the static tenant here. -
React component imports from a Django app package
I have created a Django project with a React front-end. I'd like to reuse some of the Django apps and their corresponding React components, so I moved them to a separate Python package following the Django docs: Advanced tutorial: How to write reusable apps. The React components are in the static folders for each Django app and are included with the Python package. The problem I'm running into is that after this new Python package is built and installed in a new Django project, to import a React component I have to import it from the Python package directory (site-packages). Is there a cleaner way to import the React components other than like this? import Comp1A from 'venv/lib/python3.10/site-packages/app_pkg/app1/static/app1/js/comp1a'; This is problematic since the location of site-packages can vary from project to project. Is there at least a dynamic way to generate this path? I can use module.exports.resolve.alias in my webpack.config.js to only set it once in the project, but I would, at least, like to be able to generate the alias automatically. -
how can I change django application server port number in spyne
I am trying to run the spyne Django soap server project on my computer but I can't run the project because the default port number which is 8000, is already in use so I want to change the port number of django soap server. the related project the related code: class Attributes(DjangoComplexModel.Attributes): django_model = FieldContainer django_exclude = ['excluded_field'] class HelloWorldService(Service): @rpc(Unicode, Integer, _returns=Iterable(Unicode)) def say_hello(ctx, name, times): for i in range(times): yield 'Hello, %s' % name class ContainerService(Service): @rpc(Integer, _returns=Container) def get_container(ctx, pk): try: return FieldContainer.objects.get(pk=pk) except FieldContainer.DoesNotExist: raise ResourceNotFoundError('Container') @rpc(Container, _returns=Container) def create_container(ctx, container): try: return FieldContainer.objects.create(**container.as_dict()) except IntegrityError: raise ResourceAlreadyExistsError('Container') class ExceptionHandlingService(DjangoService): """Service for testing exception handling.""" @rpc(_returns=Container) def raise_does_not_exist(ctx): return FieldContainer.objects.get(pk=-1) @rpc(_returns=Container) def raise_validation_error(ctx): raise ValidationError(None, 'Invalid.') app = Application([HelloWorldService, ContainerService, ExceptionHandlingService], 'spyne.examples.django', in_protocol=Soap11(validator='lxml'), out_protocol=Soap11(), ) hello_world_service = csrf_exempt(DjangoApplication(app)) -
Django Project Install error (The conflict is caused by: The user requested asgiref==3.2.5 django 3.1.14 depends on asgiref<4 and >=3.2.10)
When I try to install requirements.txt this error happened. This is requirements.txt asgiref==3.2.5 astroid==2.3.3 certifi==2019.11.28 chardet==3.0.4 colorama==0.4.3 defusedxml==0.6.0 dj-database-url==0.5.0 Django==3.1.14 django-allauth==0.41.0 django-crispy-forms==1.9.0 django-heroku==0.3.1 gunicorn==20.0.4 idna==2.9 isort==4.3.21 lazy-object-proxy==1.4.3 mccabe==0.6.1 oauthlib==3.1.0 Pillow==9.0.1 pylint==2.4.4 PySocks==1.7.1 python3-openid==3.1.0 pytz==2019.3 requests==2.23.0 requests-oauthlib==1.3.0 six==1.14.0 sqlparse==0.3.1 stripe==2.43.0 This error says *ERROR: Cannot install -r requirements.txt (line 8) and asgiref==3.2.5 because these package versions have conflicting dependencies. The conflict is caused by: The user requested asgiref==3.2.5 django 3.1.14 depends on asgiref<4 and >=3.2.10 To fix this you could try to: loosen the range of package versions you've specified remove package versions to allow pip attempt to solve the dependency conflict ERROR: ResolutionImpossible: for help visit https://pip.pypa.io/en/latest/topics/dependency-resolution/#dealing-with-dependency-conflicts* -
Intro.JS possible to check user input before proceed
So, i want to come out with the Javascript which forced user to input / select anything before going to next step, (like forced user to press button, input their name, etc). I am working on Django Framework with mix together with Javascript and HTML together. Ignore the first part as I am trying to assign each function to the button so the button can do different tasks individually. But it wont work in the intro.js script. Code snipper are below: <script> /* var btn1=document.getElementById("button1"); var btn2=document.getElementById("button2"); var div=document.getElementById("InputName"); btn1.onclick=function(){ if (div.style.display !=="none") { div.style.display="none"; } else { div.style.display="block"; } }; // this is the crucial part btn2.onclick=function(){ var steps=[ {element:"#button1",intro:"A button", position:"right"}, {element:"#button2",intro:"This goes away sometimes"} ]; if (div.style.display==="none") { steps.splice(1,1); } introJs().setOptions({ steps:steps }).start(); } */ var steps=[ {element:"#InputName",intro:"Please fill your name", position:"right"}, {element:"#InputUsername",intro:"Please fill your username"}, {element:"#button1",intro:"Succesfully Filled, press register."} ]; introJs().setOptions({ steps:steps }).start(); -
How to use a signal to override/block a Django api request?
I've implemented a signal for my API endpoint, and I would like it to restrict access to the endpoint when the logic for the signal evaluates to false. Is there a nice way to do this? I noticed in my logs that it is properly evaluating to true or false, but it doesn't actually cause my view to send a 500 or some way of saying "access restricted". Rather, it still sends the normal API response. handlers.py from corsheaders.signals import check_request_enabled def cors_allow_mysites(sender, request, **kwargs): if ("Origin" in request.headers) and (request.headers["Origin"] == 'https://url.com'): print("Handler allowed") return True print("Handler not allowed") return False check_request_enabled.connect(cors_allow_mysites) apps.py from django.apps import AppConfig class ApiEndpointConfig(AppConfig): default_auto_field = 'django.db.models.BigAutoField' name = 'api_endpoint' def ready(self): # Makes sure all signal handlers are connected from . import handlers # noqa __init.py default_app_config = "api_endpoint.apps.ApiEndpointConfig" -
Is it possible to have two different lockout reset settings for django-axes lockout?
I am using a custom view django login and is currently implementing throttling for failed login attempt. Currently I am utlising Django-axes for this purpose. I have successfully implemented 'soft lockout' for my failed login attempt (lockout by username for every 10 failed login attempt within 5 minutes). I would like to check if it is also possible to implement a 'hard lockout' (verify no more than 100 failed attempt per hour is possible on a single account) along with this 'soft lockout'? This is what I have done for my 'soft lockout' settings.py INSTALLED_APPS = [ ..., 'axes' ] AUTHENTICATION_BACKENDS = ( "axes.backends.AxesBackend", ... ) # django-Axes systems # https://raw.githubusercontent.com/jazzband/django-axes/master/docs/4_configuration.rst ## basic configuration for login attempt and lockout duration AXES_FAILURE_LIMIT = 10 AXES_LOCK_OUT_AT_FAILURE = True AXES_COOLOFF_TIME = 0.083 # lockout 5 mins AXES_RESET_COOL_OFF_ON_FAILURE_DURING_LOCKOUT = False AXES_ONLY_USER_FAILURES = True AXES_RESET_ON_SUCCESS = True ## custom account soft lockout message AXES_LOCKOUT_CALLABLE = 'customlogin.views.user_lockout' CUSTOM_AXES_SOFT_LOCKOUT_MESSAGE = 'Too many failed login attempts. Please try again in 5 minutes.' ## fields to use for checking AXES_USERNAME_FORM_FIELD = 'email' ## logging for db AXES_DISABLE_ACCESS_LOG = True AXES_ENABLE_ACCESS_FAILURE_LOG = True AXES_ACCESS_FAILURE_LOG_PER_USER_LIMIT = 300 views.py from axes.decorators import axes_dispatch @axes_dispatch def user_login(request): # main body of code def …