Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
What AWS Service I need for Docker Containers and team work
Right now I work as trainee in small IT Company I have a task to write a documentaion for other trainee "How upload our tg bot on AWS" & "How use Docker Containers in AWS" I don't have problems with Docker, because I have a lot of experience with it before, but I never work with AWS. It has a lot of service and I lost in them all What I need? Run a telegram-bot & Django server in Docker container Be able to have all trainee able to run their container Comfortable service to control containers Or if be simple, we need a AWS service to run a Docker Container which Run a telegram-bot and Django Server The question is: What service I need to work with? -
Excel export using loop in Django
I am working a project, which have some information about Customer. I am exporting Excel file using xlwt library. I have a booking list: [<Booking: +6055664554>, <Booking: +6055664554>, <Booking: +6055664554>, <Booking: +6055664554>, <Booking: +6055664554>, <Booking: +6055664554>] My export function: def export_shimpent_xls(request,id): response = HttpResponse(content_type='application/ms-excel') shipment = Shipment.objects.get(pk=id) file_name = "shipment_list_of_"+str(shipment.shimpment_number)+".xls" response['Content-Disposition'] = 'attachment; filename="'+ file_name +'"' wb = xlwt.Workbook(encoding='utf-8') ws = wb.add_sheet('Shipment Booking List') bookings_list = shipment.booking_list #taking existing booking list which is already added in shipment bookings = [] if bookings_list: for booking in bookings_list: data = Booking.objects.get(booking_reference=booking) bookings.append(data) # Sheet header, first row row_num = 0 font_style = xlwt.XFStyle() font_style.font.bold = True columns = ['Ref Number', 'Name', 'Destination', 'Mobile Number', 'Weight','Carton','Payment Mode','Remark','Delivery Status',] for col_num in range(len(columns)): ws.write(row_num, col_num, columns[col_num], font_style) # Sheet body, remaining rows font_style = xlwt.XFStyle() #issue is there, how can i itterate the bookings to get all value list? rows = Booking.objects.get(booking_reference=bookings).values_list('booking_reference', 'receiver_name', 'receiver_city', 'receiver_phone', 'gross_weight', 'total_carton', 'payment_method', 'comment', 'booking_status') for row in rows: row_num += 1 for col_num in range(len(row)): ws.write(row_num, col_num, row[col_num], font_style) wb.save(response) return response I am having stuck on iteration for my bookings variable to get all value list in rows. How can i do that? Please? -
clicking on Anchor link does not jump down to the section of webpage
I have a blog website built using Django and Wagtail, where the blog article URL is http://example.com/posts/blog01 that blog has a few comments, and in HTML template file, each comment is given an id, <div id="c{{comment.id}}"> this is a comment for the blog article </div> But when I navigate to http://example.com/posts/blog01/#c12, it does not jump down to the comment whose id is 12, instead it just displays the blog article, and I have to scroll down to the specific comment. anything wrong for my setup ? -
SMTPDataError Django
I get this error (450, b'The given data was invalid. The from.email must be verified.') Everything was working fine before i changed the email configuration settings. Here is the settings: EMAIL_BACKEND = 'django.core.mail.backends.smtp.EmailBackend' EMAIL_HOST = 'smtp.mailersend.net' EMAIL_PORT = '587' EMAIL_HOST_USER = 'name@domain.com' EMAIL_HOST_PASSWORD = '***' EMAIL_USE_TLS = True DEFAULT_FROM_EMAIL = EMAIL_HOST_USER Does anyone know why this error occurs and how to fix it? -
Does Javascript template Strings work inside Django templates?
I'm trying to dynamically change image source in javascript inside a Django templates file as follows image.src = `{{ static('images/Principle_Icon/Principle${index+1}.svg')}}`; console.log(`{{ static('images/Principle_Icon/Principle${index+1}.svg')}}`) but this doesn't seem to work since this is what I'm getting /static/images/Principle_Icon/Principle%24%7Bindex%2B1%7D.svg should I expect the javascript template string to work inside django templates? -
Social auth with mutation in Django
I'm trying to make social authentication for graphql, I'm using mutation to achieve but when i'm using qraph graph mutation I'll get below error: here is my mutation: mutation SocialAuth($provider: String!, $accessToken: String!) { socialAuth(provider: $provider, accessToken:"$accessToken") { social { uid extraData } } } and here is the error: { "error": { "errors": [ { "message": "Variable \"$accessToken\" is never used in operation \"SocialAuth\".", "locations": [ { "line": 1, "column": 41 } ], "extensions": { "exception": { "code": "GraphQLError", "stacktrace": [ "graphql.error.base.GraphQLError: Variable \"$accessToken\" is never used in operation \"SocialAuth\"." ] } } } ] } } already I have added everything that should be add in settings.py followed social-auth-app-django documentation. -
French locale is breaking button function
The problem Buttons are not functioning properly if a user is viewing the site in French locale. Background Info I am using {% trans %} tag to translate button text directly in my Django template. Inside of my script tags, I am also using {% trans %} tags to add translation after a button action is triggered (onclick): let show_correction = '{% trans "Show native corrections" %}';. In French locale it becomes: let show_correction='Afficher les corrections d'autres locuteurs natifs';. I think the issue is happening specifically in d'autres. My Guess Maybe the function is terminating earlier because of the apostrophe? How in the world can I fix this? -
Filter objects from a table based on ManyToMany field
I am working on a messaging app. The models are as follows. class ChatRoom(SafeDeleteModel): _safedelete_policy = SOFT_DELETE_CASCADE room_name = models.CharField(max_length=100, null=True, blank=True) participants = models.ManyToManyField(User) class Meta: db_table = TABLE_PREFIX + "chat_room" class Message(SafeDeleteModel): _safedelete_policy = SOFT_DELETE_CASCADE chat_room = models.ForeignKey(ChatRoom, on_delete=models.CASCADE) message = models.TextField() sent_by = models.ForeignKey(User, on_delete=models.CASCADE) created_on = models.DateTimeField(default=django.utils.timezone.now) class Meta: db_table = TABLE_PREFIX + "chat_message" I have to filter ChatRoom object which contains a list of users. Eg: On sending data like this to the api { "participants": [2,3] } It should return a ChatRoom object which contains both user '2' and user '3' as participants. I had tried filtering it with room = ChatRoom.objects.filter(participants__in=serializer.validated_data['participants']) but it returns a list of room objects with user '1' and user '2'. I had also tried using get() but it returns an error. What am I doing wrong and how can i do it right? Thanks for looking into my problem. Hope you have a solution. -
502 Bad Gateway for NGINX USWGI and Django app
I am having issues running this locally. I have two containers in my app. The Django app and the nginx server. Below are the config files and dockerfiles. I am getting a 502 on the localhost:8000 and the error message is 2021/11/16 01:18:29 [error] 23#23: *1 connect() failed (111: Connection refused) while connecting to upstream, client: 172.30.0.1, server: localhost, request: "GET /favicon.ico HTTP/1.1", upstream: "uwsgi://127.0.0.1:8888", host: "localhost:8000", referrer: "http://localhost:8000/" docker-compose.yml version: "3.9" services: web: build: . container_name: test_deploy_web hostname: blindspot command: uwsgi --ini uwsgi.ini volumes: - .:/app/ - staticfiles:/app/static/ nginx: build: ./nginx container_name: test_deploy_nginx volumes: - staticfiles:/app/static/ ports: - 8000:80 depends_on: - web volumes: staticfiles: app dockerfile FROM python:3 ENV PYTHONUNBUFFERED=1 RUN mkdir /app WORKDIR /app RUN pip install --upgrade pip COPY requirements.txt /app/ RUN pip install -r requirements.txt COPY . /app RUN python manage.py collectstatic --noinput nginx dockerfile FROM nginx:latest COPY nginx.conf /etc/nginx/nginx.conf COPY my_nginx.conf /etc/nginx/sites-available/ RUN mkdir -p /etc/nginx/sites-enabled/\ && ln -s /etc/nginx/sites-available/my_nginx.conf /etc/nginx/sites-enabled/\ && rm /etc/nginx/conf.d/default.conf CMD ["nginx", "-g", "daemon off;"] my_nginx.conf # the upstream component nginx needs to connect to upstream blindspot { server 127.0.0.1:8888; #server unix:/app/app.sock; # for a file socket } # configuration of the server server { # the port your site will … -
django docker micro postgres server error :django could not translate host name "db" to address: Name or service not known
I know there is a similar question here. How do you perform Django database migrations when using Docker-Compose? But all no answer from that question solved my issue: I built a django project ,it works good at local env ,and also good if I let docker to connect my local db by setting host to: host.docker.internal But when I tired to convert the whole project to docker micro postgres server,after run: docker-compose build error: django.db.utils.OperationalError: could not translate host name "db" to address: Name or service not known Here is my setting.py: DATABASES = { 'default': { 'ENGINE': 'django.db.backends.postgresql_psycopg2', 'NAME': 'postgres', 'USER': 'postgres', 'HOST': 'db', 'PORT': '5432', } } dockerfile: FROM python:3 ENV PYTHONUNBUFFERED 1 WORKDIR /app ADD . /app COPY ./requirements.txt /app/requirements.txt RUN pip install -r requirements.txt RUN python manage.py makemigrations RUN python manage.py migrate RUN python manage.py load_patient_data COPY . /app docker-compose.yml version: '3' services: web: build: . command: python manage.py runserver 0.0.0.0:8000 ports: - 8000:8000 depends_on: - db db: image : postgres environment: POSTGRES_HOST_AUTH_METHOD: trust -
Django: Filter on related model's field not being equal to a specific value
Given these models: from django.db import models class Foo(models.Model): pass # table with only one column, i.e. a primary key 'id' of type integer class Bar(models.Model): value = models.TextField() foo = models.ForeignKey(Foo, on_delete=models.CASCADE, related_name='bars') How to create a filter which returns all Foos related to at least one Bar with a non-zero value? I am aware that it is possible to at first select the non-zero Bars and then return the Foos related to them. But I am specifically looking for a solution which obtains the relevant Foos in a QuerySet directly. The reason is that it it could then easily be applied to relationships which are nested to a deeper level. What does not work It is straightforward to create a QuerySet which returns all Foos related to at least one Bar with a zero value: Foo.objects.filter(bars__value="zero") However, due to the lack of the "not equal" operator in Django's filter methods, it is impossible to do something like this: Foo.objects.filter(bars__value__not_equal="zero") # Unsupported lookup 'not_equal' for TextField Using exclude: Foo.objects.exclude(bars__value="zero") does not produce the desired output because it excludes all Foos which relate to at least one Bar with a zero value. So, if a Foo is related to two … -
How can I request an already logged in user to confirm password to enter a specific page in django?
I'm working on a django application. The application has a dashboard. How can i make it so that everytime the user wants to access the dashboard, he/she has to confirm their identity, with the same password they use to log into the same application? Thank you -
Extract keys from a Django JsonField when it is an Array using KeyTransform
When I have data like this, which represent the periodicity JsonField from the model Series: {'id': 20597, 'periodicity': [{'period': 'weekly', 'end_date': '2021-09-30', 'start_date': '2020-12-11'}]} {'id': 20596, 'periodicity': [{'period': 'weekly', 'end_date': '2021-03-05', 'start_date': '2021-03-05'}]} {'id': 20595, 'periodicity': [{'period': 'weekly', 'end_date': '2021-09-24', 'start_date': '2020-12-11'}]} {'id': 20593, 'periodicity': [{'period': 'weekly', 'end_date': '2021-09-24', 'start_date': '2020-01-27'}]} {'id': 18090, 'periodicity': [{'period': 'daily', 'end_date': '2021-06-04', 'start_date': '2012-01-03'}, {'period': 'weekly', 'end_date': '2021-08-30', 'start_date': '2020-12-14'}]} {'id': 18089, 'periodicity': [{'period': 'daily', 'end_date': '2021-06-04', 'start_date': '2012-01-03'}, {'period': 'weekly', 'end_date': '2021-08-30', 'start_date': '2020-12-14'}]} The problem as you can see, the JsonField is an Array of dict. I would like to extract all the end_date keys, even just as text. It seems like KeyTransform or KeyTextTransfom is not working when I do: Series.objects.annotate(end_date=KeyTransform("end_date", "periodicity")).values("id", "end_date", "periodicity") How can I get that? I want to get the oldest end_date from the array by the way. Impossible to find the solution using PostgreSQL or Django. -
django docker micro postgres server error:django could not translate host name "db" to address: Name or service not known
I built a django project ,it works good at local env ,and also good if I let docker to connect my local db by setting host to: host.docker.internal But when I tired to convert the whole project to docker micro postgres server,after run: docker-compose build error: django.db.utils.OperationalError: could not translate host name "db" to address: Name or service not known Here is my setting.py: DATABASES = { 'default': { 'ENGINE': 'django.db.backends.postgresql_psycopg2', 'NAME': 'postgres', 'USER': 'postgres', 'HOST': 'db', 'PORT': '5432', } } dockerfile: FROM python:3 ENV PYTHONUNBUFFERED 1 WORKDIR /app ADD . /app COPY ./requirements.txt /app/requirements.txt RUN pip install -r requirements.txt RUN python manage.py makemigrations RUN python manage.py migrate RUN python manage.py load_patient_data COPY . /app docker-compose.yml version: '3' services: web: build: . command: python manage.py runserver 0.0.0.0:8000 ports: - 8000:8000 depends_on: - db db: image : postgres environment: POSTGRES_HOST_AUTH_METHOD: trust -
Iterating over large querysets in Django
How do you efficiently iterate over a large queryset (records in the millions) with Django? I'm trying to delete several million records that I can't do with a simple bulk SQL DELETE statement because the transaction would consume too much server memory. So I'm attempting to write a Python script to group ~10000 individual DELETE statements in a transaction. My script looks like: from django.db import transaction from django.conf import settings settings.DEBUG = False qs = MyModel.objects.filter(some_criteria=123) total = qs.count() i = 0 transaction.set_autocommit(False) for record in qs.iterator(): i += 1 if i == 1 or not i % 100 or i == total: print('%i of %i %.02f%%: %s' % (i + 1, total, (i + 1) / float(total) * 100, record)) record.delete() if not i % 1000: transaction.commit() transaction.commit() This runs fine for the first 2000 records, but then errors with: Traceback (most recent call last): File "/project/.env/lib/python3.7/site-packages/django/db/models/sql/compiler.py", line 1512, in cursor_iter for rows in iter((lambda: cursor.fetchmany(itersize)), sentinel): File "/project/.env/lib/python3.7/site-packages/django/db/models/sql/compiler.py", line 1512, in <lambda> for rows in iter((lambda: cursor.fetchmany(itersize)), sentinel): File "/project/.env/lib/python3.7/site-packages/django/db/utils.py", line 96, in inner return func(*args, **kwargs) File "/project/.env/lib/python3.7/site-packages/django/db/utils.py", line 89, in __exit__ raise dj_exc_value.with_traceback(traceback) from exc_value File "/project/.env/lib/python3.7/site-packages/django/db/utils.py", line 96, in inner return func(*args, **kwargs) django.db.utils.ProgrammingError: … -
C:\Users\krish\Desktop\code\hello> docker-compose up can't find a suitable configuration file in this directory or any parent: not found
when i run this command [docker-compose up] C:\Users\krish\Desktop\code\hello>docker-compose up can't find a suitable configuration file in this directory or any parent: not found i got this error {can anyone help me form this issue} -
Is there a way to display a user's sessions in django and expose them to an API?
I am building an authentication api and I am looking for a way to Query a database to the current user's logged in sessions Serialize them Exposes the to an API endpoint Here's the far I have gotten: My models.py from django.db import models from django.contrib.auth.signals import user_logged_in from django.contrib.sessions.models import Session from django.contrib.auth.models import User import datetime from django.utils import timezone class UserSession(models.Model): user = models.ForeignKey(User,on_delete=models.CASCADE) session = models.ForeignKey(Session,on_delete=models.CASCADE) def all_unexpired_sessions_for_user(user): user_sessions = [] all_sessions = Session.objects.filter(expire_date__gte=datetime.datetime.now(tz=timezone.utc)) for session in all_sessions: print(session) try: session_data = session.get_decoded() except: pass print(session_data) #print(session_data['_auth_user_id']) print(type(user)) print(session_data.get('_auth_user_id')) if user.pk == session_data.get('_auth_user_id',''): try: user_sessions.append(session.pk) except: pass return Session.objects.filter(pk__in=user_sessions) I am able to display the session keys and the session data(please don't mind my million print statements) My Serializers.py from rest_framework import fields, serializers from .models import UserSession class UserSessionSerializer(serializers.ModelSerializer): class Meta: model = UserSession fields = ('user',) My views.py from django.shortcuts import render from rest_framework.views import APIView from rest_framework.response import Response from .models import UserSession from django.contrib.sessions.models import Session from .serializers import UserSessionSerializer class AuthView(APIView): pass class SessionList(APIView): def get(self, request,format=None): user = request.user print(type(user)) all_sessions = UserSession.all_unexpired_sessions_for_user(user=user) print(all_sessions) serializers = UserSessionSerializer(all_sessions,many=True) return Response(serializers.data) def home_page(request): user = request.user #user_sessions = UserSession.objects.get_or_create(user=request.user,session_id =request.session.session_key) usr_ssn = … -
How to send ajax request from bootstrap 5 modal form?
I use Django and Bootsrap v5. I want to make authorization through modal forms. Instead of sending the form, a redirect on the endoint is happening. Can someone suggest an example? Without use of jQuery. -
How to retrieve data using id or pk in django
I am working on a project but after trying multiple way I still couldn't find the solution, I need to get the current room on the page so that user can leave room, I am aware it has to do with making queries or using pk,id. (My 1st question ever, sorry if not correct way to ask). **Views.py: def leave_room(request, room): room = request.GET['room.pk'] room_details = Room.objects.get(name=room) messages = Messages.objects.filter(room=room_details.pk) membership = RoomMember.objects.filter(user=request.user, room=messages) membership.delete() return redirect("/" urls.py: path("leave/<int:pk>/join/", views.leave_room, name="leave_room"), html: <a class="btn btn-danger" href="{% url 'leave_room' pk=room.pk %}">Leave Room</a>** -
How to use foreign key field's attribute for another model field
I have two models in different apps like so: class Account(models.Model): """ Class to store fiat account information of a companies bank account """ number = models.CharField(max_length=100) currency = models.ForeignKey(FiatCurrency, on_delete=models.CASCADE) owner = models.ForeignKey(Company, on_delete=models.CASCADE) date_added = models.DateTimeField(auto_now_add=True) def __str__(self): return self.number class FiatTransaction(models.Model): """ Class to store Transactions made between escrow and operative white-listed fiat accounts """ debit_account = models.ForeignKey('company.Account', on_delete=models.CASCADE, related_name='debit_account') credit_account = models.ForeignKey('company.Account', on_delete=models.CASCADE, related_name='credit_account') executed_on = models.DateTimeField(auto_now_add=True) amount = models.FloatField() currency = debit_account.currency is_processed = models.BooleanField(default=False) fee = models.FloatField() memo = models.CharField(max_length=250) def __str__(self): return F"Transferred {self.amount} from {self.debit_account} to {self.credit_account} at {self.executed_on}" Now the field currency of model FiatTransaction doesn't seem to work the way I intend it to do. It raises AttributeError: 'ForeignKey' object has no attribute 'currency' # Source model class FiatCurrency(models.Model): """ A model to store Fiat Currencies offered by Finchin to include into cash-pools. """ ISO_Code = models.CharField(max_length=3) name = models.CharField(max_length=50) is_active = models.BooleanField(default=True) def __str__(self): return self.name Why's that and how to make this work? -
How do I update an SSL certificate in Python?
I am running python 3.9.1 I have some Django Admin Actions which create and then download some PDFs. When running this on my local machine (Windows 10) I have recently started getting the following error message: SSL: CERTIFICATE_VERIFY_FAILED] certificate verify failed: certificate has expired (_ssl.c:1123) Any ideas on how I can deal with this? The Django app works perfectly on the server, the problem is only on my local host. -
Merging multiple views with multi user into single html file in django
Alright, • I have project with multiuser login (developer and Project Manager) • Project manager opens ticket developer can accept ticket and complete ticket • Project manager can close ticket after developer marks completed I have implemented function based views and there is lot of repeating code in my implementation i have 8 html pages for developer & manager dashboard for open,accept,complete and closed tickets i need the function based views to be written in generic views listview and display the content according to the user logged in models.py ` class User(AbstractUser): is_developer = models.BooleanField(default=False) is_manager = models.BooleanField(default=False) first_name = models.CharField(max_length=100) last_name = models.CharField(max_length=100) email = models.EmailField(unique=True) class Ticket(models.Model): ticket_title = models.CharField(unique=True,max_length=200) ticket_description = models.TextField() created_by = models.ForeignKey(User,related_name = 'created_by',blank=True,null=True,on_delete=models.CASCADE) STATUS_CHOICES = ( ('Opened','Opened'), ('Accepted','Accepted'), ('Completed','Completed'), ('Closed','Closed') ) status = models.CharField('Status',choices=STATUS_CHOICES,max_length = 100,blank=True,null=True) closed_date = models.DateTimeField(blank=True,null=True) completed_date = models.DateTimeField(blank=True,null=True) accepted_date = models.DateTimeField(blank=True,null=True) opened_date = models.DateTimeField(blank=True,null=True) accepted_by = models.ForeignKey(User,related_name='assigned_to',on_delete=models.CASCADE,blank=True,null=True) created = models.DateTimeField(auto_now_add=True) updated = models.DateTimeField(auto_now=True) ` views.py def manager_login(request): current = User.objects.filter(is_manager = True) if request.method == 'POST': pm_form = AuthenticationForm(data=request.POST) if pm_form.is_valid(): username = pm_form.cleaned_data.get('username') password = pm_form.cleaned_data.get('password') user = authenticate(username=username,password=password) if user is not None: if user in current: login(request,user) return redirect(reverse('pm_dashboard')) else: messages.error(request,"Invalid Username or Password") else: messages.error(request,"Invalid … -
2 Django projects on one IIS server under the same domain name
My goal is to create a dev environment for a Django project that I inherited. It is hosted on an IIS server and there is currently only a production environment server-side, which is being used by the clients at my university. I want to have a copy of the entire site that I can use for testing purposes. This copy would also use a separate database, which is a copy of the current database with some added tables. My initial thought was to have another branch of the git repo in the wwwroot folder, something like this: wwwroot/prod/django_project_files_here wwwroot/dev/django_project_files_here Both of these would hopefully use the same domain name, but use different urls and views in their respective urls.py and views.py files. For example, app.uniname.edu/home would tap the production version, whereas app.uniname.edu/dev-home would tap the dev version. All of the urls in the prod version would have a similar dev version with "dev" added to the url. I thought I had this all set up, but all of the urls in the second/dev version were 404s. This leads me to believe that the server is not actually using the second copy of the Django application. Granted, I'm not sure that … -
how to run simultaneous docker commands using asynchronous Django RESTAPI call
I am building a B2C Django application where I need to build multiple docker containers for each customer. I can call a single "docker run -d" commands using os_command from my rest API in Django. I am hosting it in Ubuntu 18.04. I can make multiple API calls from Django but in my Ubuntu host, it will delay the Docker commands unless the previous command is executed fully. I want to run multiple "docker run -d" commands to build containers for my customers. Is it possible to do it using an Asynchronous API call or does the Ubuntu system have a limitation to execute multiple commands simultenously? -
emerg "http" directive is not allowed here & server_names_hash
I am currently setting up my nginx .conf file with the following code server { listen 80; server_name ec2-13-59-58-36.us-east-2.compute.amazonaws.com; location / { include proxy_params; proxy_pass http://unix:/home/ubuntu/Shiftly/app.sock; } } However when I run sudo nginx -t I get an error like so :Dec 16 11:38:08 netzmelone nginx[14242]: nginx: [emerg] could not build the server_names_hash, you should increase server_names_hash_bucket_size: 32 I then add this code at the bottom of my .conf file or in my server file http { server_names_hash_bucket_size 64; } However this returns an error of nginx: [emerg] "http" directive is not allowed here in /etc/nginx/sites-enabled/django.conf:11