Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
psql version does not change to 12 even after upgrade
I have acquired an image of postgre sql and i have imported data into the a table my_spo_stats in database music. I intended to build a webpage with Django with this being my database, so i started in this container building Django projects. However, when i ran python3 manage.py makemigrations, I got the following error: raise NotSupportedError( django.db.utils.NotSupportedError: PostgreSQL 12 or later is required (found 11.9). but i did pull the image specifying the version to be 12. Regardless, i tried to upgrade my psql . i did sudo apt-get update. sudo apt-get install postgresql-12 postgresql-server-dev-12, and (in case of any need for closer examination here) the output was invoke-rc.d: could not determine current runlevel invoke-rc.d: policy-rc.d denied execution of start. Setting up libsensors-config (1:3.6.0-2ubuntu1.1) ... Setting up libllvm10:amd64 (1:10.0.0-4ubuntu1) ... Setting up postgresql-client-12 (12.17-0ubuntu0.20.04.1) ... update-alternatives: using /usr/share/postgresql/12/man/man1/psql.1.gz to provide /usr/share/man/man1/psql.1.gz (psql.1.gz) in auto mode Setting up ssl-cert (1.0.39) ... debconf: unable to initialize frontend: Dialog debconf: (No usable dialog-like program is installed, so the dialog based frontend cannot be used. at /usr/share/perl5/Debconf/FrontEnd/Dialog.pm line 76.) debconf: falling back to frontend: Readline Setting up libclang1-10 (1:10.0.0-4ubuntu1) ... Setting up postgresql-common (214ubuntu0.1) ... debconf: unable to initialize frontend: Dialog debconf: (No … -
Django: Custom forms for each record
I am making a web app with the model below. I would like to make a list of Meals with checkboxes displayed depending on whether each meal offers takeaway, eat_in or both and sign them up as a Participant with their choice of takeaway, eat_in or both. from django.db import models from django.utils.timezone import localtime from django.conf import settings from django.db import models # Create your models here. class Meal(models.Model): meal_time = models.DateTimeField("Tid/Dato") meal_description = models.CharField(verbose_name="Beskrivelse af måltid", max_length=300) meal_deadline = models.DateTimeField(verbose_name="Tilmeldingsfrist") meal_price_pp = models.DecimalField(verbose_name="Pris per person", decimal_places=2, max_digits=5) meal_price_tt = models.DecimalField(verbose_name="Pris i alt", decimal_places=2, max_digits=5) meal_resp = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.CASCADE) meal_offer_takeaway = models.BooleanField(verbose_name="Tilbyd takeway", default=False) meal_offer_eat_in = models.BooleanField(verbose_name="Tilbyd spisning i netværket", default=False) # meal_timezone = models.CharField(verbose_name="Tidszone", default='Europe/Copenhagen', max_length=50) def __str__(self): return (f"{self.meal_description} Dato:" f" {localtime(self.meal_time).date().strftime("%d/%m/%Y")} " f"{localtime(self.meal_time).strftime("%H:%M")} Pris: {self.meal_price_pp}") def weekday(self): weekdays = ["Mandag", "Tirsdag", "Onsdag", "Torsdag", "Fredag", "Lørdag", "Søndag"] index = self.meal_time.date().weekday() return weekdays[index] def resp_name(self): return self.meal_resp.name class Participant(models.Model): list_user = models.ForeignKey(settings.AUTH_USER_MODEL, verbose_name="Bruger", on_delete=models.CASCADE) list_meal = models.ForeignKey(Meal, verbose_name="Måltid", on_delete=models.CASCADE) list_takeaway = models.BooleanField(verbose_name="Tilmeld takeaway", default=False) list_eat_in = models.BooleanField(verbose_name="Tilmeld spisning i netværket", default=False) list_registration_time = models.DateTimeField(verbose_name="Date/time registered") payment_due = models.DateField(verbose_name="Betales senest") payment_status = models.BooleanField(verbose_name="Er betalt", default=False) def registered_on_time(self): meal_record = self.list_meal return self.list_registration_time <= meal_record.meal_deadline def __str__(self): return f"Bruger: {self.list_user} … -
How I can throttle only the POST method in this views
class ExampleView(APIView): throttle_classes = [UserRateThrottle] def get(self, request, format=None): content = { 'status': 'request was permitted' } return Response(content) def post(self, request, format=None): content = { 'status': 'request was permitted' } return Response(content) I want to throttle only the post method view not the get. I have declared two views POST and GET and I want only to implement throttling for my POST view -
Custom Adapter inheriting from DefaultSocialAccountAdapter in django-allAuth throwing error
I am using django-allauth to login with Steam in my Django application. I want that when a new user signs up, the user's steam id is also stored in the database. I want to extend the DefaultSocialAccountAdapter and use a custom adapter. Here is my code from allauth.socialaccount.adapter import DefaultSocialAccountAdapter import logging logger = logging.getLogger(__name__) class CustomAccountAdapter(DefaultSocialAccountAdapter): def save_user(self, request, user, form, commit=True): user = super().save_user(request, user, form, commit=False) social_account = user.socialaccount_set.filter(provider='steam').first() if social_account: user.steam_id = social_account.uid if commit: user.save() return user When I use this adapter by setting the SOCIALACCOUNT_ADAPTER in my settings.py file, it throws an error stating DefaultSocialAccountAdapter.new_user() missing 1 required positional argument: 'sociallogin' I also tried to over-ride the new_user method but still got the same error. I tried this: def new_user(self, request): user = super().new_user(request) user.steam_id = sociallogin.account.uid return user But the error remains the same. It shows the error at /usr/local/lib/python3.10/site-packages/allauth/socialaccount/adapter.py, line 71, in new_user """ pass def new_user(self, request, sociallogin): """ Instantiates a new User instance. """ return get_account_adapter().new_user(request) <--- error on this line def save_user(self, request, sociallogin, form=None): """ Saves a newly signed up social login. In case of auto-signup, the signup form is not available. """ I went ahead and looked … -
ModuleNotFoundError: No module named 'school.message_test'
I'm encountering a ModuleNotFoundError when trying to import a module in my Django project. Here's the code snippet: import os import django from channels.routing import ProtocolTypeRouter, URLRouter from channels.auth import AuthMiddlewareStack from django.core.asgi import get_asgi_application from school.message_test.routing import websocket_urlpatterns os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'school.settings') django.setup() application = ProtocolTypeRouter({ "http": get_asgi_application(), "websocket": AuthMiddlewareStack( URLRouter( websocket_urlpatterns ) ), }) specifically on this line: from school.message_test.routing import websocket_urlpatterns I've double-checked that all the paths are correct, and the file is in the right directory. What could be causing this issue, and how can I resolve it? to run the project I used this command: daphne -p 8000 school.asgi:application I'll try to use a relative path which naturally won't work. I also tried using it for the top level, that is from ..message_test.routing import websocket_urlpatterns but it doesn't work because asgi doesn't allow it the path is absolutely correct, what can you tell me? photo of the full project path -
Django: Convert IntegerField to ForeignKey
I have a database with this django model: class System(models.Model): system_id = models.IntegerField(primary_key=True) constellation_id = models.IntegerField() It already has some data, and EVERY row of the table has constellation_id. And now I created a new table with data: class Constellation(models.Model): constellation_id = models.IntegerField(primary_key=True) Is it possible to refactor constellation_id of System model from IntegerField into ForeignKey? All of the constellation_ids in System table exist in Constellation table. -
Image is not displaying in Django from static
The following is the only code where I mention the image: Inside the HTML and CSS file: <button type="submit" class="task-item-button"> <img src="{% static 'x.svg' %}" alt="Close icon"> </button> .task-item-button { position: absolute; top: 10px; /* Adjust the top position */ right: 10px; /* Adjust the right position */ width: 20px; height: 20px; color: red; padding: 0; border: none; background: none; border-radius: 8px; cursor: pointer; } .task-item-button img { width: 20px; /* Adjust the width of the image as needed */ height: 20px; /* Adjust the height of the image as needed */ } and I do have {% load static %} at the top. Apart from that I have no other mentions of the images anywhere. The structure of static looks like: Thanks for any help. -
Why can't I activate virualenv on Mac?
I'm was working on a project few months earlier that I hadn't modified in the las 3 months. During this period I changed my Macbook and transferred everything with Time Machine. My other projects that don't using virtualenv works fine but in case of this project I am not able to activate the virtualenv. Structure: coachregiszter --bin --include --lib --mcr (this is my project folder where manage.py is) --pyenv.cfg If I try: source bin/acivate I get this error message: source bin/activate Script started, output file is started Script: on: No such file or directory Script done, output file is started bin/activate:2: bad pattern: ^[[1m^[[7m%^[[27m^[[1m^[[0m What is the problem? -
How to convert string filed to list field in serializer
I have a simple django model models.py file: from django.db import models class MyModel(models.Model): my_field = models.CharField(max_length=20) def __str__(self): return self.my_field serializers.py file from rest_framework import serializers from .models import MyModel class MySerializer(serializers.ModelSerializer): class Meta: model = MyModel fields = '__all__' Using generic view I list all of items views.py from rest_framework import generics from .serializers import MySerializer from .models import MyModel class TestView(generics.ListAPIView): serializer_class = MySerializer queryset = MyModel.objects.all() urls.py from django.urls import path from . import views urlpatterns = [ path('test\', views.Test.as_view()), ] And I got following json output: [ { "id":1, "my_field":"a,b,c" }, { "id":2, "my_field":"a" }, { "id":3, "my_field":"b,c" } ] Now I want to convert my_filed values from string to comma-separated list, expected output: [ { "id":1, "my_field":["a", "b", "c"] }, { "id":2, "my_field": ["a"] }, { "id":3, "my_field":["b", "c"] } ] I tried to modify MySerializer as below: serializers.py from rest_framework import serializers from .models import MyModel class MySerializer(serializers.ModelSerializer): class Meta: model = MyModel fields = '__all__' def __init__(self, *args, **kwargs): super(MySerializer, self).__init__(*args, **kwargs) return self.fields['my_field'].split(',') but I got AttributeError: CharField object has no attribute 'split'. Do you have any ideas how to get expected output? Any hints are appreciated! -
Asynchronous processing when using Celery in a Django application (Heroku)
I am developing an application that uses the Whisper API to convert uploaded audio files into text. I am trying to use Celery for asynchronous processing, but I can't seem to reference the media file properly. I get a "FileNotFoundError: [Errno 2] No such file or directory: '/app/media/audio/xxx.mp3'" error. Before the asynchronous processing, I was able to reference the file with no problem. What should we do in such a case? ・setting.py MEDIA_URL = '/media/' MEDIA_ROOT = os.path.join(BASE_DIR, 'media') ・views.py upload_path = os.path.join(settings.MEDIA_ROOT, "audio") audio_file_path = os.path.join(upload_path, file) convert_text.delay(audio_file_path) ・tasks.py @shared_task def convert_text(audio_file_path): openai.api_key = "xxxxxxxxxxx" audio_file= open(audio_file_path, "rb") transcript = openai.Audio.transcribe("whisper-1", audio_file) text_data = transcript["text"] -
React 'style' conflict with Django template(?)
So I'm using python django as well as inline babel script (React). Now my problem is I think that React's style style={{ height : '100px' }} conflicts with Django templates. I tried using djangos verbatim tag but still no luck. -
Django Mail Template Rendering With render_to_string
I am trying to send mail with django and I can send but when I am sending the mail, it contains <body> tags or <div> tags, I can not customize the mail template. I am using this code in my views.py template = render_to_string('mailapp2/email.html', { 'name':request.user.username, 'date':date, 'city':city, }) email = EmailMessage( 'Meeting Notification', template, settings.EMAIL_HOST_USER, [request.user.email], ) email.fail_silently=False email.send() How can I solve this, thank you from now :) I have tried using css but I can not use <div> tags for using id or class -
How can I get a batch of frames from consumers.py?
Currently, I am working on a computer vision project that involves object detection and real-time frame streaming using opencv and django. To accomplish this, I am utilizing django-channels. However, I have encountered a new challenge where I need to perform video classification. This requires sending a batch of frames to the model. Can you provide any guidance on how to approach this issue? I added a button on the front-end. What I expected was to obtain a single timestamp from the back-end consumers.py. What I got was the timestamp of the start frame till the timestamp of the frame where the button was clicked. Here is an example image of it In the consumers.py file, I'm utilizing the OpenCV library to iterate through the frames, and then I'm transmitting that data to the websocket client. Here is an example of the code (I have also provided the comments for better understanding). # Import the 'cv2' module, which is the OpenCV library for computer vision tasks. import cv2 # Import the 'json' module for working with JSON data. import json # Import the 'asyncio' module for asynchronous programming support. import asyncio # Import the 'datetime' module for working with date and … -
How to take images from Media folder from another domain?
I have 2 domains: naiuma.com and jp.naiuma.com. I have uploaded all images to Media Folder on naiuma.com and now I want to access them on jp.naiuma.com. In my models I have something like: thumbnail = models.ImageField(upload_to ='uploads/posts/') And in the settings I have: BASE_DIR = Path(__file__).resolve().parent.parent MEDIA_URL = 'media/' MEDIA_ROOT = os.path.join(BASE_DIR,'media') But of course it doesn't work since it is constructed to be used in the frames of one single domain. Please let me know, what should I do to connect thumbnail = models.ImageField with the old, main naiuma.com domain and it's hosting? Thanks. -
Django; add integer primary_key in production
We have a running instance of a Django Backend. On a few model we used an CharField as an Primary Key because it was the best solution for the old requirements. Now we need to add a basic int id like id = models.AutoField(primary_key=True) and let the old charfield remain as primary_key=False. I removed the primary_key=True Flag from the old primary key attribute and triggerd ./manage.py makemigrations. If I dont declare any primary key Django is generating its normal id like mentioned above. But after trigger, Djang asks for default values for old entries of this model like: It is impossible to add a non-nullable field 'id' to anrede without specifying a default. This is because the database needs something to populate existing rows. Please select a fix: 1) Provide a one-off default now (will be set on all existing rows with a null value for this column) 2) Quit and manually define a default value in models.py. Becaus its an unique Field, I cant use any static content. So how can I still make migrations without delete old migrations? -
In Django i'm having trouble calling a form. I see the button but not the textboxes
In the index.html page (home page) I am trying to display a form and i call the form like this: {% include 'registration/register.html' %} I would like to view the form directly on index.html (127.0.0.1:8000) and not on http://127.0.0.1:8000/register, but the problem is that in index.html, i see the button but not the textboxes (username, email, password): I don't know what I'm doing wrong This is App1: App1 .migrations .static .templates ..index.html ..registration ...register.html index.html {% load static %} <!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta http-equiv="X-UA-Compatible" content="IE=edge"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <title>University</title> <!-- Bootstrap CSS --> <link href="https://cdn.jsdelivr.net/npm/bootstrap@5.3.2/dist/css/bootstrap.min.css" rel="stylesheet"> <link href="https://getbootstrap.com/docs/5.3/assets/css/docs.css" rel="stylesheet"> <link href="/static/css/style.css" rel="stylesheet"> </head> <body> ....... ....... {% include 'registration/register.html' %} </body> </html> App1/templates/registration/register.html {% block content %} <!--Register--> <div class="container py-5"> <h1>Register</h1> <form method="POST"> {% csrf_token %} {{ register_form.as_p }} <button class="btn btn-primary" type="submit">Register</button> </form> <p class="text-center">If you already have an account, <a href="/login">login</a> instead.</p> </div> {% endblock %} App1/forms.py from django import forms from django.contrib.auth.forms import UserCreationForm from django.contrib.auth.models import User # Create your forms here. class NewUserForm(UserCreationForm): email = forms.EmailField(required=True) class Meta: model = User fields = ("username", "email", "password1", "password2") def save(self, commit=True): user = super(NewUserForm, self).save(commit=False) user.email = self.cleaned_data['email'] if commit: … -
annotation with a table referred to by content_type + object_id in DjangoORM
So issue is I need to filter by title field that in many others tables. class Model uses contenttypes framework in django. It refers to several tables that have a title field (field I want to filter by) class Model(models.Model): content_type = models.ForeignKey( ContentType, on_delete=models.CASCADE, limit_choices_to={'model__in': ('model1', 'model2', 'model3', 'model4', 'model5')}, ) object_id = models.CharField(max_length=36) content_object = GenericForeignKey('content_type', 'object_id') Every table that has the title field has GenericRelation(Model, related_query_name='elements') class model1(models.Model): # and etc for model2, model3... title = models.CharField(max_length=255) myfield = GenericRelation(Model, related_name_query='elements') First I Tried Model.objects.annotate(title=F('elements__title')). But for some reasons it does not work for me because it joins only one table. It makes sence because anyway I need to handle these strings with Coalesce. So I figured it out by create my own SQL query but I cannot convert it to DjangoORM here is the query SELECT "mm"."id", COALESCE("model1"."title", "model2"."title", "model3"."title", "model4"."title", "model5"."title") AS "title" FROM "Model" AS "mm" LEFT OUTER JOIN "model1" AS "model1" ON ("mm"."object_id" = "model1"."id") LEFT OUTER JOIN "model2" AS "model2" ON ("mm"."object_id" = "model2"."id") LEFT OUTER JOIN "model3" AS "model3" ON ("mm"."object_id" = "model3"."id") LEFT OUTER JOIN "model4" AS "model4" ON ("mm"."object_id" = "model4"."id") LEFT OUTER JOIN "model5" AS "model5" ON ("mm"."object_id" … -
self.serializer = import_string(settings.SESSION_SERIALIZER)
I apologize for the bad English. I bought a new computer, moved my files, installed all my libraries, and wanted to get my work back on its feet. But I encountered an unexpected error, the problem is exactly as follows The error I received is like this. I did research on how to solve the problem, but I could not find a solution. I am grateful in advance to those who will solve this problem of mine. Good work. -
How to get uploaded file's path?
When I upload file through admin dashboard in Django dev server, I always get error that file doesnt exist. With that it is pointing in local folder and searching for <file_name> I want to upload it to supabase but Django isn't finding the file which i Choose in /admin This is my code: class PupinObject(models.Model): video = forms.FileField(upload_to='videos/') creation_date = models.DateTimeField(auto_now_add=True) user = models.ForeignKey(PupinUser, on_delete=models.CASCADE) def save(self, *args, **kwargs): url = os.environ.get("SUPABASE_URL") key = os.environ.get("SUPABASE_KEY") supabase = create_client(url, key) bucket_name = "videos" new_file = self.video.path print(default_storage.path(self.video.name)) jwt = supabase.auth.sign_in_with_password({ "email": self.user.email, "password": self.user.password }) # Upload the file to the user's directory supabase.storage.from_(bucket_name).upload(f"/{jwt.user.id}/video.mp4", new_file) super().save(*args, **kwargs) I tried getting absolute path but no light. -
ExpoAV Video, video I get from Django server is not loading
I am working on an Expo app and I use the component from expo-av. When I source the video from my assets, it works. But when I try to display a video which is stored on my Django server, it is not loading. here is my code <Video style={{width: window.width * .93, height: window.width * .93 * 1.05,}} source={{uri: server + "media/" + media.uri}} shouldPlay usePoster /> When I do the url on http request, I get the video I want. But it is not working on the expo app. How can I fix this? -
Why do I have Broken links on my ecommerce project website dropdown menu?
I have a simple dropdown in my main navigation of my website buiot with django and python. The links are dead, although I can see the categories i the browser URL extension. I have looked at the code and I cant seem to find where to fix the issue. I have categories created in my django admin for my products and the correct category names oin the dropdown. I have manually added approximately 20 products through heroku front end deployed site and they have been added successfully, and also show in the correct category on their respective product page too. The main issue is the dropdown nav which gives 0 results when selected by category <div class="dropdown-menu border-0" aria-labelledby="soup-link"> <a href="{% url 'products' %}?category=soup" class="dropdown-item">Soups</a> <a href="{% url 'products' %}?category=stews" class="dropdown-item">Stews</a> <a href="{% url 'products' %}?category=broth" class="dropdown-item">Broth</a> <a href="{% url 'products' %}?category=hotpot" class="dropdown-item">Hotpot</a> </div> this shows my code which I have created in main-nav.html I think it is a URL routing issue -
Django with Docker is not allowing to access external API and is throwing Failed to resolve 'my-host-name' ([Errno -5] No address associated
I am new to django and Docker. The issue I am facing is when I want to fetch some data from external API and just display it in a view I am getting an error "Failed to resolve 'my-host-name' ([Errno -5] No address associated with hostname". But the API is working fine in postman and I tested it Here is my view file: import json from django.http import HttpResponse from django.shortcuts import render import requests def index(request): host='http://my_host:8190' token='My_Auth_Token' hd = {'Authorization': str({token})} data=requests.get(f"{host}/api/xyz" ,headers=hd) return render(request,"Loading/index.html",{'bundles':data}) In the html file I am just displaying the data. Please help me out with this. Thanks in advance :) I am trying to access an API endpoint for which I am getting Failed to resolve 'srd-web-apps-dev' ([Errno -5] No address associated with hostname when I use djangyour texto with docker. But If I use django without Docker it doesn't throw any error. -
My docker-compose can not run or build, causing issues
I am creating a django application and I am creating docker container for that application. I am using mySQL database. So after creating my entire project when I was succesfully running, I createrd Dockerfile and docker-compose.yml file. Here is the content of my file. Dockerfile ENV DockerHOME=/home/app/webapp RUN mkdir -p $DockerHOME WORKDIR $DockerHOME ENV PYTHONDONTWRITEBYTECODE 1 ENV PYTHONUNBUFFERED 1 RUN pip install --upgrade pip COPY . $DockerHOME RUN pip install -r requirements.txt # Add Django migrations and apply them RUN python manage.py makemigrations RUN python manage.py migrate EXPOSE 8080 CMD ["python", "manage.py", "runserver", "0.0.0.0:8080"] and here is my docker-compose.yml version: '3' services: web: image: blogs:latest container_name: blogs_web ports: - "8080:8080" volumes: - .:/home/app/webapp environment: - PYTHONDONTWRITEBYTECODE=1 - PYTHONUNBUFFERED=1 - SECRET_KEY=${SECRET_KEY} - DEBUG=${DEBUG} - DATABASE_NAME=${DATABASE_NAME} - DATABASE_USER=${DATABASE_USER} - DATABASE_PASSWORD=${DATABASE_PASSWORD} - DATABASE_HOST=${DATABASE_HOST} - DATABASE_PORT=${DATABASE_PORT} depends_on: - db db: image: data:latest container_name: blogs_db environment: MYSQL_DATABASE: ${DATABASE_NAME} MYSQL_USER: ${DATABASE_USER} MYSQL_PASSWORD: ${DATABASE_PASSWORD} MYSQL_ROOT_PASSWORD: ${DATABASE_ROOT_PASSWORD} ports: - "3306:3306" command: --default-authentication-plugin=mysql_native_password When I run docker-compose build it gives me this response [+] Building 0.0s (0/0)``` The build isn't right. and when I do ```docker-compose up``` here is my error [+] Running 2/2 ✘ web Error 3.8s ✘ db Error 3.8s Error response from daemon: pull access denied … -
How to annotate field for the right sorting
I annotate queryset in Django like this: q_set = q_set.annotate( period=Concat( ExtractYear(date_field), Value(' - '), ExtractMonth(date_field), output_field=CharField() ), ) But then I get this result: 2022 - 12 2023 - 1 2023 - 10 2023 - 11 2023 - 12 2023 - 2 2023 - 3 2023 - 4 2023 - 5 2023 - 6 2023 - 7 2023 - 8 2023 - 9 But I need to sort it in a right order... -
Django-Allauth MultipleObjectsReturned
I use django-sites model to seperate localhost:8000 and productive_server.de for test purpose. Django-Allauth with login from e.g. Github throws an exception "MultipleObjectsReturned" even though provider github is in the database with either "localhost:8000" or "productive_server.de" as SITE_ID. There is no additional list of providers in settings.py I have traced down the problem to env/Lib/site-packages/allauth/socialaccount/adapter.py -> DefaultSocialAccountAdapter(object) -> list_apps(self, request, provider=None, client_id=None) def list_apps(self, request, provider=None, client_id=None): """SocialApp's can be setup in the database, or, via `settings.SOCIALACCOUNT_PROVIDERS`. This methods returns a uniform list of all known apps matching the specified criteria, and blends both (db/settings) sources of data. """ # NOTE: Avoid loading models at top due to registry boot... from allauth.socialaccount.models import SocialApp # Map provider to the list of apps. provider_to_apps = {} # First, populate it with the DB backed apps. if request: db_apps = SocialApp.objects.on_site(request) # <-------- filter according "site_id" only if request is given else: db_apps = SocialApp.objects.all() in the error trace it turns out that on the way the "request" parameter is not handed over -> so no filter according "site_id" and a thus 2 providers are returned -> exception: Traceback (most recent call last): File "...\env\lib\site-packages\django\core\handlers\exception.py", line 47, in inner response = get_response(request) File …