Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Login and authentication with Django REST framework
I would like help from someone who has more experience with the Django REST framework, to tell me if the login and authentication system I created follows the right framework standards I'm in doubt whether or not Django's login() function should be used in some part of my code, in the client views I want to avoid any direct access to the server, so I do all the logic involving the database in the microservice views, in my "UserLoginAPI" microservice view, should I use the login(request, user) function to log in the user? I saw in some discussions that I should replace login() with update_last_login(None, user) and that's what I did but I'm not sure if it's right I would also like to know if my authentication middleware is correct, both to ignore public views and to check the token and update the user in the session I don't have a lot of experience and I would appreciate it if you could tell me if my code is following the right standards or if there is something I can improve, a certain problem that I can avoid. My login flow is: The HTML form, through a POST request, sends the … -
Changin beheaviour of django-two-factor-auth package
I have being using django-two-factor-auth package and it was really simple to set up. Unfortunately my boss wants to do some changes which more advanced for my junior level. Firstly, we are working in a type of browser dashboard web app and so all users needs to authenticate before logging in. So the first view needs to be the login. Secondly, i was asked that if the user hasnt enabled the two-factor qr code, the authentication needs to redirect the user to the set up view to enable it. So users wont be able to use the app unless they have the 2FA enabled. How can i achieve this? I tried to dig into the documentation but im feelling too lost right now and i would appreciate some insight on the matter. Thank you all. I tried looking into the documentation but got lost on it. Then i tried to see if i can change the package code but couldnt find it. Also tried to add a path with name 'login' but it doesnt work. -
I am looking for experiences with AI Application devlopment companies from India? [closed]
How Can identify whether an Off-shore AI Development company for example from India is a serious and competent partner for my AI Application development project? Any Experiences? Thank you in advance! Because the web is full such companies, but it is difficult to evaluate them and seprate good from bad and serious and scams! -
Making changes in the Django models VS. making changes directly on the database vs
This question is motivated by another question I posted yesterday where the migrations I have applied are not altering the database tables. So, my only solution to do that change is to alter the database directly through SQL commands. Specifically, I want to allow nulls in a particular table field. Are there any pitfalls I should be aware of before doing that change directly on the PostGreSQL database? -
How to add custom js for select in Wagtail choice block
My goal is to have select (dropdowns) handled by custom-select js library for blocks in Wagtail Stream Field. As it is quite easy to add for normal fields when event DOMContentLoaded is triggered. But is there any event or hook for adding a block to StreamField? I tried even calling my function in html template for block. But it seems to be called too early because styles are not applied to selects in this html. this is my .js (typescript) const initColorChoosers = () => { const colorChoosers = Array.from(document.querySelectorAll('.color-chooser select')) as HTMLSelectElement[]; colorChoosers.forEach((chooser) => { if (!chooser.hasAttribute('custom')) { chooser.setAttribute("custom", "true") new CustomSelect(chooser, { customOptionClass: 'option--hero-glow-color' }) } }) } document.addEventListener("DOMContentLoaded", function (event) { window.myfuncs.initColorChoosers = () => initColorChoosers(); }); and my color chooser: class Colors(blocks.ChoiceBlock): choices = [ ('color1', 'color1'), ('color2', 'color2'), ('color2', 'color2'), ] required = False, class Meta: form_classname = 'color-chooser' icon = 'copy' and block template at the end contains: <script> window.myfuncs.initColorChoosers() </script> And it works.. but for already added blocks not for the current one. So if I add a block which contains ColorChooser, it won't apply logic from custom-select but when I add another one, for the first one changes will be applied. -
Django. "dictionary changed size during iteration" while not changing anything
I think I am going insane here. I am trying to iterate over a dictionary containing lists. This is my code: (Yes i know this is not enough to accomplish what I am trying to do, but I have shaved the code down to the minimum while still causing the problem): {% for wc in response %} <tr> <td>{{ response.wc }}</td> </tr> {% endfor %} But i get this error "dictionary changed size during iteration" As anybody with half a brain can see, I am very much not changing ANYTHING in the dict of lists. I am thinking of a hacky solution, just pass another list of of the keys to the template, which I can use to iterate over the list, like: {%for key in keys%} response.key. This just seems like the wrong way to do it. -
Django: annotate query of one model with count of different non-related model which is filtered by a field of first model
Long title in short : I have a complex annotate query to work with. Example Models: class FirstModel(models.Model): master_tag = models.CharField() ... other fields class SecondModel(models.Model): ref_name = models.CharField() I want to fetch all objects from FirstModel with count of all objects from SecondModel if ref_name of this objects are same as master_tag of FirstModel object. What i tried: I tried using annotate with Subquery and OuterRef but can not get this to work as getting constant errors. from django.db.models import OuterRef, Subquery, Count sub_query = Subquery( SecondModel.objects.filter(ref_name=OuterRef("master_tag")).values_list("pk", flat=True) ) FirstModel.objects.annotate(sm_count=Count(sub_query)) This gave me error : "django.db.utils.ProgrammingError: more than one row returned by a subquery used as an expression" I tried lots of other things one of which is putting ".count()" at the end of subquery but that causes another error as count tries to evaluate query eagerly and fails due to OuterRef. So is there a way to fetch a query like this with the count annotation ? Any stupid mistakes i made in writing above query ? -
"matching query does not exist" when creating an object
I have: class GoogleSignIn(APIView): def post(self, request): settings = request.settings code = request.data['code'] # Verify the OAuth code with Google try: google_user_info = verify_user(code) except Exception as e: print(str(e)) return Response({'error': 'Failed to verify with Google.'}) email = google_user_info['email'] picture = google_user_info['picture'] try: user = User.objects.get(email=email) user_info = UserInfo.objects.get(user=user) except User.DoesNotExist: first_name = google_user_info['given_name'] user = User.objects.create_user( email = email, username = email, first_name = first_name, last_name = google_user_info['family_name'], password=None) user_info = UserInfo.objects.create( user = user, credits = request.settings.INITIAL_CREDITS, expiry = compute_credits_expiry( num_days=settings.FREE_CREDITS_EXPIRY_IN_DAYS)) The last statement (that is, creating the UserInfo object in the exception handler) produces an exception: accounts.models.UserInfo.DoesNotExist: UserInfo matching query does not exist. What does it mean? The complete output: Internal Server Error: /accounts/google-sign-in/ Traceback (most recent call last): File "/mnt/c/Dropbox/Parnasa/Web/wherewasit/backend/accounts/views.py", line 129, in post user = User.objects.get(email=email) File "/usr/lib/python3/dist-packages/django/db/models/manager.py", line 85, in manager_method return getattr(self.get_queryset(), name)(*args, **kwargs) File "/usr/lib/python3/dist-packages/django/db/models/query.py", line 435, in get raise self.model.DoesNotExist( django.contrib.auth.models.User.DoesNotExist: User matching query does not exist. During handling of the above exception, another exception occurred: Traceback (most recent call last): File "/usr/lib/python3/dist-packages/django/core/handlers/exception.py", line 47, in inner response = get_response(request) File "/usr/lib/python3/dist-packages/django/core/handlers/base.py", line 181, in _get_response response = wrapped_callback(request, *callback_args, **callback_kwargs) File "/usr/lib/python3/dist-packages/django/views/decorators/csrf.py", line 54, in wrapped_view return view_func(*args, **kwargs) File … -
how can I do django custom authorization? I need admin auth by username and password and users by only phone number
How can I realize this code? admin use only admin panel for authorization users doesn't use admin panel therefore they use only app for authorization with OTP phonenumber. from django.contrib.auth.base_user import BaseUserManager from django.utils.translation import gettext as _ class CustomUserManager(BaseUserManager): """ Custom user model manager where email is the unique identifier for authentication instead of usernames. """ # oddiy userlar yaratish uchun def create_user(self, email, password, **extra_fields): if not email: raise ValueError(_('Users must have an email address')) email = self.normalize_email(email) user = self.model(email=email, **extra_fields) user.set_password(password) user.save() return user # supper user yaratish uchun def create_superuser(self, email, password, **extra_fields): extra_fields.setdefault('is_staff', True) extra_fields.setdefault('is_superuser', True) extra_fields.setdefault('is_active', True) if extra_fields.get('is_staff') is not True: raise ValueError(_('Superuser must have is_staff=True.')) if extra_fields.get('is_superuser') is not True: raise ValueError(_('Superuser must have is_superuser=True.')) return self.create_user(email, password, **extra_fields) I have manager class and I looked similar code. from django.contrib.auth.backends import ModelBackend from django.contrib.auth import get_user_model class EmailBackend(ModelBackend): def authenticate(self, request, email=None, password=None, **kwargs): UserModel = get_user_model() try: user = UserModel.objects.get(email=email) except UserModel.DoesNotExist: return None else: if user.check_password(password): return user def get_user(self, user_id): UserModel = get_user_model() try: return UserModel.objects.get(pk=user_id) except UserModel.DoesNotExist: return None I looked some video in youtube I didn't find. -
Django: collectstatic is not collecting static files
I found a github proyect. Copied it locally, but running collecstatic does not copy files to staticfiles folder. Why? If I do the full path search: python manage.py findstatic D:\web_proyects\imprenta_gallito\static\css\home.css I get error: django.core.exceptions.SuspiciousFileOperation: The joined path (D:\web_proyects\imprenta_gallito\static\css\home.css) is located outside of the base path component (D:\virtual_envs\imprenta_gallito\Lib\site-packages\django\contrib\admin\static) settings.py: import os import os import secrets from pathlib import Path import dj_database_url from decouple import config # SITE_ROOT = root() # Build paths inside the project like this: BASE_DIR / 'subdir'. BASE_DIR = Path(__file__).resolve().parent.parent # Quick-start development settings - unsuitable for production # See https://docs.djangoproject.com/en/2.1/howto/deployment/checklist/ # SECURITY WARNING: keep the secret key used in production secret! SECRET_KEY = os.environ.get( "SECRET_KEY", default=secrets.token_urlsafe(nbytes=64), ) #DEBUG = config('DEBUG', default=False, cast=bool) # The `DYNO` env var is set on Heroku CI, but it's not a real Heroku app, so we have to # also explicitly exclude CI: # https://devcenter.heroku.com/articles/heroku-ci#immutable-environment-variables IS_HEROKU_APP = "DYNO" in os.environ and not "CI" in os.environ # SECURITY WARNING: don't run with debug turned on in production! if not IS_HEROKU_APP: DEBUG = True # On Heroku, it's safe to use a wildcard for `ALLOWED_HOSTS``, since the Heroku router performs # validation of the Host header in the incoming HTTP request. On other platforms … -
How to fix Django regualr expression Problem
Django Rest Framework after User registration sends out an Email for the new User to verify the EMail adress. The link attached is like https://my_domain.com/api/verify_email/?token=ddfddjrf....fddkfjdjh my api.urls.py file looks like: api.urls.py from django.urls import re_path from . import views urlpatterns = [ re_path(r'^verify_email/(?P<token>[\w.-]+)/',views.verify_email, name="verify_email"), [ and in project urls.py ... path('api/', include("api.urls")), ... When I try to run that link I get: Page not found (404) The current path api/verify_email/, didn't match any of these. I can see a URL pattern from the URL.conf: Django tried these URL patterns,in this order. ... api/ ^verify_email/(?P[\w.-]+)/ [name='verify_email'] ... I hope somebody can help because I can't find a solution somewhere .... And I tried several things to fix it. But without any success. Thank's a lot. Greetings RR -
Django filter in other model without foreign key
I have two different models: class AggUii(Model): year = models.IntegerField(blank=True, null=True) month = models.CharField(max_length=2, blank=True, null=True) country = models.CharField(max_length=7, blank=True, null=True) service = models.CharField(max_length=16, blank=True, null=True) doc_id = models.CharField(max_length=100, blank=True, null=True) counts = models.IntegerField(blank=True, null=True) data_type = models.CharField(max_length=200, blank=True, null=True) section_type = models.CharField(max_length=200, blank=True, null=True) yop = models.CharField(db_column='YOP', max_length=4, blank=True, null=True) # Field name made lowercase. class Meta: managed = False db_table = 'agg_uii' class HierarchieIndexDocid(Model): ancestor = models.CharField(max_length=255) descendant_docid = models.CharField(max_length=255, blank=True, null=True) class Meta: managed = False db_table = 'hierarchie_index_docid' As you can see, these tables aren't connected by a Foreign Key. Is there any way, I can rebuild this MySQL statement in Django ORM? The meta_id is passed as a parameter. SELECT agg_uii.year, SUM(agg_uii.counts) FROM agg_uii,hierarchie_index_doc_id WHERE (agg_uii.doc_id=hierarchie_index_doc_id.descendant_docid and hierarchie_index_docid.ancestor="meta_id") GROUP BY agg_uii.year; Thank you! -
Getting errors in installing redux-devtools-extension in react project
I am getting errors while installing redux-devtools-extension uisng npm command in react-redux-django project. -
Prefetch related n+1 problem with django. How can i solve it?
I have three Models named 'Route', 'Place', 'PlaceImage'. class Route(models.Model): place = models.ForeignKey(Place, on_delete=models.CASCADE, null=False, blank=False) day = models.IntegerField(null=False, blank=False) order = models.IntegerField(null=False, blank=False) class Place(models.Model): name = models.CharField(null=False, blank=False) class PlaceImage(models.Model): place = models.ForeignKey(Place, on_delete=models.CASCADE, null=False, blank=False) image = models.ImageField(null=False, blank=False) I want to display routes and place image based on Route Model. Original code was... # views.py response_obj = (Route.objects.filter(day=day).prefetch_related("place__image").order_by('order')) serializer = RouteSerializer(response_obj, many=True, context={'request': request}) # Part of RouteSerializer in serializers.py placeImage = serializers.SerializerMethodField("get_placeImage_prefetch_related") def get_placeImage_prefetch_related(self, group): request = self.context.get('request') image = group.place.image return request.build_absolute_uri(image.first().image.url) And I have N+1 Query at getting place image like this (0.000) SELECT "PLACE_IMAGE"."id", "PLACE_IMAGE"."place_id", "PLACE_IMAGE"."image", "PLACE_IMAGE"."created_at" FROM "PLACE_IMAGE" WHERE "PLACE_IMAGE"."place_id" = 80 ORDER BY "PLACE_IMAGE"."id" ASC LIMIT 1; args=(80,); alias=default (0.000) SELECT "PLACE_IMAGE"."id", "PLACE_IMAGE"."place_id", "PLACE_IMAGE"."image", "PLACE_IMAGE"."created_at" FROM "PLACE_IMAGE" WHERE "PLACE_IMAGE"."place_id" = 79 ORDER BY "PLACE_IMAGE"."id" ASC LIMIT 1; args=(79,); alias=default (0.000) SELECT "PLACE_IMAGE"."id", "PLACE_IMAGE"."place_id", "PLACE_IMAGE"."image", "PLACE_IMAGE"."created_at" FROM "PLACE_IMAGE" WHERE "PLACE_IMAGE"."place_id" = 78 ORDER BY "PLACE_IMAGE"."id" ASC LIMIT 1; args=(78,); alias=default How can I solve this n+1 problem? In views.py, I tried prefetch_related(Prefetch('place__image', queryset=PlaceImage.objects.all().only('image'))) but error occurred. AttributeError: 'PlaceImage' object has no attribute '_add_hints' -
data transfer into sql
from django.shortcuts import render import json from .models import MyModel import os def display(request): json_file_path = os.path.join(os.path.dirname(__file__), '..', '..', './jsondata.json') try: with open(json_file_path, 'r') as f: data = json.load(f) for item in data: my_model_instance = MyModel(end_year=item['end_year'], intensity=item['intensity'], sector=item['sector'], topic=item['topic'], insight=item['insight'], url=item['url'], region=item['region'], start_year=item['start_year'], impact=item['impact'], added=item['added'], published=item['published'], country=item['country'], relevance=item['relevance'], pestle=item['pestle'], source=item['source'], title=item['title'], likelihood=item['likelihood']) my_model_instance.save() except FileNotFoundError: data = [] template_name = 'display' return render(request, template_name, {'data': data}) i am trying to transfer the data from json into sql using django -
Django join on a field that isn't the ForeignKey
I'm new to Django but I'm making a game where one of the elements is that players vote for each other. Here are the models I've set up (relevant fields only) #models.py class Game(models.Model): gamecode = ShortUUIDField(length=4, max_length=4, unique=True) phasenumber = models.IntegerField(default=1) isActive = models.BooleanField(default=True) class Player(models.Model): game = models.ForeignKey(Game, on_delete=models.CASCADE) user = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.CASCADE) isPlaying = models.BooleanField(default=True) class PlayerVote(models.Model): byplayer = models.ForeignKey(Player, on_delete=models.CASCADE) forplayer = models.ForeignKey(Player, on_delete=models.CASCADE, related_name="voteforplayer") gamephasenumber = models.IntegerField() timestamp = models.DateTimeField(auto_now_add=True) When a user joins a game, they get an entry in the "Player" model and when they cast a vote for another player, an entry is added to the "PlayerVote" model showing which player voted (byplayer) and who they voted for (forplayer). What I'd like to do is create a QuerySet which contains each player and how many votes they got. I have tried using annotate which seems to be able to give me a count of the number of votes, but it defaults to joining on the byplayer field, so I end up with the number of votes each player cast, rather than the number of votes each player received. In SQL I would just do a join on Player.pk = PlayerVote.forplayer.pk, is it … -
integrate google oauth for gmail login/ signup system
I am designing an application to be accessible on both app and web. I want my customers to login/ signup via gmail as well. for this I need to integrate google auth system for social logins. My end goal is to establish a connection with google and extract user data such as name, profile_pic, dob, sub from that. I followed the below approach for my app and it worked. from google.oauth2 import id_token from google.auth.transport import requests id_info = id_token.verify_oauth2_token(token, requests.Request(), google_client_id) print(id_info['sub'], id_info['email']) this works fine for app and gives me all user data. Now, when i try to do this for web, from all the ways i could find, I tried with google API calls as below in web, we get code in callback API request from google as a request param. We have to fetch an auth token from google in exchange of this code and then use that token to fetch user data. (That's how it works, as per my understanding) data = { 'code': code, 'client_id': my_client_id, 'client_secret': my_client_secret_key, 'redirect_uri': redirect_uri, 'grant_type': 'authorization_code' } response = requests.post('https://oauth2.googleapis.com/token', data=data) if not response.ok: logger.info('Could not get access token from Google.') return access_token = response.json()['access_token'] response2 = requests.get( … -
Django Taggable tags not working, empty page
I apologize in advance if I write something unclear, I am new to both django and stackoverflow. I'm trying to implement a blog site, with posts and all that. An important part of the site is tag search, which I'm trying to implement via Taggit. However, when I click on the tag url link, I always get a blank page. I also have a pagination system that divides the blog into different pages. urlpatterns = [ path('', views.PostList.as_view(), name="home"), path(r'^$', views.post_list, name='post_list'), path(r'^tag/(?P<tag_slug>[-\w]+)/$', views.post_list, name='post_list_by_tag'), ] class Post(models.Model): title = models.CharField(max_length = 250, unique = True) slug = models.CharField(max_length = 200, unique = True) type = models.CharField(max_length=100, choices=Type_CHOICES) section = models.CharField(max_length=100, choices=Section_CHOICES) tags = TaggableManager() from django.shortcuts import render, get_object_or_404 from django.http import HttpResponse from .models import Post from django.views import generic from taggit.models import Tag from django.core.paginator import Paginator, EmptyPage, PageNotAnInteger def post_list(request, tag_slug=None): object_list = Post.objects.all() tag = None if tag_slug: tag = get_object_or_404(Tag, slug=tag_slug) object_list = object_list.filter(tags__in=[tag]) paginator = Paginator(object_list, 3) # 3 posts in each page page = request.GET.get('page') try: posts = paginator.page(page) except PageNotAnInteger: # If page is not an integer deliver the first page posts = paginator.page(1) except EmptyPage: # If page is out … -
Serving a Dash dashboard from Django hosted app to an external webpage
I am currently hosting my dashboard on a url like the following: https://xxx.herokuapp.com/dashboard/ExternalDashboard using Django and serving an HTML page with the following contents: <!DOCTYPE html> <html> <head> <title>External Dashboard</title> <style> body, html { height: 100%; margin: 0; padding: 0; } #plotly-app-container { height: 100%; } </style> </head> <body> <div id="plotly-app-container"> {% load plotly_dash %} {% plotly_app name="ExternalDashboard" ratio=1 %} </div> </body> </html> This works very well and my dash dashboard is interactable and everything is good. Now I want to serve this Dashboard on another website say https://YYY.herokuapp.com/FetchDashBoard, here I also want to send back some information such as an authentication token which i will use on my dashboard to check which plots to display. From the official dash documentation (https://dash.plotly.com/integrating-dash) on integrating dash I gather zero useful information. Im not a frontend developer and simply creating an html page on https://YYY.herokuapp.com/FetchDashBoard with the following contents just yields a blank page: <!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <title>Display Dashboard</title> </head> <body> <div id="dash-app"></div> <script> var setter = window.dash_embedded_component.renderDash( { url_base_pathname: "https://xxx.herokuapp.com/dashboard/ExternalDashboard"}, 'dash-app', sharedData ); </script> </body> </html> Bear in mind that im not sending any data to begin with, I just want to see … -
how to create user profile and save user data from data base?
I want to create a user profile, I will add that user to my own template, when a user registers, it will be registered. His profile name, username, email address will be added. As soon as he adds the post, all the posts will be added to his profile history. How to make this thing in django? I want to create a user profile, I will add that user to my own template, when a user registers, it will be registered. His profile name, username, email address will be added. As soon as he adds the post, all the posts will be added to his profile history. How to make this thing with django? -
How to allow null value on serializer when the field in the model is required?
Given the following payload, models.py, and serializers.py in Django (DRF): payload { "created_by": 6, "brand": 1, "foo_details": [ { "quantity": 123, "price_estimation": 456 }, { "quantity": 789, "price_estimation": 1011 } ] } models.py class Foo(models.Model): created_by = models.ForeignKey(CustomUser, on_delete=models.PROTECT) brand = models.ForeignKey(Brand, on_delete=models.SET_NULL, null=True) # OTHER FIELDS HERE class FooChild(models.Model): foo = models.ForeignKey(Foo, on_delete=models.CASCADE, related_name="foo_details") quantity = models.PositiveIntegerField(default=0) price_estimation = models.PositiveIntegerField(default=0) # OTHER FIELDS HERE serializers.py class FooChildSerializer(serializers.ModelSerializer): # foo = serializers.PrimaryKeyRelatedField(read_only=True, required=False) -> LINE 2 class Meta: model = FooChild fields = ["id", "foo", "quantity", "price_estimation", ...] class FooSerializer(serializers.ModelSerializer): # foo_details = FooChildSerializer(many=True) -> LINE 9 # foo_details = serializers.DictField(child=serializers.CharField(), many=True) -> LINE 10 class Meta: model = Foo fields = ["id", "created_by", "brand", "foo_details", ...] def create(self, validated_data): # I want to save the payload to `Foo` and `FooChild` inside this function at the same time, below is my unsuccessful attempt # print(validated_data) # validated_data.pop("foo_details") # foo = Foo.objects.create(**validated_data) -> LINE 21 # foo_child = FooChild.objects.create(foo=foo) # return foo The problem I'm having right now is, when I tried to POST the payload, DRF complained that foo field in FooChild is required, which is understandable, the problem is, the id of the Foo exists only after I created … -
what is the different between migrate and makemigrations?
What is the difference between the migrate and makemigrations ? I want to know different between both and why we have to both in django. after changing model.py file and that affect database then we have to run this two command py manage.py makemigrations user py manage.py migrate -
How to combine queries in django that span foreign key relationships?
Suppose I have two models: class Team(models.Model): name = models.CharField() class Player(models.Model): name = models.CharField() team = models.ForeignKey(Team) Now, I want to filter Player objects through their name as well as the name of their team. So for example if user input is aa, I want all Players who have aa in their name OR in their team's name. So far I have tried to use two queries like this: players = Player.objects.filter( name__icontains=request.GET.get("q", ""), # ...other filters ) more = Player.objects.filter( team__name__icontains=request.GET.get("q", ""), # ...other filters ) players = players.union(more) This gives the results, but it has its own problems: i) It gives duplicate results in cases where the search query matches both, the player name and the team name (.union method does not support .distinct) ii) It searches the database twice which can be an expensive operation. So I would like it to run in just one query. iii) It is not DRY. You have to repeat the other filters twice. So is there a way to get the results accurately? -
Django multi tenant help required
I am currently building saas app using django_multitenant package and i read and followed all the detail given in the docs and while using Django admin panel everything is fine. If we create any object from panel the object automatically get tenant assigned to it but while using an API and It kept asking the tenant id how to solve it. # setting MIDDLEWARE = [ "corsheaders.middleware.CorsMiddleware", "django.middleware.security.SecurityMiddleware", "django.contrib.sessions.middleware.SessionMiddleware", "django.middleware.common.CommonMiddleware", "django.middleware.csrf.CsrfViewMiddleware", "django.contrib.auth.middleware.AuthenticationMiddleware", "django.contrib.messages.middleware.MessageMiddleware", "django.middleware.clickjacking.XFrameOptionsMiddleware", "apps.api_auth.middlewares.MultitenantMiddleware", # 'django_multitenant.middlewares.MultitenantMiddleware', ] # custom middleware class MultitenantMiddleware: def __init__(self, get_response): self.get_response = get_response def __call__(self, request): jwt_auth = JWTAuthentication() # Authenticate the user auth_result = jwt_auth.authenticate(request) if auth_result is not None: user, _ = auth_result if user and not user.is_anonymous: tenant = Institute.objects.filter(user=user).first() set_current_tenant(tenant) response = self.get_response(request) unset_current_tenant() return response # models class Institute(TenantModel): name = models.CharField(max_length=100) class TenantMeta: tenant_field_name = "id" class CustomUserManager(TenantManagerMixin, UserManager): pass class User(TenantModel, AbstractUser): institute = TenantForeignKey( "tenant.institute", on_delete=models.CASCADE, blank=True, null=True ) objects = CustomUserManager() class TenantMeta: tenant_field_name = "institute_id" class SessionYear(TenantModel): start_year = models.DateField() end_year = models.DateField() is_deleted = models.BooleanField(default=False) is_active = models.BooleanField(default=False) institute = TenantForeignKey("tenant.institute", on_delete=models.CASCADE) class TenantMeta: tenant_field_name = "institute_id" # API view from django_multitenant import views from rest_framework import viewsets, permissions from apps.tenant import tenant_func … -
nginx + uwsgi upstream prematurely closed connection while reading response header from upstream
I'm using uwsgi and nginx to deploy a Django project which using VUE3 and Django. And nginx is in a docker container.I have tried several conf combinations, only the follow one works. location /cseq/ { root /usr/share/nginx/html; #try_files $uri $uri/ /cseq/index.html; index index.html index.htm; } location /cseq/api/ { proxy_pass http://xxx:8001; proxy_http_version 1.1; proxy_set_header Upgrade $http_upgrade; proxy_set_header Connection 'upgrade'; proxy_set_header Host $host; proxy_cache_bypass $http_upgrade; proxy_set_header X-Real-IP $remote_addr; proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for; proxy_set_header X-Forwarded-Proto $scheme; uwsgi_buffer_size 16k; uwsgi_busy_buffers_size 24k; } [uwsgi] http=:8001 chdir=/root/project/cseq/cseq-backend module=cseq.wsgi:application master=true vacuum=true max-requests=5000 workers= 4 threads = 2 buffer-size = 65536 daemonize=/root/project/cseq/cseq-backend/uwsgi.log My question is: in uwsgi conf, using http works, but change http to socket, nginx has a error:upstream prematurely closed connection while reading response header from upstream. when I change both conf to the follow location /cseq/ { root /usr/share/nginx/html; #try_files $uri $uri/ /cseq/index.html; index index.html index.htm; } location /cseq/api/ { include uwsgi_params; uwsgi_pass 127.0.0.1:8001; } [uwsgi] socket=:8001 chdir=/root/project/cseq/cseq-backend module=cseq.wsgi:application master=true vacuum=true max-requests=5000 workers= 4 threads = 2 buffer-size = 65536 daemonize=/root/project/cseq/cseq-backend/uwsgi.log the error becomes failed (111: Connection refused) while connecting to upstream, in both errors, uwsgi didn't has any connection. Any ideas or solutions? I want to use nginx and uwsgi to deploy a Django project