Django community: Django Q&A RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Django Channels AsyncHTTPConsumer example
Title says it all. For the love of god, is there an example where there are routes both for 'http' and 'websocket' protocols? I'm simply trying to have (along with classic django channels websockets) an async download, and setup my asgi configuration for it, but I can't find any examples on the internet, let alone the documentation, how to have them both. It shouldn't be much of an ask, but it seems that it is. -
Forbidden (403) CSRF verification failed. Request aborted. with Gunicorn
I've created a form that includes the {% csrf_token %} but every time I submit the form it refuses it due to my domain not coming from a trusted origin. I set CSRF_TRUSTED_ORIGIN = "https://proj.com" and I even tried using @csrf_exempt to see if that would get rid of the problem but it still didn't work, the form still isn't submitting. I am using gunicorn with my django project and PostgreSQL for my database. -
django: update html dynamically when model is updated
There is a Status model with instances saved in the database. There is a view generating the html code that displays these instances to the client. Another process updates the values of the fields of these instances ('updates': read the instance from the database, change the values of some of the fields, and save the instances back to the database). I would like the html report currently displayed to the client to be updated 'live' everytime the database has been updated. I searched, but I am failing to determine the canonical way of doing this. It feels like I should use things like channels, data binding, WebsocketBinding. But the documentation (https://channels.readthedocs.io/en/1.x/binding.html) is quite difficult to follow for a beginner and I could not find any example that would help me start. It would be great, and possibly useful to many, to have a minimal example of this (not necessarily using WebsocketBinding if there are better ways of doing this) -
How can I change form field population *after* successful POST request for Class-Based-Views
I want to change the forms initial field population. Here is the catch: I want to change it for the POST request and not for the GET request. Let's say my app offers a calculation based on a body weight input. If the user inputs a body weight calculation happens with that weight, if not a default of 50 is used. So it is allowed to let the field empty. But after the calculation ran, I want to display that the value used for calculation was 50. That's why I want to populate the field with 50 after the form was initially submitted with an empty value. # forms.py class CalculatorForm(forms.Form): body_weight = forms.FloatField(required=False) def clean(self): cleaned_data = super().clean() if cleaned_data['body_weight'] is None: cleaned_data['body_weight'] = 50.0 # ideally I want to put the logic here # self.data[bpka] = 50.0 --> AttributeError: This QueryDict instance is immutable # self.fields['body_weight'] = 50.0 --> does not work # self.initial.update({'body_weight': 50.0}) --> does not work return cleaned_data I feel like the problem is that I can not reach the bound fields from the clean() method. If it is not possible within the form the logic has to go to the view I guess. Feel … -
no such table: api_user
I used from django.contrib.auth.models import User before, but now I need to switch to AbstractUser. How can I transfer the data from the previous auth_user table to AbstractUser? I followed the code from here. models.py from django.db import models from django.contrib.auth.models import AbstractUser class User(AbstractUser): username = models.CharField(max_length=50, unique=True) email = models.CharField(max_length=100) password = models.CharField(max_length=100) USERNAME_FIELD = 'email' REQUIRED_FIELDS = [] serializers.py from .models import User from rest_framework import serializers class UserSerializer(serializers.ModelSerializer): class Meta: model = User fields = ['username', 'email', 'password'] extra_kwargs = { 'password': {'write_only': True} # Don't return password } def create(self, validated_data): # Hash password password = validated_data.pop('password', None) instance = self.Meta.model(**validated_data) if password is not None: instance.set_password(password) instance.save() return instance When I login to admin pages I get : no such talbe: api_user I want to use AbstractUser instead without deleting the auth_user table. -
snapchat like feature in django rest framework
In snapchat user takes a snap and can upload the taken snap to list of friends in frontend and it should be done in backend using Django rest framework instead of friends i need groups. groups should be in list in DRF user wants to upload post to different groups at same time and similar to snapchat how user can upload snaps to his friends models.py from django.db import models from django.contrib.auth.models import User class Groups(models.Model): name = models.CharField(max_length=50) created_by = models.ForeignKey(User, on_delete=models.CASCADE, null=True, related_name='created_clusters') created_at = models.DateTimeField(auto_now=True) members = models.ManyToManyField("Members", related_name='members') post = models.ManyToManyField("Post", related_name='moments', db_column='moments') class Members(models.Model): member = models.ForeignKey(User, on_delete=models.CASCADE) groups = models.ForeignKey("Groups", on_delete=models.CASCADE, null=True, related_name='cluster_members') joined_at = models.DateTimeField(auto_now=True) class Post(models.Model): user = models.ForeignKey(User, on_delete=models.CASCADE, null=True) post = models.FileField(upload_to='post', null=True, default='') caption = models.CharField(max_length=200, null=True) created_at = models.DateTimeField(auto_now=True) groups = models.ManyToManyField("Groups", related_name="clusters") serilizers.py there is group serializer and post serializer from rest_framework import serializers from .models import Groups, Post class GroupsSerializer(serializers.ModelSerializer): class Meta: model = Groups fields = '__all__' class PostSerializer(serializers.ModelSerializer): user = serializers.HiddenField(default=serializers.CurrentUserDefault()) class Meta: model = Post fields = '__all__' views.py from rest_framework.decorators import api_view from rest_framework.response import Response from rest_framework import status from django.shortcuts import get_object_or_404 from .models import Users, Groups, Post from .serializers … -
Django unexpected keyword argument "encoder"
I am using django to create a back-end for my web app and I am getting an Exception Type: TypeError at /register/ Exception Value: Field.init() got an unexpected keyword argument 'encoder'. Meanwhile there's no field like that in my views.py or serializers.py. views.py from django.contrib.auth.decorators import login_required from django.contrib.auth.mixins import LoginRequiredMixin from django.core.mail import send_mail from django.http import JsonResponse from rest_framework.generics import UpdateAPIView from rest_framework.permissions import IsAuthenticated from .serializers import UserProfileSerializer, ProfileViewSerializer, FavoriteSerializer, MessageSerializer from django.db.models import Q from django.contrib.auth.models import User from django.contrib.auth import authenticate, get_user_model, login from django.utils.encoding import force_bytes from django.utils.http import urlsafe_base64_encode, urlsafe_base64_decode from django.utils.translation import gettext_lazy as _ from rest_framework import generics, permissions, serializers, status from rest_framework.response import Response from django.conf import settings from django.http import JsonResponse from rest_framework.views import APIView from .models import Favorite, ProfileView, UserProfile, Message from random import randint from django.contrib.auth.decorators import login_required from .serializers import ( LoginSerializer, UserProfileSerializer, ProfileViewSerializer, FavoriteSerializer, ) email_domain = ( ("ucc.edu.gh", "University of Cape Coast"), ("knust.edu.gh", "Kwame Nkrumah University of Science and Technology"), ("ug.edu.gh", "University of Ghana"), ("uew.edu.gh", "University of Education, Winneba"), ("umat.edu.gh", "University of Mines and Technology"), ("uds.edu.gh", "University of Development Studies"), ("upsa.edu.gh", "University of Professional Studies, Accra"), ("uenr.edu.gh", "University of Energy and Natural Resources"), ("uhas.edu.gh", … -
No hostname was supplied. Reverting to default 'localhost' - Celery Redis Django Ubuntu 22.04
I built an application with django. There are some background tasks that run using celery and redis. On windows, everything works fine. However when I deploy on Ubuntu 22.04, I get the following error in the log. settings.py # CELERY SETTINGS CELERY_BROKER_URL = 'redis://127.0.0.1:6379/0' CELERY_ACCEPT_CONTENT = ['application/json'] CELERY_TASK_SERIALIZER = 'json' CELERY_RESULT_SERIALIZER = 'json' CELERY_TIMEZONE = TIME_ZONE or 'UTC' CELERY_RESULT_BACKEND = 'django-db' # CELERY BEAT SETTINGS CELERY_BEAT_SCHEDULER = 'django_celery_beat.schedulers:DatabaseScheduler' celery.py from __future__ import absolute_import, unicode_literals import os from celery import Celery from django.conf import settings from celery.schedules import crontab os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'dear.settings') app = Celery('dear') app.conf.broker_url = 'redis://localhost:6379/0' app.conf.result_backend = 'redis://localhost:6379/0' app.conf.enable_utc = False app.conf.update(timezone = 'Asia/Dubai') app.config_from_object(settings, namespace='CELERY') celery.conf [program:dearapi] command=/home/djangoadmin/pyapps/venv/bin/celery -A celery worker --loglevel=INFO directory=/home/djangoadmin/pyapps/dearapi/dear user=djangoadmin numprocs=1 stdout_logfile=/var/log/supervisor/celery.log stderr_logfile=/var/log/supervisor/celery.log autostart=true autorestart=true startsecs=0 ; Need to wait for currently executing tasks to finish at shutdown. ; Increase this if you have very long running tasks. stopwaitsecs = 600 ; When resorting to send SIGKILL to the program to terminate it ; send SIGKILL to its whole process group instead, ; taking care of its children as well. killasgroup=true ; if rabbitmq is supervised, set its priority higher ; so it starts first priority=998 celerybeat.conf ; ======================== ; celery beat supervisor ; … -
how to route between different pages in a website using django
I want to build a website to practice wherein i want to make a home page in which there will be two categories in a horizontal direction, lets name them "windows" and "linux" , i simply want to show text about windows when a user clicks on windows button and text about linux when a user clicks on linux button. As per my knowledge i need to create two apps called windows and linux with their respective template file and a master template file in rot folder that will work like hompage , however i am unable to put all together as im new to django. I have attached a demo picture of how i want my website to look like. I only have two html files for windows and linux app, i am unable to merge it with master template file. -
How can I use Django to transform checkboxes into radio buttons while retaining the logic of checkboxes and use them in my form?
I'd like to know how to customise a function on Django that would allow me to transform checkboxes into radio buttons, while retaining the logic of checkboxes. Let me explain: I've created a form on Django, but my form has several fields containing checkboxes with distinct behaviours depending on the field. But for the most part, the functionalities that can be observed on these checkboxes are : The ability to check and uncheck a box (normal functionality) Two checkboxes in a group of checkboxes cannot be checked simultaneously (uniqueness of checkboxes) If a checkbox encapsulates a field, then checking the box reveals the hidden field and unchecking the box or checking another box automatically hides the field encapsulated by the previous checkbox. But I haven't found any resources in the Django documentation that could help me with this task, especially as when I tried to implement the client-side logic with JavaScript/jQuery, when I submitted my form on a web page, it generated validation errors in my checkboxes, implying that the logic implemented on the client side didn't find a match on the server side, so I'm a bit at a loss, I've been working on this code for a while … -
Loading images stored on linode object storage in react
I am creating an ui for a django project and I have all my static files uploaded to a linode object storage and in django I can load images and view them with no problem but in react I fetch the url using an api from django but when I try to render it I get a 403 access forbidden. How do I set the access keys in react to grab the images? -
django rest api serialization
any hep is appreciated. What I am trying to do is build some kind of rooms booking system. this is what I did till now: from django.db import models from ckeditor.fields import RichTextField from autoslug import AutoSlugField class Room(models.Model): room_name = models.CharField(max_length=255) slug = AutoSlugField(populate_from='room_name', unique=True) room_location = models.CharField(max_length=255) room_capacity = models.CharField(max_length=50) reservation_period = models.IntegerField(default=1) item_price = models.DecimalField(max_digits=10, decimal_places=2, default=0.00) room_description = RichTextField() room_image = models.ImageField(upload_to='rooms__images') def __str__(self): return self.room_name class MenuItem(models.Model): item_name = models.CharField(max_length=255) item_price = models.DecimalField(max_digits=10, decimal_places=2) def __str__(self): return 'naam: ' + self.item_name class Reservation(models.Model): room = models.ForeignKey(Room, on_delete=models.CASCADE) reservation_day = models.DateField() reservation_start_time = models.TimeField() reservation_end_time = models.TimeField() first_name = models.CharField(max_length=255) last_name = models.CharField(max_length=255) email = models.CharField(max_length=255) phone = models.CharField(max_length=255) company_name = models.CharField(max_length=255, blank=True, null=True) kvk_number = models.CharField(max_length=255, blank=True, null=True) notes = models.TextField(blank=True, null=True) def __str__(self): return self.first_name class MenuItemReservation(models.Model): menu_item = models.ForeignKey(MenuItem, on_delete=models.CASCADE) quantity = models.IntegerField() reservation = models.ForeignKey(Reservation, on_delete=models.CASCADE, related_name='menu_item_reservations') from rest_framework import serializers from .models import Room, MenuItem, Reservation, MenuItemReservation class RoomSerializer(serializers.ModelSerializer): class Meta: model = Room fields = '__all__' class MenuItemSerializer(serializers.ModelSerializer): class Meta: model = MenuItem fields = '__all__' class MenuItemReservationSerializer(serializers.ModelSerializer): menu_item = serializers.PrimaryKeyRelatedField(queryset=MenuItem.objects.all(), source='menu_item.id') class Meta: model = MenuItemReservation fields = '__all__' class ReservationSerializer(serializers.ModelSerializer): room = serializers.PrimaryKeyRelatedField(queryset=Room.objects.all(), source='room.id') menu_item_reservations = MenuItemReservationSerializer(many=True, required=False) … -
DRF and React authentication with djoser
I how some problem with in login in django-djoser! I used django djoser in api login path('api/v1/', include('djoser.urls.authtoken')) I changed urls in authcontext and in login js dont worked authcontext.jsx and login.jsx Can you help me with this problem, signup working but login didn't open the site! Thanks before! -
Can't show image from database in django
index.html <img src="{{beat.image.url}}" class="card-img-top" alt="{{beat.name}}"> settings.py `STATIC_URL = '/static/' MEDIA_URL = '/media/' MEDIA_ROOT = os.path.join(BASE_DIR, 'beat/media')` models.py image = models.ImageField(upload_to='images', blank=True) urls.py urlpatterns = [ path('', views.index, name='index'), path('test', views.test, name='test'), ] + static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT) beat.image.url not working -
How can I improve the speed and performance of database queries?
I'm currently working on a Django project where I'm encountering performance issues, especially as my application scales. To provide better context, I've included a realistic code snippet below that represents a performance-intensive section of my application: from django.db import models class Order(models.Model): # Fields and relationships... class OrderItem(models.Model): order = models.ForeignKey(Order, on_delete=models.CASCADE) product = models.ForeignKey('Product', on_delete=models.CASCADE) quantity = models.PositiveIntegerField() class Product(models.Model): # Fields and relationships... def calculate_total_price(order_id): order_items = OrderItem.objects.filter(order_id=order_id).select_related('product') total_price = 0 for item in order_items: product_price = item.product.price quantity = item.quantity total_price += product_price * quantity return total_price In the above code snippet, I have an Order model that is associated with multiple OrderItems, and each OrderItem references a Product. The calculate_total_price function is used to calculate the total price for a given order by iterating over its associated OrderItems. However, as the number of OrderItems increases, the calculation becomes significantly slower. I would greatly appreciate any insights and suggestions on how to optimize this code snippet or any other general Django performance tips. Are there any specific techniques, database query optimizations, caching mechanisms, or Django features I should consider to enhance the performance of this code? Additionally, if there are any profiling tools or libraries you recommend … -
How do I resolve the "no-name-in-module" error in Pylint when using Parler's TranslatedFields?
I have the following class in models.py: class Family(models.Model): code = models.CharField(max_length=50, unique=True) translations = TranslatedFields(name=models.CharField(max_length=255)) When I try to import the "FamilyTranslation" model for various purposes from .models import FamilyTranslation Pylint detects the "E0611:no-name-in-module" error. The table with the translations is created, the code works, but Pylint doesn't recognize the model. I have tried some pylint plugins to make Parler's automatic models recognized, but it doesn't work. I have already checked the __init__.py file, and it is correct. If possible, I would prefer not to explicitly declare all the "Translation" models from Parler. -
How to fix a bug after stripe paymant
I have a website with games. I also included stripe as a payment method, and everything works pretty fine! But, after you finish your payment, you get redirected to your home page, and objects that are looped just DISSAPPEAR! They appear again once you travel from one page to another. Views.py def button_to_buy(request): stripe.api_key = settings.STRIPE_SECRET_KEY checkout_session = stripe.checkout.Session.create( payment_method_types=[ 'card', ], line_items=[ { 'price': '', 'quantity': 1, }, ], mode='payment', success_url=request.build_absolute_uri(reverse('success')) ) return redirect(checkout_session.url, code=303) def success_url(request): user = request.user.pk profile = Profile.objects.get(user_id=user) profile.subscription = True profile.save() messages.success(request, 'Оплата прошла успешно') return render(request, 'store/index.html') Urls.py path('checkout/', button_to_buy, name='checkout'), path('success/', success_url, name='success'), Profile.html <div class="justify-content-center py-4 px-2"> {% if not profile.subscription %} <form action="{% url 'checkout' %}" method="POST"> {% csrf_token %} <button class="btn text-light bg-danger mt-4">Buy subscription</button> </form> {% else %} <button class="btn text-light bg-success mt-4">Already paid</button> {% endif %} -
How to speed up celery task which add info into DB
I'm using Django with Celery and PostgreSQL I wrote a celery task which takes json from 3rd party api with more than 10k lines and write them into my database but it takes kinda slow like 30 seconds or more and i'm wondering is there a way to speed up this task? @app.task def create_presence_info(): url = 'http://3rd_party_api.com/api' enter code here response = requests.get(url).json() if len(response) <= 0: print('JSON IS EMPTY') elif len(response) > 0: for item in response: obj_json = json.dumps(item) info_parsed = PresenceInfoListSerializer.parse_raw(obj_json) for counter_list in info_parsed.ListOfCounterparty: presence_list_model = check_presence_list(counter_list) object_list_model = check_object(info_parsed.ObjectGUID) set_of_presence_model = set_of_presence_guid(PresenceListInfo, counter_list) if presence_list_model is None or presence_list_model.GUID not in set_of_presence_model: presence_info = PresenceListInfo.objects.create(GUID=counter_list.DocumentGUID, object_presence=object_list_model) set_of_presence_model.add(presence_info.GUID) deleted = False for info in counter_list.Information: counter_party_model = check_counter_party(info.CounterpartyGUID) if not deleted: PresenceDetailInfo.objects.filter(presence_info=presence_list_model).delete() deleted = True details = PresenceDetailInfo.objects.create(presence_info=presence_list_model, counter_presence=counter_party_model, work_date=counter_list.Date, amount_of_workers=info.Number) for section in info.SectionsGUID: sections = None try: sections = CleanSections.objects.get(GUID=section) except CleanSections.DoesNotExist as sections_error: logger.error(f'{sections_error} update_or_create_presence_info') PresenceSectionList.objects.create(presence_detail=details, presence_sections=sections) ``` -
sqlAlchemy jsonb in Django form
I have a PostgreSQL database and use sqlAlchemy to access the data. In one of the tables, I have a JSONb column. When I load a sqlAlchemy object (an entry from the DB) containing a not empty JSON entry sqlAlchemy will directly transfer it to a Python dict. On default, for Python dicts single quotes are used; therefore, even though JSON uses double quotes, the dict is with single quotes. I then show the JSON in a Django form field so that a user might update the JSON and/or other parameters. When I get the form back with the content of the JSON field as an str, I want to validate that the user sends a valid JSON, so I execute json.loads(json_form_field_content) to verify it. This will raise an error if single quotes are in the JSON string. This is especially bad as this will even happen if the user has not changed the JSON. I googled hard and didn't find a fitting solution for my problem, so I thought hard and came up with an in my option poor solution. I use the following code to transfer the dict to a string where I explicitly set double quotes for … -
AttributeError at /order: module 'groceries_app.views' has no attribute 'usrnme'
I've created two apps in my django project called groceries_app and products_app. When I try to submit a shopping list in my browser, I get this attribute error: module 'groceries_app.views' has no attribute 'usrnme', even though I defined 'usrnme' in my views.py file in groceries_app. How do I fix this so that my order will be confirmed? groceries_app/views.py from django.contrib import messages from django.contrib.auth.mixins import UserPassesTestMixin from django.core.exceptions import ObjectDoesNotExist from django.http import HttpResponse from django.shortcuts import render, redirect from django.views.generic import ListView, DetailView, CreateView, UpdateView, DeleteView from .forms import RegisterForm from .models import RegisteredUser def app_homepage(request): try: if usrnme: userdetails = {'username': usrnme} return render(request, "loggedin.html", userdetails) except NameError: return render(request, 'homepage.html') def about_us(request): try: if usrnme: return render(request, "aboutUs.html") except NameError: return render(request, 'aboutUs.html') def services(request): try: if usrnme: return render(request, "services.html") except NameError: return render(request, 'services.html') def contact_us(request): try: if usrnme: return render(request, "contactUs.html") except NameError: return render(request, 'contactUs.html') def register(request): if request.method == "POST": form = RegisterForm(request.POST) if form.is_valid(): form.save() messages.success(request, "Account created successfully") return redirect("signin") else: form = RegisterForm() user_info = {'form': form} return render(request, "register.html", user_info) def signin(request): global usrnme if request.method == 'POST': usrnme = request.POST['username'] psswrd = request.POST['pswd'] try: user = RegisteredUser.objects.get(name=usrnme) … -
UnicodeEncodeError at / 'ascii' codec can't encode character '\x92' in position 65: ordinal not in range(128)
This error occurs when django tries to use the send_email function: UnicodeEncodeError at / 'ascii' codec can't encode character '\x92' in position 65: ordinal not in range(128) Request Method: GET Request URL: http://127.0.0.1:8002/ Django Version: 4.2.2 Exception Type: UnicodeEncodeError Exception Value: 'ascii' codec can't encode character '\x92' in position 65: ordinal not in range(128) Exception Location: /usr/lib/python3.11/smtplib.py, line 641, in auth in views.py: from django.core.mail import send_mail EmailMessage def contactView(request): email = EmailMessage( 'encoded_subject', 'Body', 'obidjonova07@mail.ru', ['inspiring.sunset07@gmail.com'], ) email.send() return render(request, "parts/base.html", {'birth_date': age}) I tried using encode function: encoded_subject = subject.encode('utf-8') and passed it to the function, tried to use the function for the message as well, but it did not help -
How to filter multiple tags with django-taggit in admin view?
I'm reading through the documentation for any example, alas without success. Can anybody point me to an example about filtering for e.g. "green" and "blue" in django admin view? -
Use IntegrityError exception (in Django) to check if username is taken?
I wanted to create a signup form in Django and throw an error if the username already exists. I have seen people have used User.DoesNotExist() method to check that, but can you use IntegrityError exception as follows for that purpose? I have read the definition of IntegrityError but honestly do not quite understand this: This exception is raised when the relational integrity of the data is affected. def signup(request): if request.method == 'GET': return render(request, 'signup.html', {'form': UserCreationForm}) else: if request.POST['password1'] == request.POST['password2']: try: user = User.objects.create_user(request.POST['username'], password=request.POST['password1']) user.save() login(request, user) return redirect('home') except IntegrityError: return render(request, 'signup.html', {'form': UserCreationForm, 'error': 'Username already exists'}) else: return render(request, 'signup.html', {'form': UserCreationForm, 'error': 'Passwords do not match'}) I have seen this code in a Django project. I would appreciate your feedback. -
Django FileField - how to save files to different directories
I have two similar forms for upload files, but I want to save files in different directories depending on the form. Let me explain, for example: if User uploaded file from Form_1 -> file should be save in media/folder_file_1/file.csv if User uploaded file from Form_2 -> file should be save in media/folder_file_2/file.csv Regarding models.py, forms.py, views.py, urls.py I just used examples from Django docs. index.html: <!DOCTYPE html> {% load static %} <body> <div class="page_secondblock secondblock"> <div class="secondblock__container _container"> <h1 class="secondblock__title"> The file you want to update: </h1> <h2 class="secondblock__title"> The file from which you want to get information: </h2> </div> </div> <div class="page_thirdblock thirdblock"> <div class="thirdblock__container _container"> <form method="POST" enctype="multipart/form-data" class="upload1" id="upload_container"> {% csrf_token %} {{form.as_p}} <input type="submit" value="Submit"> </form> <form method="POST" enctype="multipart/form-data" class="upload2" id="upload_container"> {% csrf_token %} {{form.as_p}} <input type="submit" value="Submit"> </form> </div> </div> </body> models.py: from django.db import models class UploadFile(models.Model): file = models.FileField(upload_to='working/') forms.py: from django import forms from .models import UploadFile class UploadFileForm(forms.ModelForm): class Meta: model = UploadFile fields = ['file'] views.py: from django.shortcuts import render from django.http import HttpResponse, HttpResponseRedirect from .forms import UploadFileForm def index(request): return render(request, "index.html") def tools(request): return render(request, "index.html") def login(request): return render(request, "index.html") def upload_file(request): if request.method == 'POST': … -
How to configure SSL certificate inside my docker container?
I have a django application that running inside a docker container. However, while the application works perfectly fine inside my local PC when running inside the container it is unable to make any requests such as calling certain APIs or even pip install. All of these actions will throw an error like [SSL: CERTIFICATE_VERIFY_FAILED] certificate verify failed: unable to get local issuer certificate (_ssl.c:992). Only way I got pip install working is to do RUN pip install --trusted-host pypi.org --trusted-host pypi.python.org --trusted-host=files.pythonhosted.org --no-cache-dir -r requirements.txt Solutions tried: Copying my local rootCA.pem file to /usr/local/share/ca-certificates/ in the container RUN update-ca-certification Tried different python providers (alpine, buster, slim-buster) There are many more I couldn't remember I don't want to just turn verify off as it is bad practice so I'm trying to keep verification on. I have included my Dockerfile below. Dockerfile: FROM python:3.11.2-slim-buster ENV PYTHONUNBUFFERED=1 WORKDIR /app RUN apt-get update && apt-get install -y ca-certificates COPY certs/rootCA.pem /usr/local/share/ca-certificates/ RUN update-ca-certificates COPY requirements.txt requirements.txt RUN pip install --trusted-host pypi.org --trusted-host pypi.python.org --trusted-host=files.pythonhosted.org --no-cache-dir -r requirements.txt COPY . . CMD ["python", "manage.py", "runserver", "0.0.0.0:8000"]