Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
(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 … -
how to upload image file from project directory in django?
I have this function which will convert any images to jpg format. While doing this it saves the file inside my project root directory but what I want is I want to upload it into my model and remove that image from the directory. def convert_image_to_jpg(image): from PIL import Image im = Image.open(image).convert("RGB").save("some.jpg", "JPEG", quality=100) # save into the model MyModel.objects.create(image=im) In my model I am getting None values for image but inside the project root directory there is a image in jpg format. -
Error Deploying Django App on Elastic Beanstalk
I'm trying to deploy my Django app on elastic beanstalk. It is saying that it is deployed, but the health immediately turns red and I see "502 Bad Gateway / Nginx" when I try to go to the site. I know there are other answers to this question on stack overflow, but I am still stuck. In my logs I see web: ModuleNotFoundError: No module named 'mysite.wsgi'. In my file repos/mydjangoproject/mysite/.ebextensions/django.config I have aws:elasticbeanstalk:application:environment: DJANGO_SETTINGS_MODULE: "core.settings" PYTHONPATH: "/var/app/current:$PYTHONPATH" aws:elasticbeanstalk:container:python: WSGIPath: mysite.wsgi:application And I have a file: repos/mydjangoproject/mysite/mysite/wsgi.py Which contains import os from django.core.wsgi import get_wsgi_application os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'mysite.settings') application = get_wsgi_application() I also am seeing these errors 2022/07/04 01:57:50 [error] 3507#3507: *536 connect() failed (111: Connection refused) while connecting to upstream, client: 172.31.22.27, server: , request: "GET / HTTP/1.1", upstream: "http://127.0.0.1:8000/", host: "44.241.154.93" 2022/07/04 01:57:50 [error] 3507#3507: *536 connect() failed (111: Connection refused) while connecting to upstream, client: 172.31.22.27, server: , request: "GET /blog/wp-includes/wlwmanifest.xml HTTP/1.1", upstream: "http://127.0.0.1:8000/blog/wp-includes/wlwmanifest.xml", host: "44.241.154.93" I have gunicorn installed and in my requirements.txt. Any thoughts on what I might be doing wrong would be appreciated! -
how can I import django to my python path
I started my project, it was running successfully until I returned back to continue, and encountered this problem. I typed 'python manage.py makemigrations' and this error message popped up on terminal 'ImportError: Couldn't import Django. Are you sure it's installed and available on your PYTHONPATH environment variable? Did you forget to activate a virtual environment?' How can I resolve this problem -
Django CORS Handler is false but not but not rejecting API requests
When I run my Django CORS framework, nothing gets filtered out. The value gets evaluated to false when I insert print statements to the handlers but it's not filtering out requests to my view endpoint. Do I need to make any changes to my view? Am I missing something that will make it reject requests that don't meet the criteria in cors_allow_mysites? handlers.py from corsheaders.signals import check_request_enabled def cors_allow_mysites(sender, request, **kwargs): return ("Origin" in request.headers) and (request.headers["Origin"] == 'url.com') 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" -
What unit tests could I build for a class like this?
I have several such classes in my views. And I need to test them all. class ExampleViewSet(viewsets.ModelViewSet): serializer_class = ExampleSerializer queryset = Example.objects.all() filter_backends = (filters.DjangoFilterBackend,) filterset_class = ExampleFilter All were created with the help of available Django Rest Framework libraries. -
How to maintain metrics after restart server?
I'm using Prometheus to monitor my local Django server. I successfully connected them and wrote a custom metric custom_counter in code. Unfortunately, I recognized that the custom metrics the metric custom_counter_total would always reset to 0 every time I restart my server. It sounds bad because I can only see something about it since the last time I restarted the server. Is there any method to save the metrics so we can persist the metrics even after resetting server? Thanks in advance! -
Django Cors Handler evaluating to false but not rejecting API requests
My Django Cors Framework Handler is being ran, but is not filtering anything out. When I inserted print statements to the handlers, I saw that the value was evaluating to false (meaning it had the signal to reject) but it was not actually filtering out requests to my view endpoint. I did not make any changes to my view (I was under the assumption I did not need to). Am I missing something that will make it reject requests that don't meet the criteria in cors_allow_mysites. handlers.py from corsheaders.signals import check_request_enabled def cors_allow_mysites(sender, request, **kwargs): return ("Origin" in request.headers) and (request.headers["Origin"] == 'url.com') 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"