Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
mysql.connector imports through the python shell, but still throws error in python module
I have a simple python module test.py. Its content is: import mysql.connector When I run it, it gives this error: C:\xxx\Software\Website\django\Scripts\python.exe C:\xxx\Software\Website\django\MyDB\test.py Traceback (most recent call last): File "C:\xxx\Software\Website\django\MyDB\test.py", line 1, in <module> import mysql.connector ModuleNotFoundError: No module named 'mysql' Process finished with exit code 1 So it can't find mysql.connector. But when I go into the python shell (launched from the directory of test.py), running >>> import mysql.connector doesn't give any error. So the mysql.connector package must be installed, somewhere. How come running the python module gives an error, while running the same python instruction through the python shell doesn't? -
How to calculate current day streak in Django?
I would like to calculate every time a ClassAttempt with a status "completed" is created or updated. class ClassAttempt(models.Model): user = models.ForeignKey(to=User,on_delete= models.PROTECT, null=True) related_class = models.ForeignKey(to=Class, related_name='attempt', on_delete= models.PROTECT, null=True) collected_xp = models.IntegerField(null=True, blank=True, default=0) status = models.CharField( verbose_name='status', max_length=20, choices=( ('no-completed', 'no-completed'), ('completed', 'completed'), ), default='no-completed' ) created_at = models.DateTimeField(auto_now_add=True) updated_at = models.DateTimeField(auto_now=True) -
How to set default user password when creating users in Django?
I'm creating my first programming project with Django as part of the IB Computer Science course and I decided to make a platform where students can access their grades. I want admins to be able to create new students, with a default password that students can reset later on. After trying to researching it and read the Django docs, I found out that I have to make use of Django's AbstractBaseUser. However, after trying to watch multiple tutorials which did not answer my question, I am now stuck. Is there a way to implement this function? -
Django: Why I can't access extra fields in Many to Many relationship with _set.all in templates. What is wrong?
I want to access the extra field is_valid of Class GroupMember (ManytoMany relation with Class Group). In templates I do: {% for field in user.groupmember_set.all %}{{ field.is_valid }}<br>{% endfor %} But nothing is shown. Where is the problem? The relevant code is below models.py from django.contrib.auth.models import User class Group(models.Model): name = models.CharField(max_length=255, unique=True) members = models.ManyToManyField(User,through="GroupMember") def __str__(self): return self.name class GroupMember(models.Model): user = models.ForeignKey(User,related_name='user_groups',on_delete=models.CASCADE,) group = models.ForeignKey(Group, related_name="memberships",on_delete=models.CASCADE,) is_valid = models.BooleanField(default=False) def __str__(self): return self.user.username class Meta: unique_together = ("group", "user") views.py class SingleGroup(DetailView): model = Group urls.py path("groups/<pk>/",views.SingleGroup.as_view(),name="single"), template: groups/<pk> {% for field in user.groupmember_set.all %}{{ field.is_valid }}<br>{% endfor %} -
I am getting a "error": "invalid_client" on social_oauth2. When i try to get the tokens through. I am trying the tokens for DjangoOauth
I have attached the requirements.txt. I am unable to get the token even after changing versions of djangorestframework etc. Please help. I have been trying different things for 3 days. [![```appdirs==1.4.4 asgiref==3.2.10 astroid==2.4.2 autopep8==1.5.4 boto3==1.14.31 botocore==1.17.31 cachelib==0.1 certifi==2020.4.5.1 cffi==1.15.1 chardet==3.0.4 click==7.1.2 colorama==0.4.4 cryptography==38.0.1 cs50==5.0.4 defusedxml==0.7.1 Deprecated==1.2.13 distlib==0.3.1 Django==3.1.4 django-ckeditor==5.9.0 django-cors-headers==3.5.0 django-crispy-forms==1.9.2 django-filter==2.3.0 django-js-asset==1.2.2 django-oauth-toolkit==2.2.0 django-storages==1.9.1 djangorestframework==3.11.1 docutils==0.15.2 drf-social-oauth2==1.0.8 filelock==3.0.12 Flask==1.1.2 Flask-Session==0.3.2 gunicorn==20.0.4 idna==2.9 install==1.3.3 isort==5.6.4 itsdangerous==1.1.0 Jinja2==2.11.2 jmespath==0.10.0 jwcrypto==1.4.2 lazy-object-proxy==1.4.3 MarkupSafe==1.1.1 mccabe==0.6.1 oauthlib==3.2.2 Pillow==9.2.0 psycopg2-binary==2.9.4 pycodestyle==2.6.0 pycparser==2.21 PyJWT==2.5.0 pylint==2.6.0 python-dateutil==2.8.1 python-dotenv==0.13.0 python3-openid==3.2.0 pytz==2020.1 requests==2.23.0 requests-oauthlib==1.3.1 s3transfer==0.3.3 six==1.15.0 social-auth-app-django==5.0.0 social-auth-core==4.3.0 SQLAlchemy==1.3.17 sqlparse==0.3.1 termcolor==1.1.0 toml==0.10.2 tzdata==2022.5 urllib3==1.25.9 virtualenv==20.2.1 Werkzeug==0.15.4 whitenoise==5.1.0 wrapt==1.12.1 [1]: https://i.stack.imgur.com/wUmdy.png -
How to handle IntegrityError unique constraint correctly in Django 3.2
Hello i stacked with that simple thing. I need validation with two fields in model their combination must be unique. These is work almost as want, but after i try to add a new combination it raise IntegrityError instead validation error in my form. Any workaround to handle it? #Model(is not all field but it not Necessary in my question): class AggSubnet(models.Model): region = models.ForeignKey("db_info.Region", on_delete=models.PROTECT, related_name='get_agg_by_region') subnet_ip = models.GenericIPAddressField() class Meta: constraints = [ models.UniqueConstraint(fields=['subnet_ip','region'], condition=~Q(subnet_ip__startswith='172.'), name='agg_subnet_unique'), ] def __str__(self): return f'{self.region} {self.subnet_ip}/{self.subnet_prefix}' def get_absolute_url(self): return reverse(f'{self.__class__.__name__}{DETAIL_SUFFIX}', kwargs={"pk": self.pk}) #View: class AggregateSubnetCreateView(LoginRequiredMixin, SuccessMessageMixin, CreateView): model = AggregateSubnet template_name = 'Subnet_create.html' fields = ('region', 'subnet_ip') success_message = "%(subnet_ip)s was created successfully" def form_valid(self, form): form.instance.created_by = self.request.user form.instance.updated_by = self.request.user return super().form_valid(form) #Template I mean how i can replace: enter image description here to something like this: enter image description here -
Django Send_mail not working in production
I have the current set up and emails are pushed locally fine but it doens't in production. It is a django, docker, dokku and nginx setup hosted on a VPS. Locally I run it in docker with docker compose up and in production also with the same dockerfile. This is all the info that i thought was useful does anyone know what i have to do? settings.py ... EMAIL_BACKEND = "django.core.mail.backends.smtp.EmailBackend" EMAIL_USE_TLS = True EMAIL_HOST_USER = os.environ.get("Email_Username", "") EMAIL_HOST_PASSWORD = os.environ.get("Email_Password", "") EMAIL_HOST = os.environ.get("Email_Host", "mail.domain.nl") EMAIL_PORT = os.environ.get("Email_Port", 587) ... actions.py def sendRegisterMail(modeladmin, request, queryset): for lid in queryset: print("email sending") achievements = '...' subject = "..." message = f""" ... """ send_mail( subject, message, settings.EMAIL_HOST_USER, [lid.email], fail_silently=True, ) print("email sent") dokku nginx:show-config app server { listen [::]:80; listen 80; server_name app.dispuutstropdas.nl; access_log /var/log/nginx/app-access.log; error_log /var/log/nginx/app-error.log; include /home/dokku/app/nginx.conf.d/*.conf; location / { return 301 https://$host:443$request_uri; } } server { listen [::]:443 ssl http2; listen 443 ssl http2; server_name app.dispuutstropdas.nl; access_log /var/log/nginx/app-access.log; error_log /var/log/nginx/app-error.log; ssl_certificate /home/dokku/app/tls/server.crt; ssl_certificate_key /home/dokku/app/tls/server.key; ssl_protocols TLSv1.2 TLSv1.3; ssl_prefer_server_ciphers off; keepalive_timeout 70; location / { gzip on; gzip_min_length 1100; gzip_buffers 4 32k; gzip_types text/css text/javascript text/xml text/plain text/x-component application/javascript application/x-javascript application/json application/xml application/rss+xml font/truetype application/x-font-ttf font/opentype application/vnd.ms-fontobject image/svg+xml; … -
Having venv made with powershell 5, can I safely move/upgrade my shell to powershell 7?
I have a Django project with venv made with PowerShell 5. I wonder if is it safe to install and use this project with PowerShell 7. If I would invoke my venv with a later version of PowerShell (v7), will it cause some sort of a conflict, create bugs, or clashes? Are there any data fetched by venv (and stored) related to PowerShell? -
Connect views.py to a Javascript file
I'm working on a Django project showing PDF files from a dummy database. I have the function below in views.py to show the PDF files. def pdf_view(request): try: with open ('static/someData/PDF', 'rb') as pdf: response = HttpResponse(pdf.read(), content_type="application/pdf") response['Content-Disposition'] = 'filename=test1.pdf' return response pdf.closed except ValueError: HttpResponse("PDF not found") This function needs get connected to another function located in a javascript file. How do we connect views.py to another Javascript file? -
Django Create separate copy of a model every time a user signs up
So, I am really new to Django. I was working around an app as a part of an assignment which requires me to build a webapp with login functionality, Further the admin, shall create few tasks that will be common to all the users. So here is the model that would contain all the tasks and will be controlled by the admin: from django.db import models # Create your models here. class applib(models.Model): status_code=[ ('C','Completed'), ('P','Pending'), ] title = models.CharField(max_length=50) status=models.CharField(max_length=2,choices=status_code) point = models.IntegerField() category= models.CharField(max_length=50) subcat = models.CharField(max_length=50) applink = models.CharField(max_length=100) def __str__(self): return self.title Now I have worked around the login functionality, and I want that upon each login a copy of this model is attached to the user so that the user can has his own set of tasks. He should be able to keep track of these tasks and do the tasks independently. How do I do this without creating separate task models for each user. I know there would be a really simple explanation and solution but all I know write now is I want to inherit the tasks from the main model for each user upon user creation. Thank you. -
How does database connection pooling work with Celery (& Django) for prefork & gevent connection types?
I have a django server, alongside a celery background worker, both of them interact with a Postgres database. I have a single celery worker running gevent with 500 concurrency flag. This gives 500 threads under a single worker to run and execute tasks. My question is do all of these threads try to use the same database connection? Or will it try to create 500 connections. In a prefork pool, does it create a connection per process? I saw in django documentation (https://docs.djangoproject.com/en/4.1/ref/databases/#connection-management), it says that it allows persistent connections, so connections are reused, but I'm not sure how this translates to celery? -
Django Dataframe not able to convert timestamp to date
Django Data frame not able to convert timestamp to date in template view Query result of Select * from paper_trade where date = now()::date order by open_time is Date day open_time 2022-10-19 Wednesday 10:54 My code is as below sql_query_n = pd.read_sql_query("""Select * from paper_trade where date = now()::date order by open_time""",con=engine) df_n = pd.DataFrame(sql_query_n) json_records_n = df_n.reset_index().to_json(orient ='records') data_n = [] data_n = json.loads(json_records_n) In the django template trying to itrate and use as {{ i.date }} Date_______________day_________ open_time 1666137600000 Wednesday 1666176843000 1666137600000 Wednesday 1666185662000 1666137600000 Wednesday 1666188004000 Tried {{ i.date|date:'Y-m-d' }} but it gives empty value. What is the issue -
ImportError: cannot import name 'views' from 'birds_eye'
I've recently started to learn how to build django projects with multiple apps. I have learnt that by using from . import views I can import the different views from the current directory that I am in. However, when using this method, the prompt would give me an error saying: ImportError: cannot import name 'views' from 'birds_eye' The following is my current directory tree of my django project: birds_eye |- accounts (app folder) |- birds_eye (actual project folder) |- clubs (app folder) |- events (app folder) |- posts (app folder) |- static |- templates And this is the actual code of what is happening: birds_eye |- birds_eye (actual project folder) |- urls.py from django.contrib import admin from django.urls import path, include from . import views urlpatterns = [ path('', views.HomePage.as_view(), name="home"), path("admin/", admin.site.urls), path("test/", views.TestPage.as_view(), name="test"), path("thanks", views.ThanksPage.as_view(), name="thanks"), path('accounts/', include("accounts.urls", namespace="accounts")), path("accounts/", include("django.contrib.auth.urls")), # Events --> Calendar, Posts --> Feed | Expected to finish later on. Uncomment when done. # path("posts/", include("posts.urls", namespace="posts")), # path("events/", include("events.urls", namespace="events")), path("clubs/", include("clubs.urls", namespace="clubs")), path('surveys', include('djf_surveys.urls')), ] Is there any solution to this? (I can edit the question in order to provide more resources from my project) -
Django media returns the 404 NOT FOUND when I try to GET media using Axios
I'm trying to get media from django but I get this 404 NOT FOUND error message in the console xhr.js?1a5c:244 GET http://127.0.0.1:8000/api/v1/products/$%7Bcategory_slug%7D/$%7Bproduct_slug%7D 404 (Not Found) My product/urls.py code is this from product import views urlpatterns = [ path('latest-products/', views.LatestProductsList.as_view()), path('products/<slug:category_slug>/<slug:product_slug>/', views.ProductDetail.as_view()), ] the first path works perfectly but the second one shows this error GET http://127.0.0.1:8000/api/v1/products/$%7Bcategory_slug%7D/$%7Bproduct_slug%7D 404 (Not Found) -
Django rest framework browsable api show null for manytomany field
I am going to implement api for blog app using DRF ModelViewSet: This is how i implemented: views.py from rest_framework.permissions import IsAuthenticatedOrReadOnly from rest_framework.response import Response from .serializers import PostSerializer, CategorySerializer from ...models import Post, Category from rest_framework import viewsets from rest_framework.decorators import action from .permissions import IsOwnerOrReadOnly from django_filters.rest_framework import DjangoFilterBackend from rest_framework.filters import SearchFilter, OrderingFilter from .paginations import DefaultPagination class PostModelViewSet(viewsets.ModelViewSet): permission_classes = [IsAuthenticatedOrReadOnly, IsOwnerOrReadOnly] serializer_class = PostSerializer queryset = Post.objects.filter(ok_to_publish=True) filter_backends = [DjangoFilterBackend, SearchFilter, OrderingFilter] filterset_fields = { "category": ["exact", "in"], "author": ["exact"], "ok_to_publish": ["exact"], } search_fields = ["title", "content"] ordering_fields = ["publish_date"] pagination_class = DefaultPagination @action(detail=False, methods=["get"]) def get_ok(self, request): return Response({"detail": "ok"}) class CategoryModelViewSet(viewsets.ModelViewSet): permission_classes = [IsAuthenticatedOrReadOnly] serializer_class = CategorySerializer queryset = Category.objects.all() serializers.py from rest_framework import serializers from ...models import Post, Category from accounts.models import Profile class CategorySerializer(serializers.ModelSerializer): class Meta: model = Category fields = ["id", "name"] class PostSerializer(serializers.ModelSerializer): summary = serializers.CharField(source="get_summary", read_only=True) relative_url = serializers.CharField(source="get_relative_api_url", read_only=True) absolute_url = serializers.SerializerMethodField(method_name="get_absolute_api_url") category = serializers.SlugRelatedField( queryset=Category.objects.all(), slug_field="name", many=True ) class Meta: model = Post fields = [ "id", "title", "author", "image", "content", "summary", "category", "relative_url", "absolute_url", "ok_to_publish", "login_required", "n_views", "created_at", "publish_date", ] read_only_fields = ["author"] def get_absolute_api_url(self, obj): # It is not a standard and correct … -
Can't serve Django static files with NGINX
I'm trying to deploy a Django and React website using gunicorn, nginx and docker. I can't get nginx to read my static files for example the django admin panel. I already ran python manage.py collecstatic and the files are in recommendations-be/backend/static Here is the docker-compose.yml file: version: '3' services: backend: build: context: ./recommendations-be command: gunicorn backend.wsgi:application --bind 0.0.0.0:8000 --timeout 0 ports: - "8000:8000" volumes: - static:/django/backend/static frontend: build: context: ./recommendations-fe volumes: - react_build:/react/build nginx: image: nginx:latest ports: - "80:8080" volumes: - ./nginx/nginx-setup.conf:/etc/nginx/conf.d/default.conf:ro - react_build:/var/www/react - static:/django/backend/static depends_on: - backend - frontend volumes: static: react_build: Here is my nginx conf file: upstream api { server backend:8000; } server { listen 8080; location / { root /var/www/react; } location /api/ { proxy_pass http://api; proxy_set_header Host $http_host; } location /static/ { alias /django/backend/static; } } Here's the Dockerfile in backend directory recommendations-be: FROM python:3.10.8-slim-buster ENV PYTHONUNBUFFERED 1 WORKDIR /django COPY requirements.txt requirements.txt RUN pip install --upgrade pip --no-cache-dir RUN pip install -r requirements.txt --no-cache-dir COPY . . And the django settings.py: STATIC_URL = "/static/" STATIC_ROOT = os.path.join(BASE_DIR, "backend", "static") Here is the file structure in my project: file structure -
Django needs to restart server for changing data in template
The goal is to make texts in static templates like "about us" page dynamic with a model so that it can be edited easily later on. My model is as below: class SiteData(models.Model): data_set_name = models.CharField( max_length=200, blank=False, null=False, default="نام مجموعه داده" ) main_page_english_info = models.TextField( verbose_name="مقدمه انگلیسی", blank=True, null=True ) main_page_persian_info = models.TextField( verbose_name="مقدمه فارسی", blank=True, null=True ) my view is as below: class HomePageView(ListView): model = SiteData template_name: str = "core/index.html" site_data = SiteData.objects.get(pk=1) context_vars = { "site_data": site_data, } def get_context_data(self, **kwargs): context = super(HomePageView, self).get_context_data(**kwargs) context.update(HomePageView.context_vars) return context and my template: <p class="mt-3 text-justified text-english fw-semibold nm-text-color" style="direction: ltr; ">{{ site_data.main_page_english_info }}</p> <p class="mt-3 text-justified nm-text-color">{{ site_data.main_page_persian_info }}</p> My problem with this method is two main issues: This method works and if I change data from admin panel, it will be applyed, BUT ONLY if I restarted development server! (ctrl + c and py manage.py runserver). Where is my problem? How can I solve this issue? My model itself isn't so dynamic itself, and this is why I'm also trying another method which I have other problems in that, and I've asked another question here. Now, I'll appreciate an answer to either of these question! -
How to rename default django model field after creation in admin panel
I am making a simple application in Django, where I want my admins to be able to go into the admin panel and create a Level object class Level(models.Model): content = models.CharField(max_length = 200) ^^ This is my simple layout for the model, only admins can create this. However, when my admins create the Level object, it shows up like this: How it shows up in admin panel I don't want this, and I want that to be replaced with the string content, which is a field in my Level model So instead of looking like above, I want it to just contain the context. How can I do this? -
Django Extend Default User Model
I am searching for a way to easily add more character fields to the default user model from Django. This question has been asked, but I couldn't find an up to date answer. I let Django handle all the authenticating and logging in, so I don't want to create a custom user model, any ideas? -
From SQL to Django without raw method
I'm trying to convert SQL Query to Django. I'm new to Django and I find it hard to do simple things, here is the SQL query I'm trying to run with Django : SELECT * FROM balance_hold bh1 WHERE bh1.account_balance = X and bh1.hold_id in ( SELECT hold_id FROM balance_hold bh2 WHERE bh2.transaction_id = bh1.transaction_id and bh2.account_balance = X and ( bh2.release_time = null and hold_type >= (select * from balance_hold bh3 where bh3.transaction_id = bh2.transaction_id and bh3.account_balance = X and bh3.release_time = null) ) or ( bh2.release_time != null and bh2.release_time >= (select release_time from balance_hold bh3 where bh3.transaction_id = bh2.transaction_id and bh3.account_balance = X and bh3.release_time != null) )) ) how do I run this with Django (without using RAW method!)? -
Download a file created using python-docx from Django DRF?
I am trying to create a file using python-docx and download it using DRF/Django. I have tried almost all the answers to questions similar to mine. I get errors. Api.py class CreateDocx(viewsets.ModelViewSet): queryset = BooksModel.objects.all() serializer_class = BooksSerializer # serializer_class = BooksSerializer # permission_classes = [ # permissions.AllowAny # ] # def get(self): def download(self, request): print('creating file') document = file_create() # Function is returning a Document from python-docx, see below response = FileResponse(document, content_type='application/msword') # response['Content-Length'] = instance.file.size response['Content-Disposition'] = 'attachment; filename="TEST.docx"' return response file_create function: def file_create(): document = Document() docx_title = "TEST_DOCUMENT.docx" # Get the required info queryset = BooksModel.objects.all() # Place queries in document for query in queryset.values(): print(query) table = document.add_table(rows=1, cols=1) pic_cel = table.rows[0].cells[0].paragraphs[0] run = pic_cel.add_run() run.add_picture("/Users/xxx/Downloads/1.jpg", width=Mm(90), height=Mm(45)) print('added picture') return document urls.py from rest_framework import routers from .api import CreateDocx router = routers.DefaultRouter() router.register('api/download', CreateDocx, 'download-doc') urlpatterns = router.urls When I make a call to api/download/ I get a json reponse. I can't figure out what I am doing wrong because it seems download function inside the CreateDocx is not getting called whatsoever. I tried removing the serializer_class and queryset before the function but that results in errors. Such as: 'CreateDocx' … -
How to define default_search_fields in StretchIndex for Object type
I am trying to apply search for some of the child attributes of an Object in elastic search StretchIndex. The base attribute is defined in the below manner. primary_occupied_property = elasticsearch_dsl.Object( source='get_primary_occupied_property', properties=PROPERTY_MAPPING_PROPERTIES, dynamic=False, enabled=True, ) PROPERTY_MAPPING_PROPERTIES is defined as below. PROPERTY_MAPPING_PROPERTIES = { 'building': elasticsearch_dsl.Object(properties=BUILDING_MAPPING_PROPERTIES) } BUILDING_MAPPING_PROPERTIES is defined as below. 'city': elasticsearch_dsl.Keyword( fields={ 'standard': elasticsearch_dsl.Text(analyzer='standard'), 'autocomplete': elasticsearch_dsl.Text(analyzer=autocomplete_analyzer) }), 'state': elasticsearch_dsl.Keyword( fields={ 'standard': elasticsearch_dsl.Text(analyzer='standard'), 'autocomplete': elasticsearch_dsl.Text(analyzer=autocomplete_analyzer) }), On checking the index, we receive the below data. "primary_occupied_property": { "dynamic": "false", "properties": { "building": { "properties": { "address": { "type": "keyword" }, "city": { "type": "keyword", "fields": { "autocomplete": { "type": "text", "analyzer": "autocomplete_analyzer" }, "standard": { "type": "text", "analyzer": "standard" } } }, } } The default_search_fields are defined as - default_search_fields = [ 'primary_occupied_property.building.city.standard', 'primary_occupied_property.building.state.standard', 'primary_occupied_property.building.city.autocomplete', 'primary_occupied_property.building.state.autocomplete', ] However when I am executing the API, the search with specific city or state is not working. Please suggest. -
Django doesn't show images after adding multiple environments
I'm trying to add local and production environments to my Django project. So instead of one settings.py file, I created a settings directory and in that directory, added 3 settings files: base.py, local.py, and pro.py settings (directory) base.py (the new name for settings.py) local.py (inherits from base.py with some parameter overrides) pro.py (inherits from base.py with some parameter overrides) In the base.py file, I updated the BASE_DIR parameter to point to the parent folder of the current file. previous BASE_DIR: BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__))) new BASE_DIR: BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath( os.path.join(__file__, os.pardir)))) I didn't change static and media root parameters (in base.py): STATIC_URL = '/static/' STATIC_ROOT = os.path.join(BASE_DIR, 'static/') MEDIA_URL = '/media/' MEDIA_ROOT = os.path.join(BASE_DIR, 'media/') However, after the change, my images don't show up anymore. What am I doing wrong? -
send variables or messages to page while script is doing tasks (django 4)
I'm doing some python script with django, and I when the user submit a file, I process the file and do tons of tasks, it can last a few minutes. While the user is waiting, I got a loading screen in js, and I print in console what's happening. But I would like to print it in the page, on the loading screen, is there a simple way to do this? my model looks like that models.py def main(): #all the long stuff & logic and my view : views.py def upload(request): #some other stuff MyModel.main() return render(request, 'frontend/upload.html',{ 'form':form, } ) It can be frustrating for the user (and for me) to wait and not know what's going on, I'd like to use my page as I use the console with print, because I'm not over with the stuff to do and I guess it could last some long minutes. -
error while using django_scopes : 'A scope on dimension(s) tenant needs to be active for this query.'
I am using django_scopes module to integrate tenancy across all get views in my django app. As per the readme doc in the repo: https://github.com/raphaelm/django-scopes it says: You probably already have a middleware that determines the site (or tenant, in general) for every request based on URL or logged in user, and you can easily use it there to just automatically wrap it around all your tenant-specific views. Accordingly, I have setup my middleware : class TenantScoper: def __init__(self, get_response): self.get_response = get_response def __call__(self, request): with scope(tenant='xyz'): response = self.get_response(request) return response However, for model view set, when i bring up the server i get an error: django_scopes.exceptions.ScopeError: A scope on dimension(s) tenant needs to be active for this query. class TenantFeatureViewSet(viewsets.ModelViewSet): serializer_class = TenantFeatureSerializer queryset = TenantFeature.objects.all() Although it works perfectly for custom get view: class TenantFeatureView(APIView): def get(self, request): data = TenantFeature.objects.all() Error seems to originate when the line TenantFeature.objects.all() gets executed during server initialisation itself, Is there any workaround for this?