Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Why are styles not pulled when running a django application through nginx?
I know that I have a large number of similar questions, and I tried probably all the proposed options, but it didn't help me, maybe I'm doing something wrong. The problem is that when i start normal all the styles are pulled up and everything works, but when i do it through the server for production, they disappear Here is an example of the code used: settings.py: STATIC_URL = '/static/' STATIC_ROOT = os.path.join(BASE_DIR, "staticfiles") nginx.conf: upstream hello_django { server web:8000; } server { listen 80; location / { proxy_pass http://hello_django; proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for; proxy_set_header Host $host; proxy_redirect off; } location /static/ { alias /home/app/web/staticfiles/; } location /media/ { alias /home/app/web/mediafiles/; } } docker-compose.prod.yml: version: '3.8' services: web: build: context: ./app dockerfile: Dockerfile.prod command: gunicorn hello_django.wsgi:application --bind 0.0.0.0:8000 volumes: - static_volume:/home/app/web/static - media_volume:/home/app/web/media expose: - 8000 env_file: - ./.env.prod depends_on: - db healthcheck: test: ["CMD-SHELL", "pg_isready -U hello_django -h db"] interval: 10s timeout: 5s retries: 3 db: image: postgres:15 volumes: - postgres_data:/var/lib/postgresql/data/ environment: - POSTGRES_USER=hello_django - POSTGRES_PASSWORD=hello_django - POSTGRES_DB=hello_django_prod nginx: build: ./nginx volumes: - static_volume:/home/app/web/staticfiles - media_volume:/home/app/web/mediafiles ports: - 1337:80 depends_on: - web volumes: postgres_data: static_volume: media_volume: Maybe someone has already solved a similar problem and can help me with it? -
How to avoid sorting of Dictonary keys in Ajax response
I am sending an ajax call to get data from server side. $.ajax({ dataType: 'json', type: "POST", data: { 'data':["100","102","101"] , "compare_data": 0, "category": category_val, "type": type }, url: "{% url 'test:test_search' %}", beforeSend: function () { $("#loader-div").show(); }, success: function (data) { console.log(data,"data") } }); from the server side I am returning JsonReponse. Attaching sample here Response: response={"100":"test","102":"test12","101":"test13"} return JsonResponse({'status':'200','response':response}) But when I see the response dictonary in javascript it is changing as {"100":"test","101":"test13","102":"test12"} The response is getting sorted. Is there a way to stop sorting of keys ? I tried changing the type of key to string, even the values are getting sorted. -
Signup form in Django not showing checkboxinput as checkboxinput
I want to add "Accept termns and conditions" to signup form in my Django project. As I did before in a different form I added this: class SignUpForm(UserCreationForm): email = forms.CharField(max_length=254, required=True, widget=forms.EmailInput()) -> accept = forms.BooleanField(required=True, widget=CheckboxInput, label="I Accept the TNC!") class Meta: model = User fields = ('username', 'email', 'password1', 'password2') It shows you this: enter image description here I can not check it, I can not write in it. While in a different form I added the same way and that works normally. It is really weird for me, I am only a beginner to Django. I tried with empty argument section like this: class SignUpForm(UserCreationForm): email = forms.CharField(max_length=254, required=True, widget=forms.EmailInput()) accept = forms.BooleanField() class Meta: model = User fields = ('username', 'email', 'password1', 'password2') Showing the same. -
How to write an excel file on user desktops using a Python program running on AWS
We have an application, the UI of which is developed using React and is running on user’s laptops/desktops, and the backend is developed using Django and is running on AWS. When we create an excel output of a dataframe, it is getting saved in ec2 instead of the user’s laptop, which is quite understandable. But how do we create these output files on the individual user’s laptops, instead of ec2, since these users are not having direct access to AWS? -
When trying test django.db.utils.OperationalError: (1071, 'Specified key was too long; max key length is 3072 bytes')
When trying test django python manage.py test It shows the error like this, django.db.utils.OperationalError: (1071, 'Specified key was too long; max key length is 3072 bytes') mysql version is mysql Ver 8.1.0 for macos14.0 on arm64 (Homebrew) It occurs only when testing. I don't do any special settiing for testing database. 'default': { 'ENGINE': 'django.db.backends.mysql', "NAME": config("DB_NAME"), "USER": config("DB_USER"), "PASSWORD": config("DB_PASSWORD"), "HOST": config("DB_HOST"), "PORT": "3306", 'OPTIONS': { 'charset': 'utf8mb4', }, } -
django-helpdesk 0.4.1 "extendMarkdown() missing 1 required positional argument: 'md_globals'"
When I try to view /tickets/1/ I get the error: extendMarkdown() missing 1 required positional argument: 'md_globals' /usr/local/lib/python3.9/dist-packages/markdown/core.py, line 115, in registerExtensions How can I fix this? -
How to save logical expressions in django?
I have a model in my django project like this: class Condition(models.Model): activity = models.CharField(max_length=50) operator = models.CharField(max_length=50) condition = models.IntegerField() Suppose we store the user's activity in another model called UserActivity and we want to check whether the user has performed that activity more than the condition times. But this is not enough. I want to combine these Condition objects with logical operators like AND and OR and XOR and NOT etc. Can you help me to do this? Suppose the person who wants to create rules does not have engineering knowledge and I have to think about comfortable user experience -
Django failing to import app in a different directory
A codebase which is working in another local machine isn't working on mine and this is taking far more time that I have expected. Command to run the application: python3 manage.py runserver --settings=config.settings.local Directory: --- Config ----> Settings ----> urls.py ----> wsgi.py ----> asgi.py ----> __init__.py --- Pybo ----> views ----> apps.py ----> urls.py ----> views ------> indicator_views.py ------> profile_check.py After running the command, I am encountering 404 Error saying "No Board matches the given query". If I try to view the definition of the imported app by clicking from pybo.views import indicator_views, profile_check inside the /config/urls.py/, the intellisense complains No definition found for views. Thus, I'm suspecting that the config/urls.py isn't correctly importing components located inside the other directory. Is there a way that I can solve this? It's my first time using Django, and I believe the structure is a bit weirdly established but I was given this codebase and I should apparently start from what I have. I also tried running in a venv, but it would complain that background-task isn't installed. And once I finish installing the package, it complains that urls.conf is deprecated so abandoned using venv. -
Is it possible to annotate a column which contains a queryset?
I want to show a table on a HTML template with data from GroupCaseFile model. But one of the columns must contain data from the most recent ProceduralAct object, specifically: 'act_number', 'act_type', and 'act_summary' (inside a single cell of the HTML table). I could simply use something like this to get it: group_case_file.case_file.proceduralact_set.all().order_by('-created_at').first() But, before getting the last ProceduralAct, I want to apply filtering by search term. The search term should cover 'act_number', 'act_type', and 'act_summary' from the corresponding last ProceduralAct. To be able to do this search, I have tried using nested subqueries, like I did with 'summary' on the code below, to annotate 'summary' value in the GroupCaseFile query, and only then apply the filtering by search term. I think this would be enough if I wanted to get search only 'summary'. But I want to know if there is any way to annotate a column, let's say last_procedural_act, which can contain a QuerySet of the corresponding most recent ProceduralAct row. That way, I could perform search on all of the fields of that ProceduralAct row I'd appreciate if there is a different approach for this. Models class CaseFile(models.Model): code = models.CharField(primary_key=True, max_length=30) # More fields class GroupCaseFile(models.Model): … -
Run Django query and time out after X seconds
I want to build a function which takes a query in MariaDB/MySQL (it's the same engine in Django) and times out after X seconds and executes a faster, heuristical query. I found a PostGreSQL example: with transaction.atomic(), connection.cursor() as cursor: cursor.execute("SET LOCAL statement_timeout TO 50;") try: return cursor.execute(my_query) except OperationalError: pass with connection.cursor() as cursor: cursor.execute(heuristic_query) return int(cursor.fetchone()[0]) I want to do the same for MariaDB/MySQL but I read that a) you have to set it directly before the query AND that the way max_statement_time is implemented in MariaDB and MySQL differs from one another. Any ideas how I would build such a thing? Thx! -
How to keep scheduled jobs of celery worker in docker container? (django, celery, redis, docker)
I deploy my django app with docker. When I update my deployment, I stop current running container and start new container with new image. I start my celery worker in the created container. (exec -> celery worker) The problem is that the scheduled jobs (not executed yet) of celery in old container are gone since the worker gets shutdown when the container the worker is in is stopped. I understand why it happens but cannot think of how to make celery worker persistent because I think the worker is dependent on the django app. I thought the broker keeps the job and new celery worker gets connected with the broker again so the new worker would execute the jobs, receiving them from the broker. So I kept the redis container (broker) intact, not stopping or restarting it. But the new worker did not execute the previously scheduled jobs. (I think I misunderstood how brokers work) I think there can be two ways store jobs in somewhere and get all celery workers refer to it make persistent celery worker but not sure if they are possibile. Any solutions are welcome. Thank you! -
Integrating Gmail API with Django to Receive Email Details in Real-time
I am developing a Django application that needs to respond to incoming emails in Gmail. Currently, I am using a Pub/Sub subscription to receive notifications with the latest history ID whenever there is a change in the user's inbox. However, this approach only provides limited information, and I need to retrieve detailed information about the received emails. I noticed that platforms like Zapier have a feature where they receive real-time updates with email details, allowing users to trigger actions based on incoming emails. I would like to implement a similar functionality in my Django application. Here are my specific questions: Is there a way to receive real-time updates or notifications in my Django application when a user receives an email in their Gmail inbox? How can I retrieve detailed information about the sender, subject, and content of the received email in real-time? I have looked into the Gmail API documentation but couldn't find a clear solution. Can anyone provide guidance or share an example of how to achieve this? Additionally, if there are any specific features or endpoints in the Gmail API that support real-time email updates, I would appreciate guidance on where to find this information. Thank you for … -
Django - DetailView with foreign key resulting in NoReverseMatch error
I have a Profile model that has a one-to-one relationship with User model. The user should be able to view and edit their profile after logging in but I am running into multiple problems in accomplishing this. Guidance and suggestions are appreciated. Model.py class Profile(models.Model): "" user = models.OneToOneField( User, on_delete=models.CASCADE ) first_name = models.TextField( db_comment="", default="", max_length=55, null=True ) last_name = models.TextField( db_comment="", default="", max_length=55, null=True ) zipcode = models.TextField( db_comment="", default="00000", max_length=5, null=True ) def __str__(self) -> str: return f"{self.first_name} {self.last_name}" Urls.py # User Profile Detail path("accounts/profile/", ProfileDetailView.as_view(), name="profile_detail"), Views.py class ProfileDetailView(DetailBreadcrumbMixin, DetailView, LoginRequiredMixin): model = Profile template_name = "account/profile.html" def get_object(self, queryset=None): return self.model.objects.get(user_id=self.request.user.id) For some reason when I try to access http://localhost:8000/accounts/profile/ after logging in I get the following error even though I am using a detail view. NoReverseMatch at /accounts/profile/ Reverse for 'profile_list' not found. 'profile_list' is not a valid view function or pattern name. -
Pre-populate FK relation with logged in user without dropdown in GET request
I would like to pre-populate fields with driver info into html page(more driver into needed) which he already filled during registration(as a normal user) for example "username" I am able to do for all fields except user field is shown as dropdown with all the users list in html page Here are my urls, models, forms, views and html page info: urls.py path('driver_info/', driver_info, name='driver_info'), views.py @login_required(login_url='login') def driver_info(request): p_form = DriverUserInfoForm(instance=request.user.driverprofile) context = { 'p_form' : p_form } return render(request, 'driver/driver_info.html', context) models.py class DriverProfile(models.Model): user = models.OneToOneField(CustomUser, on_delete=models.CASCADE) is_verified = models.BooleanField(default=False) is_active = models.BooleanField(default=False) driving_license_number = models.CharField(max_length=25, unique=True, verbose_name="DL Number") expiry_date = models.DateField(verbose_name="DL Expiry Date") def __str__(self): return self.user.username forms.py class DriverUserInfoForm(forms.ModelForm): class Meta: model = DriverProfile exclude = ('is_verified', 'is_active',) drive_info.html {% block content %} <h3>Driver info</h3> <form action="" method="POST"> {% csrf_token %} {{ p_form }} <input type="submit" value="Next" /> </form> {% endblock %} In- case CustomUser model needed, here it is: users/models.py class CustomUser(AbstractUser): mobile_no = models.CharField(max_length=12) def __str__(self): return self.username I have tried to set the value in init method inside forms.py but no luck I tried having a new CharField in forms.py but not able to fill the value with current user username **Could … -
How to install requests-ntlm2?
I could not install the requests-ntlm2 package for API integration in my Django project (python2.7.17). Error: -
cannot use django.models.connection to log django raw query
I cannot log SQL when I use django ORM raw query reset_queries() TwilioContent.objects.raw( "delete from %s where id in %s", [TwilioContent._meta.db_table, json.dumps(tuple(external_trans))], ) for i in connection.queries: print(f"{i['sql']}\n") How do I fix this? -
Django annotate with Count on subquery with OuterRef failing
TLDR: Lets hit overall problem here 1st: How in django annotate queryset with a Subquery that uses OuterRef and count how many objects subquery returned (for every object in original query) Pseudocode: Model.objects.annotate(count=Count(Subquery(Model2.objects.filter(rel_id=OuterRef("id")).values_list("some_field").distinct()))) Full description I have couple of models: class Model1(models.Model): model2 = models.ForeignKey(Model2, related_name="one_model2") model2_m2m = models.ManyToMany(Model2, related_name="many_model2") new_field = models.BooleanField() class Model2(models.Model): model3 = models.ForeignKey(Model3) class Model3(models.Model): ... I need to make a query that checks for every Model1 objects whether for every Model2 related objects (through model2 or model2_m2m) their related model3 uniquely count more than 1. If yes, set new_field to True. For example model1 related with model2.model3 = 1 and model2_m2m = [model2.model3 = 1] This results in new_field = False but model1 related with model2.model3 = 1 and model2_m2m = [model2.model3 = 2] Results in it being True So what was my approach? I created suquery from Model2: sub_model2 = Model2.objects.filter(one_model2=OuterRef("id") | many_model2=OuterRef("id")) And then used it in various ways to annotate Model1: Model1.objects.annotate(my_annotation=Subquery(sub_model2.values_list("model3", flat=True).distinct().aggregate(<here is counting>) Result in error that This should be put in subquery(? isnt it?) [This queryset contains a reference to an outer query and may only be used in subquery] When trying to Count it as this: Model1.objects.annotate(my_annotation=Count(Subquery(sub_model2.values_list("model3", … -
odd behavior extending django tutorial with urlpatterns
building a new django site following the first app tutorial created polls ok and site.urls.py from django.contrib import admin from django.urls import include, path urlpatterns = [ path("polls/", include("polls.urls")), path("admin/", admin.site.urls), ] All is well and http://localhost:8000/polls/ gives the proper response "Hello World..." Now I run python manage.py startapp brollysaas and the folders get created site.urls now from django.contrib import admin from django.urls import include, path urlpatterns = [ path("polls/", include("polls.urls")), path("brolly/", include("brollysaas.urls")), path("admin/", admin.site.urls), ] I am getting ModuleNotFoundError: No module named 'brollysaas.urls' everything else is the same as polls includding settings. So I cannot figure out the error or remedy. Thanks for your help. -
Django rest framework does not save user to Postgres, no error
I have a project that is connected to a postgres db on AWS but when I go to create a user the user does not get saved. I was able to create a superuser with the python manage.py createsuperuser command. I can also see the superuser appear correctly in the database using PGAdmin. models.py class UserManager(BaseUserManager): def _create_user(self, email, password,first_name,last_name,is_staff, is_superuser, **extra_fields): if not email: raise ValueError('Users must have an email address') now = timezone.now() email = self.normalize_email(email) user = self.model( email=email, is_staff=is_staff, is_active=True, is_superuser=is_superuser, last_login=now, date_joined=now, first_name = first_name, last_name = last_name, **extra_fields ) user.set_password(password) user.save(using=self._db) return user def create_user(self, email, password, first_name, last_name, **extra_fields): user = self._create_user(email, password, first_name, last_name, False, False, **extra_fields) user.save(using=self._db) return user # return self._create_user(email, password, first_name, last_name, False, False, **extra_fields) def create_superuser(self, email, password, **extra_fields): user=self._create_user(email, password, None, None, True, True, **extra_fields) user.save(using=self._db) return user # Custom user model class User(AbstractBaseUser, PermissionsMixin): email = models.EmailField(max_length=254, unique=True) name = models.CharField(max_length=254, null=True, blank=True) first_name = models.CharField(max_length=254, null=True, blank=True) last_name = models.CharField(max_length=254, null=True, blank=True) is_staff = models.BooleanField(default=False) is_superuser = models.BooleanField(default=False) is_active = models.BooleanField(default=True) last_login = models.DateTimeField(null=True, blank=True) date_joined = models.DateTimeField(auto_now_add=True) serializer.py class UserSerializer(ModelSerializer): class Meta: model = User fields = '__all__' extra_kwargs = { 'password': {'write_only': … -
How to use Common Workflow Language (CWL) with viewflow?
Looking for ways to build workflows for viewflow that business analysts can use without writing code. A graphical painter/editor like those for CWL may be just the ticket, but I have not found a way to use it. If there is a tool for CWL or BPMN for graphically building workflows that can be consumed and executed with viewflow, please advise Looking for a reference to a graphical tool to build viewflow workflows. -
Email with HTML format insert data in it
New on this. Trying to send email from python with HTML format. Inside HTML how do I insert python data. Please if someone can tell me the syntax. Thank you I was trying to attach html page as I click send button. It is taking the page and send it but not the data. Only static data. -
HTML file rendering correctly in one file but not being rendered or usable in another file?
I have the following user_obj.HTML code for a template: {% block content %} <style> .task-item{ background-color: #aba9a9; height: 120px; margin-bottom: 10px; border-radius: 16px; padding: 10px; } .Q3{ flex-basis:60%; background-color: #f2f2f2; border-radius: 16px; overflow: auto; height: 75%; padding: 10px; scrollbar-width: 0px; /* "thin" or "auto" */ scrollbar-color: transparent; } .Q3::-webkit-scrollbar { /* Adjust the width as needed */ background-color: transparent; /* Make the background transparent */ } .Q3::-webkit-scrollbar-track { background-color: transparent; /* Make the track background transparent */ } /* Hide arrows in Firefox */ .Q3::-webkit-scrollbar-button { display: none; } </style> <html> <body> <div class="Q3"> {% for task in user_obj %} <div class="task-item"> <h3>{{ task.name }}</h3> <p>{{ task.description }}</p> <p>Due Date: {{ task.time_left|date:"F j, Y" }}</p> </div> {% endfor %} </div> </body> </html> {% endblock %} This html code does exactly what I want and it works. Now in the following main.HTML file I have: {% extends 'base_content.html' %} {% block content %} <style> html,body{ margin:0; padding:0; width:100%; height:100%; } .Q3{ flex-basis:60%; background-color: #f2f2f2; border-radius: 16px; overflow: auto; height: 75%; padding: 10px; scrollbar-width: 0px; /* "thin" or "auto" */ scrollbar-color: transparent; } .Q3::-webkit-scrollbar { /* Adjust the width as needed */ background-color: transparent; /* Make the background transparent */ } .Q3::-webkit-scrollbar-track … -
how is the django's channels performance?
i have a website for chatting and dating . and this website is programmed in django and channels of django. this website will make a WebSocket connect since the user enter to the website (not only when they chat). Why ? i want to show notifications when someone show the user's profile i want to show notifications when someone send a massage to the user i want to show notifications when someone block or like the user's profile and a lot of ideas the picture My question is : is channels alone enough to handle more than 25,000 connection a day easly ? or what will happen in this case ? please advise me. what should i do ? -
Dockerized Django backend fails to connect to Postgress
I have a Django/Gunicorn/Ngnix/Postgres project deployed in docker containers in a DigitalOcean ubuntu droplet. When running docker-compose up I get this error: dev | Traceback (most recent call last): dev | File "/env/lib/python3.10/site-packages/django/db/utils.py", line 113, in load_backend dev | return import_module("%s.base" % backend_name) dev | File "/usr/local/lib/python3.10/importlib/__init__.py", line 126, in import_module dev | return _bootstrap._gcd_import(name[level:], package, level) dev | File "<frozen importlib._bootstrap>", line 1050, in _gcd_import dev | File "<frozen importlib._bootstrap>", line 1027, in _find_and_load dev | File "<frozen importlib._bootstrap>", line 992, in _find_and_load_unlocked dev | File "<frozen importlib._bootstrap>", line 241, in _call_with_frames_removed dev | File "<frozen importlib._bootstrap>", line 1050, in _gcd_import dev | File "<frozen importlib._bootstrap>", line 1027, in _find_and_load dev | File "<frozen importlib._bootstrap>", line 1004, in _find_and_load_unlocked dev | ModuleNotFoundError: No module named 'None' dev | dev | The above exception was the direct cause of the following exception: dev | dev | Traceback (most recent call last): dev | File "/app/manage.py", line 22, in <module> dev | main() dev | File "/app/manage.py", line 18, in main dev | execute_from_command_line(sys.argv) dev | File "/env/lib/python3.10/site-packages/django/core/management/__init__.py", line 446, in execute_from_command_line dev | utility.execute() dev | File "/env/lib/python3.10/site-packages/django/core/management/__init__.py", line 420, in execute dev | django.setup() dev | File "/env/lib/python3.10/site-packages/django/__init__.py", line … -
Validador Rut/Run chileno
/*Tengo esos 2 campos donde se debe ingresar el rut y el dv. como seria el js para una validación de rut existente. */ <div class="form-group mb-4"> <input type="text" name="rut" id="rut" class="form-control" placeholder="Rut" maxlength="8" minlength="7" pattern="[0-9]*" title="Debe ingresar valores númericos" required/> <label class="form-label" for="rut"></label> </div> <div class="form-group text-center mb-4"> <input type="text" name="dv" id="dv" class="form-control" maxlength="1" pattern="[1-9kK]*" title="Solamente se permite Números, SI SU RUT TERMINA CON 0 INGRESAR K" placeholder="Dv" required/> <label class="form-label" for="dv"></label> </div> /* Con este codigo logro me funcione el validador de cierta manera el problema es que tampoco me permite la creacion de usuarios con rut existentes */ function validarRut(rut, dv) { if (rut.trim() === "" || !/^[0-9]+[-|‐]{1}[0-9kK]{1}$/.test(rut)) { return false; } rut = rut.replace(/\./g, "").replace("-", ""); var splitRut = rut.split("-"); var cuerpoRut = splitRut[0]; var dvUsuario = splitRut[1]; var suma = 0; var multiplo = 2; for (var i = cuerpoRut.length - 1; i >= 0; i--) { suma += parseInt(cuerpoRut.charAt(i)) * multiplo; multiplo = multiplo < 7 ? multiplo + 1 : 2; } var dvEsperado = 11 - (suma % 11); dvEsperado = (dvEsperado === 11) ? 0 : (dvEsperado === 10) ? "K" : dvEsperado.toString(); return dvEsperado.toUpperCase() === dv.toUpperCase(); } document.addEventListener("DOMContentLoaded", function() { …