Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Value from request.POST different than expected
I am attempting to pass a list as part of a data parameter in a AJAX call. The call itself seems to be working fine in Javascript, but accessing the QueryDict object in Python returns a single integer, 17, rather than a list, [17]. Could this have anything to do with Javascript interpreting strings as numbers? I don't know why else a list with a single element would convert to an integer. # models.py def mark_shipped(self, request): print(request.POST) orders = request.POST['orders'] print(orders) for pk in orders: try: order = Sale.objects.get(pk=pk) except ObjectDoesNotExist: print(pk) return False order.shipped = True order.date_shipped = timezone.now() order.save() self.__shipping_confirm(order.email) return True Which outputs: <QueryDict: {'csrfmiddlewaretoken': ['hc4...I2a'], 'orders': ['17']}> 17 1 Expected output: <QueryDict: {'csrfmiddlewaretoken': ['hc4...I2a'], 'orders': ['17']}> [17] -
Django: How to make a ListView which will take the parameters to build a list of questions?
The purpose of the project that I am working on is to fetch physics' questions according to what choices the user wants. The first choice is what topic the wanted questions belong to, and the other one is what type of questions, the questions belong to. However and with the help of different online sources, I have created the forms and they look great. But now I would like to get the results out of these forms, I know that I have to create a view.py for the results and make the action in my HTML files into GET. But I don't know how the view will look like. This is my views.py for the forms. from django.shortcuts import render, render_to_response from django.views.generic import CreateView from home.models import Topic, Image, Question, Answer from home.forms import QuizMultiForm def QuizView(request): if request.method == "POST": form = QuizMultiForm(request.POST) if form.is_valid(): pass else: form = QuizMultiForm() return render(request, "index.html", {'form': form}) This is html file {% extends 'base.html' %} {% block content %} <form method="GET" action="results.html"> {% csrf_token %} {{ form.as_p }} <button type="submit" id="home-Physics-time-button">It is Physics Time</button> </form> {% endblock content %} Here are my urls.py urlpatterns = [ path('admin/', admin.site.urls), path('ask/', ask_page_url, … -
Can python asyncio be used in place of celery background tasks?
I have been using celery for the past projects for asynchronous tasks, but now with the introduction of asyncio I was wondering what are the difference between the two when it comes to handling async tasks ,are there situation where one is suitable more than the other? -
Django: {% csrf_token %} keeps returning 403 Forbidden error
I have a form that I try to submit however whenever I click the submit button Django puts me into the 403 Forbidden page error. I have no clue how to fix this. Please help. This is done using materialize CSS. page.html: <form action="/present/" method="POST"> {% csrf_token %} <p> <input type="checkbox" id="completed" name="completed" /> <label for="completed">Present</label> </p> <input class="waves-effect waves-light btn" type='submit'/> </form> views.py: def present(request): completed = request.GET.get('pre') if request.POST.get('completed', '') == 'on': print("Succes!") else: print("Nope") #above coode doesn't work either for detecting whether or not the checkbox was selected. return render(request, 'main/test.html') -
"didn't return an HttpResponse object. It returned None instead" in forms.py clean_fieldname() method
Whenever I'm entering special character or any number it should give validation error message but it is showing me "didn't return HttpResponse Error." forms.py class EventCreateForm(forms.ModelForm): class Meta: model = Event fields = ['name', 'date'] def clean_name(self): name = self.cleaned_data['name'] name = re.sub(' +',' ', name) if all(x.isalpha() or x.isspace() for x in name): return name else: raise forms.ValidationError("Please use only alphabets!!!") #views.py class EventCreateView(LoginRequiredMixin, CreateView): model = Event form_class = EventCreateForm template_name = 'events/event_form.html' -
How to redirect url from middleware in Django?
How to redirect url from middleware? Infinite loop problem. I intend to redirect the user to a client registration url if the registration has not yet been completed. def check_user_active(get_response): def middleware(request): response = get_response(request) try: print(Cliente.objects.get(usuario_id=request.user.id)) except Cliente.DoesNotExist: return redirect('confirm') return response return middleware -
Can I use Django template language directly at top level of a HTML file i.e. without <HTML> or <body> tags ? Example -
{% if user.is_authenticated %} . . . (HTML code) {% else %} . . . (HTML code) {% endif %} -
Creating user profile after they sign up
I'm using Django Allauth. Users can either sign up using Google, Twitter, Facebook or they can sign up using their email address. Once signed up, their details will be stored in the User table. There's also another model I have called Profile that contains user information like bio, avatar, etc. I'd like to create a Profile for the user when they sign up. I looked at Allauth signals and found the user_signed_up signal to be appropriate. Here's how I wrote the code in my handlers.py file: @receiver(user_signed_up) def create_profile(request, user): profile = Profile(avatar='img/blah/blah.jpg', bio='Example text', gender='M', dob='2018-01-01', country='US', user=user) profile.save() I added random stuff just so I can see if it's being created or not, but for some reason when the user signs up their profile is not being created. What am I doing wrong? -
How does routers and viewsets configure their urls?
I was reading through a long piece of code. And was stuck at how routers and viewsets automatically configure their URLs. For eg. the views.py file is: class UserViewSet(viewsets.ModelViewSet): authentication_classes = (BasicAuthentication,SessionAuthentication) permission_classes = (IsAuthenticated,) serializer_class = UserSerializer queryset = User.objects.all() The corresponding urls with router is: router = DefaultRouter() router.register(r'users',views.UserViewSet,basename='user') urlpatterns = router.urls In the above case, what will be the respective urls for the different actions in viewsets, ie list, create, retrieve, update, partial_update and destroy as mentioned in the djangorestframework documentation on viewsets: http://www.tomchristie.com/rest-framework-2-docs/api-guide/viewsets -
Content from two columms doesn't show as expected Django and Bootstrap 4
I'm currently building a blog+portfolio with Django and Bootstrap 4. The problem is when I try to show two columns, Articles next to my Profile. Both columns are in a HTML table, but for some reason they do not show correctly. Eg. How it looks like using HTML,Css, and Bootstrap Here is how it looks when I insert everything on my Base_layout.html How it looks like when it is inserted in my django Base_layout.html Here is my Base_layout, which has the code inside the table to show the articles of the blog ({% load bootstrap4 %} {% load static from staticfiles %} are included in the top of the document): <div class="container"> <div class="row"> <!-- Blog Entries Column --> <div class="col-md-8"> <div class="card mb-4" class="article-detail"> {% block content %} {% endblock %} </div> </div> <!-- Pagination --> <ul class="pagination justify-content-center mb-4"> <li class="page-item"> <a class="page-link" href="#">&larr; Older</a> </li> <li class="page-item disabled"> <a class="page-link" href="#">Newer &rarr;</a> </li> </ul> </div> <!-- Sidebar Widgets Column --> <div class="col-md-4"> <div class="card" style="width: 18rem;"> <img src="{% static 'profile.jpg' %}" class="rounded-circle card-img-top" alt=""> <div class="card-body"> <h5 class="card-title">Leandro Fraisinet</h5> <p class="card-text">Some quick example text to build on the card title and make up the bulk of the … -
Gunicorn: Access logs to a file instead of Stndout
I am using Digitalocean one click Django server deployment using below version of Python, Django and Gunicorn. gunicorn (version 19.7.1) python 2.7 I can't seem to figure out how to log my access logs into a file. Below is my gunicorn.service file. [Unit] Description=Gunicorn daemon for Django Project Before=nginx.service After=network.target [Service] WorkingDirectory=/home/django/egre ExecStart=/usr/bin/gunicorn --name=egre --pythonpath=/home/django/egre --bind unix:/home/django/gunicorn.socket --config /etc/gunicorn.d/gunicorn.py --access-logfile /var/log/emperor.log eGRE.wsgi:application Restart=always SyslogIdentifier=gunicorn User=django Group=django [Install] WantedBy=multi-user.target https://docs.gunicorn.org/en/19.7.1/settings.html#logging After following the above documentation I tried using --access-logfile=- which works but does not log my stndout to a file after passing a relative path the gunicorn does not restart giving an exit-code 1. How to write logs to emperor.log? -
Django: How can I show up the name of the choices instead of the integers?
I have had several problems while making this website and this is the newest one. I have created these choices fields, however, only the numbers are showing up in the first one, where in the second one and because the question_type is linked to the Question table, the questions that I add into the database are showing up instead of the quesiton type, where there are only two questions' types that are supposed to show up. And depending on the choice made by the user, a new page that is only for reading will show up with the questions that belong to this specific topic with the specific type of questions. This is the models.py from django.db import models from home.choices import * # Create your models here. class Topic(models.Model): topic_name = models.IntegerField( choices = question_topic_name_choices, default = 1) def __str__(self): return '%s' % self.topic_name class Image (models.Model): image_file = models.ImageField() def __str__(self): return '%s' % self.image_file class Question(models.Model): questions_type = models. IntegerField( choices = questions_type_choices, default = 1) question_topic = models.ForeignKey( 'Topic', on_delete=models.CASCADE, blank=True, null=True) question_description = models.TextField() question_answer = models.ForeignKey( 'Answer', on_delete=models.CASCADE, blank=True, null=True) question_image = models.ForeignKey( 'Image', on_delete=models.CASCADE, blank=True, null=True) def __str__(self): return '%s' % self.question_type class … -
Why does Apache constantly shows wsgi error in error log even though there is no apparent error accessing the website
I am running a website writen in django 11.6. Though there is no apparent errors, Apache 2 constantly spills out wsgi error: [Tue Feb 05 02:50:57.413059 2019] [wsgi:error] [pid 36444:tid 139983401850624] [remote 127.0.0.1:58626] /orchid/species/?type=species&genus=Baskervilla [Tue Feb 05 02:51:00.107167 2019] [wsgi:error] [pid 36443:tid 139983334708992] [remote 127.0.0.1:58740] /orchid/species/?type=species&genus=Baskervilla [Tue Feb 05 02:51:06.626110 2019] [wsgi:error] [pid 36443:tid 139983243437824] [remote 127.0.0.1:59052] /orchid/species/?type=species&genus=Baskervilla [Tue Feb 05 02:51:12.026706 2019] [wsgi:error] [pid 36443:tid 139983243437824] [remote 127.0.0.1:59310] /orchid/species/?type=species&genus=Baskervilla [Tue Feb 05 02:51:14.600444 2019] [wsgi:error] [pid 36444:tid 139983401850624] [remote 127.0.0.1:59442] /orchid/species/?type=species&genus=Baskervilla I am at a lost where to start. Any hint would be greatly appreciated. -
GeoJson is rendered correctly but without the requested color
I have the following method "ajax_geojson" that produces the geo json: geo_json = [ {"type": "Feature", "properties": { "id": c_name, "marker-color": "#f80530", "marker-size": "medium", "marker-symbol": "", "popupContent": content , }, "geometry": { "type": "Point", "coordinates": [lon, lat] }} for c_name,content, lon,lat in zip(country_name, content, longtitude, latitude) ] return JsonResponse(geo_json, safe=False) the javascript renders this with a jQuery: $.ajax({ url: '/research/ajax_geojson', success: function (collection) { L.geoJson(collection, {onEachFeature: onEachFeature}).addTo(map); function onEachFeature(feature, layer) { if (feature.properties && feature.properties.popupContent) { layer.bindPopup(feature.properties.popupContent); } } } }); While the markers are shown on the map precisely as requested, the color doesn't seem to take any effect (#f80530 is red) My question: is there anything I need to add to the javascript under the layer.bindPopup? I was under the impression that defining the color in the geo_json should present itself in the map. What am I missing here? -
How to trim a video before serving it up on the front end
I have been trying to search for the code or an app to help crop a video in django. so far, i have been searching for a code to help crop a video before serving it up on the front end, however i haven't found any. please if any one can help. -
object not saving to cart in django
I am trying to add object to cart but nothing is added. I'm pretty new to Django any help is appreciated. Also I think the error has to do with my cart_update function. In the tutorial this is how I wrote but when I was looking up this issue I found out I should be using get_object_or_404. When I tried that way I was still unsuccessful with adding objects to the cart. models.py from django.db import models import os import random from django.db.models import Q from django.db.models.signals import pre_save, post_save from django.urls import reverse from django.shortcuts import get_object_or_404 from .utils import unique_slug_generator def get_filename_ext(filepath): base_name = os.path.basename(filepath) name, ext = os.path.splitext(base_name) return name, ext def upload_image_path(instance, filename): new_filename = random.randint(1,233434234) name, ext = get_filename_ext(filename) final_filename = '{new_filename}{ext}'.format(new_filename=new_filename, ext=ext) return "products/{new_filename}/{final_filename}".format(new_filename=new_filename, final_filename=final_filename) class ProductQuerySet(models.query.QuerySet): def active(self): return self.filter(active=True) def featured(self): return self.filter(featured=True, active=True) def search(self,query): lookups = (Q(title__icontains=query) | Q(description__icontains=query) | Q(price__icontains=query) | Q(tag__title__icontains=query) ) return self.filter(lookups).distinct() class ProductManager(models.Manager): def get_queryset(self): return ProductQuerySet(self.model, using=self._db) def all(self): return self.get_queryset().active() def featured(self): return self.get_queryset().featured() def get_by_id(self,id): qs = self.get.queryset().filter(id=id) if qs.count() == 1: return qs.first() return None def search(self,query): return self.get_queryset().active().search(query) class Product(models.Model): title = models.CharField(max_length=120) slug = models.SlugField(blank=True,unique=True) description = models.TextField() price … -
Why am I getting errors during the initial migration when using django-allauth?
I get errors during my initial database migration based on the models defined by django-allauth. I don't have any other models defined, and therefore I have no migration files in my django project. Django==2.1.5 django-allauth==0.38.0 django-pyodbc-azure==2.1.0.0 Python 3.6.7 MS SQL Server 16 Build Version 13.0.4474.0 (March 2018) This worked fine when I was using SQLite > python manage.py showmigrations account [ ] 0001_initial [ ] 0002_email_max_length admin [ ] 0001_initial [ ] 0002_logentry_remove_auto_add [ ] 0003_logentry_add_action_flag_choices auth [ ] 0001_initial [ ] 0002_alter_permission_name_max_length [ ] 0003_alter_user_email_max_length [ ] 0004_alter_user_username_opts [ ] 0005_alter_user_last_login_null [ ] 0006_require_contenttypes_0002 [ ] 0007_alter_validators_add_error_messages [ ] 0008_alter_user_username_max_length [ ] 0009_alter_user_last_name_max_length contenttypes [ ] 0001_initial [ ] 0002_remove_content_type_name sessions [ ] 0001_initial sites [ ] 0001_initial [ ] 0002_alter_domain_unique socialaccount [ ] 0001_initial [ ] 0002_token_max_lengths [ ] 0003_extra_data_default_dict > python manage.py makemigrations No changes detected > python manage.py migrate Operations to perform: Apply all migrations: account, admin, auth, contenttypes, sessions, sites, socialaccount Running migrations: Applying account.0001_initial...Traceback (most recent call last): File "/home/testuser/envs/venv367/lib/python3.6/site-packages/django/db/backends/utils.py", line 85, in _execute return self.cursor.execute(sql, params) File "/home/testuser/envs/venv367/lib/python3.6/site-packages/sql_server/pyodbc/base.py", line 546, in execute return self.cursor.execute(sql, params) pyodbc.ProgrammingError: ('42000', "[42000] [Microsoft][ODBC Driver 17 for SQL Server][SQL Server]Foreign key 'account_emailaddress_user_id_2c513194_fk_users_customuser_id' references invalid table 'users_customuser'. (1767) (SQLExecDirectW)") … -
Looking for some help on Django authentication with Angular login page
I have an angular login page that sends an Ajax request to my django server (listening on a separate port from the angular application), and I am able to log my user in but a session cookie is not getting returned in the response for the client to store in the angular app. Here is what my backend settings.py looks like the for authentication specific stuff: MIDDLEWARE = [ 'django.middleware.security.SecurityMiddleware', 'django.contrib.sessions.middleware.SessionMiddleware', 'corsheaders.middleware.CorsMiddleware', 'django.middleware.common.CommonMiddleware', 'django.middleware.csrf.CsrfViewMiddleware', 'django.contrib.auth.middleware.AuthenticationMiddleware', 'django.contrib.messages.middleware.MessageMiddleware', 'django.middleware.clickjacking.XFrameOptionsMiddleware',] # Here are the session specific settings SESSION_ENGINE = 'django.contrib.sessions.backends.signed_cookies' SESSION_COOKIE_HTTPONLY = True SESSION_COOKIE_AGE = 1800 # The age of session cookies, in seconds CORS_ORIGIN_ALLOW_ALL = True And here is my login view function that is hooked up to my login path: @csrf_exempt @require_POST def login_view(request: HttpRequest): payload = request.body.decode() body = json.loads(payload) username = body['username'] password = body['password'] user = authenticate(request, username=username, password=password) if user is not None: login(request, user)# Log the user in return HttpResponse('Success') else: return HttpResponseBadRequest() I am trying to used cookie/ session based authentication so that if the user closes the page and relaunches it before the session time has expired, it will direct them back to the landing page, and for a specific input select field only … -
How do I combine multiples columns of data into their respective rows using Python
I having multiple lists that represent a column of data. I need to convert the column data into rows. My approach to this problem has been attempting to iterate over each column and appending the appropriate items to a separate list. The data is structured in this way: columns = [[column1], [column2], ... ] My goal is to create something like: row = [column1[1], column2[1], ...] I can't quite figure out how to iterate over each column at the same time, grabbing the same index of each list. -
Changing Font in input field with underline under each character
I want to create a complete text in Django. The gaps should show how many letters are missing. For example: This is an example. I will sh_ _ you what i me_ _. I found some usefull css-snippet on codepen. I tried to play around with it and use letters instead of numbers and change the font to Segoe UI. The problem i have is that the underlines are not synchronized with the letters anymore when i use Segoe UI. How do i have to change the configurations so it can fit well again? My SCSS code: $char-w: 1ch; $gap: .5*$char-w; $n-char: 7; $in-w: $n-char*($char-w + $gap); input { display: block; margin: 2em auto; border: none; padding: 0; width: $in-w; background: repeating-linear-gradient(90deg, dimgrey 0, dimgrey $char-w, transparent 0, transparent $char-w + $gap) 0 100%/ #{$in-w - $gap} 2px no-repeat; font: 5ch Segoe UI; /*That's the attribute i changed*/ letter-spacing: $gap; &:focus { outline: none; color: dodgerblue; } } my HTML code: <input maxlength='7' value=''/> -
How to delete a record from user instance
I created a delete function to remove a specific "goal" record from a user. The delete function currently deletes all "goal" records assoicated with a user. I would like the function to delete a specific goal record for a user depending on the html delete button that is pressed. HTML <div class="col-md-6 outer"> <div class="box"> <div class="words"> <div> <p class="ins">{{ goals.0.instrument }}</p> <p class="date">{{ goals.0.goal_date }}</p> </div> <div> <br /> <br /> <p>{{ goals.0.goal_info }}</p> </div> <form action="{% url 'student:goal_progress' %}" method="POST"> {% csrf_token %} <div class="buttons"> <button type="submit" name="submit" class="btn white_button box_button">Delete</button> </div> </form> </div> </div> </div> <div class="col-md-6 outer"> <div class="box"> <div class="words"> <div> <p class="ins">{{ goals.1.instrument }}</p> <p class="date">{{ goals.1.goal_date }}</p> </div> <div> <br /> <br /> <p>{{ goals.1.goal_info }}</p> </div> <form action="{% url 'student:goal_progress' %}" method="POST"> {% csrf_token %} <div class="buttons"> <button type="submit" name="submit" class="btn white_button box_button">Delete</button> </div> </form> </div> </div> </div> views.py @login_required def goal_progress(request): goals = Goal.objects.filter(user=request.user) form = GoalForm() if request.method == 'POST': form = GoalForm(request.POST) goals.user = request.user goals.delete() return redirect('/student/dashboard') else: form = GoalForm() form = GoalForm() context = {'form' : form, 'goals' : goals} return render(request, 'student/goal_progress.html', context) -
Date input returns blank to django when filled in with datepicker
I have an input field with datepicker: <div class="col-md-6 col-lg-4"> <label for="fromDate">From Date* (MM/DD/YYYY)</label> <div class="input-group date" id="from-datepicker" data-date="" data-date-format="mm/dd/yyyy"> <input class="form-control datepicker" type="text" id="fromDate" name="fromDate" v-model="fromDate" @keydown.enter.prevent="validDate"> <span class="input-group-addon add-on"><i class="fa fa-calendar"></i></span> </div> </div> <div class="col-md-6 col-lg-4"> <label for="toDate">To Date* (MM/DD/YYYY)</label> <div class="input-group date" id="to-datepicker" data-date="" data-date-format="mm/dd/yyyy"> <input class="form-control datepicker" type="text" id="toDate" name="toDate" v-model="toDate" @keydown.enter.prevent="validDate"> <span class="input-group-addon add-on"><i class="fa fa-calendar"></i></span> </div> </div> There's a javascript function that passes it to the django views. I can't show you anything else due to all the rest being incredibly complicated. For some reason, trying to submit will raise an error in javascript because it apparently considers it a blank input if filled in with datepicker. Typing it in normally will work for some reason. I know I'm not detailed, but does anyone have any idea on what's happening? Thanks. -
Django: Get all the parent data based on a field in both parent and foreign key model
I have these two models: class Post(models.Model): user = models.TextField() name = models.TextField(max_length=1024) created = models.DateTimeField(False) class Meta: ordering = ['-created'] def save(self, *args, **kwargs): if not self.id: self.created = timezone.now() return super(Post, self).save(*args, **kwargs) and class PostShared(models.Model): post = models.ForeignKey(Post, related_name='postshared', on_delete=models.CASCADE) is_accepted = models.BooleanField(default=False) shared_to = models.TextField(max_length=50) shared_by = models.TextField(max_length=50) A post can be shared by a user to any number of users. Now given a user's name, I would like to get the Post details of all the Posts that a given user might have created or Posts that were shared to him/her. I tried Post.objects.filter(postshared__isnull=False,postshared__shared_to='user1',user='user1') But I am only getting the Posts that have been shared to the user and not the Posts created by the user. -
Reverse for 'shop.product_detail' not found. 'shop.product_detail' is not a valid view function or pattern name. DJANGO 2.1
I cant see were i made a mistake, I tried almost everthing. Even checked stackoverflow but I cant find mistake... Please can you detect were I went wrong? This is Printscreen of an error : http://prntscr.com/mgnfyz shop/views.py : from django.shortcuts import render, get_list_or_404 from .models import Category, Product def product_list(request, category_slug=None): category = None categories = Category.objects.all() products = Product.objects.filter(available=True) if category_slug: category = get_list_or_404(Category, slug=category_slug) products = Product.objects.filter(category=category) context = { 'category': category, 'categories': categories, 'products': products } return render(request, 'shop/list.html', context) def product_detail(request, id, slug): product = get_list_or_404(Product, id=id, slug=slug, available=True) context = { 'product': product } render(request, 'shop/detail.html', context) urls.py in shop app : from django.urls import path from . import views app_name = 'shop' urlpatterns = [ path('', views.product_list, name='product-list'), path('<category_slug>/', views.product_list, name='product_list_by-category'), path('<slug>/', views.product_detail, name='product-detail'), ] base.html in shop app within templates and then shop folder agian : <!DOCTYPE html> {% load staticfiles %} <html lang="en"> <head> <meta charset="UTF-8"> <title>{% block title %}On-line Shop{% endblock %}</title> <link rel="stylesheet" href="{% static 'css/bootstrap.min.css' %}"> <link rel="stylesheet" href="{% static 'css/styles.css' %}"> </head> <body> {% include 'shop/navbar.html' %} {% block content %} {% endblock %} <script src="{% static 'js/jquery.min.js' %}" type="text/javascript"></script> <script src="{% static 'js/bootstrap.min.js' %}" type="text/javascript"></script> </body> </html> … -
With using login(request, user) function with a database other than default - Django?
With using login(request, user) function with a database other than default - Django? Is there any possibility settings.DATABASES is improperly configured. Please supply the ENGINE value. Check settings documentation for more details. DATABASES = { 'default':{}, 'mw': { 'ENGINE': 'django.db.backends.postgresql', 'NAME': '01_sistema', 'USER': 'root', 'PASSWORD': 'root', 'HOST': 'localhost', 'PORT': '5432', } } I created a route and it works perfectly with queries. but with the function login(request, user) does not work. class TenantRouter(object): def db_for_read(self, model, **hints): return get_thread_local('using_db', 'default') def db_for_write(self, model, **hints): return get_thread_local('using_db', 'default') def allow_relation(self, obj1, obj2, **hints): return True def allow_migrate(self, db, app_label, model_name=None, **hints): return True Middliware def Multidb(get_response): def middleware(request): try: usuario = request.user empresa = usuario.empresa print('0') except: empresa = request.GET['empresa'] print('1') @thread_local(using_db=empresa) def execute_request(request): return get_response(request) response = execute_request(request) return response return middleware The whole problem is that the login section is not registered because of the error in the login(request, user) thank you all for your attention.