Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Nginx subdomain running the wrong web application
so I have a ubuntu server that run two different website with two different domain: www.firstwebsite.com www.secondwebsite.com But when I create an AAA record to create a subdomain with the first domain (like this) demo.firstwebsite.com If I go to this subdomain it automatically run the application website of my other domain (www.secondwebsite.com) I tried creating a specific socket&service file for the subdomain for it still run the web application of the second domain. Im not sure what is causing that and how to fix that? thank you -
create superuser in django custom User model with phone number as username
I have a django project which I want it to have phone number as its username field. I've created an app named accounts, and this is the models.py: class UserManager(BaseUserManager): use_in_migrations = True def create_user(self, phone_number, password, **extra_fields): user = self.model(phone_number=phone_number, **extra_fields) user.set_password(password) user.save(using=self._db) return user def create_superuser(self, phone_number, 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(phone_number, password, **extra_fields) class User(AbstractUser): phone_number = models.CharField(max_length=20, null=False, blank=False, unique=True) USERNAME_FIELD = "phone_number" username = None first_name = None last_name = None objects = UserManager() REQUIRED_FIELDS = [phone_number] And I've declared it as my user model, in settings.py. AUTH_USER_MODEL = "accounts.User" ACCOUNT_USER_MODEL_USERNAME_FIELD = "phone_number" When I run python manage.py createsuperuser, I get this error: django.core.exceptions.FieldDoesNotExist: User has no field named 'accounts.User.phone_number' I can't figure out what is the problem. -
dockerized django application cannot connect to mysql server on localhost
I have a Dockerized django application I am running and I am trying to connect it to a mysql server I have that is port forwarded from another docker container. I have done a sanity test already and confirmed that I can connect to my mysql server using mysql workbench on my localhost. I have my dockerized django application running on network_mode: host so I thought I would be able to simply connect. Sadly I currently error out on docker-compose build with the error django.db.utils.OperationalError: (2002, "Can't connect to MySQL server on '127.0.0.1' (115)") An accepted resolution to this issue means that my dockerized django application would be able to connect successfully to my mysql server running localhost:29998 SETTINGS.PY (Django Application) DATABASES = { 'default': { 'ENGINE': 'django.db.backends.mysql', 'NAME': 'mytestdb', 'USER': 'userone', 'PASSWORD': 'password', 'HOST': '127.0.0.1', 'PORT': '29998', } } DJANGO App compose file version: '3.3' services: mydjangoapp: container_name: mydjangoapp restart: always env_file: .env build: . volumes: - ./apps:/apps - ./core:/core network_mode: host Django app dockerfile: FROM python:3.9 COPY . . # set environment variables ENV PYTHONDONTWRITEBYTECODE 1 ENV PYTHONUNBUFFERED 1 COPY requirements.txt . # install python dependencies RUN pip install --upgrade pip RUN pip install --no-cache-dir -r requirements.txt # … -
Receiving email content with in a template using Django contact form
I have set up a fully operational contact form and now I would like to render the users inputs into a html template, so when I receive the email it is easier to read. How do I do this? Do I link the template below some where, or link the form with in a template? Thank you in advance def contactPage(request): if request.method == 'POST': form = contactForm(request.POST) if form.is_valid(): subject = "INQUIRY" body = { 'full_name': form.cleaned_data['full_name'], 'email': form.cleaned_data['email_address'], 'message':form.cleaned_data['message'], } message = "\n".join(body.values()) try: send_mail(subject, message, '', ['email]) except BadHeaderError: return HttpResponse('Invalid header found.') return redirect ('thankyou') form = contactForm() return render(request, "contact.html", {'form':form}) -
django: aggregation-of-aggregation with subquery: cannot-compute-avg-is-an-aggregate
I've been scouting & testing for quite some time now and I'm unable to get anything working with MariaDB. I have a subquery: rating_average_by_puzzle_from_completion_plays = Play.objects.filter(completion_id=OuterRef('id')).values('puzzle_id').order_by('puzzle_id').annotate(puzzle_rating_average=Avg('rating')).values('puzzle_rating_average') where the ratings of all plays corresponding to a given completion are averaged per puzzle_id Afterwards, I'm trying, for each completion, to average the puzzle_rating_average corresponding to each puzzle_id: if I do annotate, I end up with : SequenceCompletion.objects.annotate(rating_avg_from_completion_plays=Subquery(rating_average_by_puzzle_from_completion_plays.annotate(result=Avg('puzzle_rating_average')).order_by().values('result'))) django.core.exceptions.FieldError: Cannot compute Avg('puzzle_rating_average'): 'puzzle_rating_average' is an aggregate if I do aggregate, I end up with : SequenceCompletion.objects.annotate(rating_avg_from_completion_plays=Subquery(rating_average_by_puzzle_from_completion_plays.aggregate(result=Avg('puzzle_rating_average')).order_by().values('result'))) ValueError: This queryset contains a reference to an outer query and may only be used in a subquery. I tried as well: SequenceCompletion.objects.annotate(rating_avg_from_completion_plays=Avg(Subquery(rating_average_by_puzzle_from_completion_plays))) and I end up with: MySQLdb._exceptions.OperationalError: (1242, 'Subquery returns more than 1 row' Nothing I could find on the documentation or in any post would work, so I'll appreciate any help -
Page not found (404) Error in Django when creating a checkout session with Stripe
I am working on my first Stripe integration project to Django and I have landed into a problem that I have not managed to figure out a solution. I am trying to create a session whereby users can be redirected to the page where they can make a payment. Here is my views.py: class ProductLandingPageView(TemplateView): template_name = "landing.html" def get_context_data(self, **kwargs): product = Product.objects.get(name="Test Product") context = super(ProductLandingPageView, self).get_context_data(**kwargs) context.update({ "product": product, "STRIPE_PUBLIC_KEY": settings.STRIPE_PUBLISHABLE_KEY }) return context class CreateCheckoutSessionView(View): def post(self, request, *args, **kwargs): product_id = self.kwargs["pk"] product = Product.objects.get(id=product_id) YOUR_DOMAIN = "http://127.0.0.1:8000" checkout_session = stripe.checkout.Session.create( line_items=[ { # Provide the exact Price ID (for example, pr_1234) of the product you want to sell 'price': '{{product.price}}', 'quantity': 1, }, ], metadata={ "product_id": product.id }, mode='payment', success_url=YOUR_DOMAIN + '/success/', cancel_url=YOUR_DOMAIN + '/cancel/', ) return redirect(checkout_session.url, code=303) Here is my urls.py; urlpatterns = [ path('', ProductLandingPageView.as_view(), name='landing'), path('success/', SuccessView.as_view(), name='success'), path('cancel/', CancelView.as_view(), name='cancel'), path('create-checkout-session/<pk>', CreateCheckoutSessionView.as_view(), name='create-checkout-session'), ] Also here is the templatate where the checkout button is located: <body> <section> <div class="product"> <!-- <img src="https://i.imgur.com/EHyR2nP.png" alt="The cover of Stubborn Attachments" /> --> <div class="description"> <h3>{{product.name}}</h3> <h5>${{product.price}}</h5> </div> </div> <form action="/create-checkout-session" method="POST"> <button type="submit" id="checkout-button">Checkout</button> </form> </section> {% csrf_token %} </body> <script type="text/javascript"> … -
i have defined block content in base.html and extents in index.html , block content is not working
in template/app/index.html {% extends 'base.html' %} {% block content %} replace me {% endblock %} in template/app/base.html <!doctype html> <html> <head> <title>Base title</title> </head> <body> {% block content %} {% endblock %} </body> </html> in app/urls.py from django.urls import path from app import views urlpatterns = [ path('',views.index) ] in app/views.py from django.shortcuts import render # Create your views here. def index(request): return render(request,'app/base.html',{}) this is the code...! i have tried changing the folder location and saw level of the folder -
Can't import anything from django
I'm having problems with importing stuff from django. I'm completely new to python and I'm following a tutorial where I'm taught how to make my first django project (I'm using pycharm btw). The problem I'm encountering is when I try to import something from django it says Unresolved reference 'django'. from django.http import HttpResponse from django.shortcuts import render In this case it only shows the red squiggly line under the two django, HttpResponse and render. Any help would be appreciated I have tried searching on google, but i couldn't find what I'm looking for. -
Django token authentication error: cURL request without header shows 401 unauthorized, but adding header token auth changes to 404 not found error
Titles lays out the issue I am facing. Working on a boiler plate Django app with an API endpoint. I am able to (semi-successfully) access the endpoint via a simple cURL without header which returns a 401, but when I add the header token, I now get a 404 not found error. What could be going wrong? I've tried multiple different combinations of django settings changes across these forums and cannot get it to change. Examples of some things I have tried: Changing order of MIDDLEWARE CORS_ORIGIN_WHITELIST CORS_ALLOWED_ORIGINS CORS_ALLOW_CREDENTIALS CORS_ORIGIN_ALLOW_ALL Playing with REST_FRAMEWORK settings -- both DEFAULT_AUTHENTICATION_CLASSES & DEFAULT_PERMISSION_CLASSES Changing ALLOWED_HOSTS from [] to current value below CORS_ALLOWED_ORIGINS Attaching snippets of relevant code: 401 cURL: curl -X GET http://127.0.0.1:8000/bettor/create/ 404 cURL: curl -X GET http://127.0.0.1:8000/bettor/create/ -H "Authorization: Token <super secret but valid token>" settings.py: from pathlib import Path BASE_DIR = Path(__file__).resolve().parent.parent # SECURITY WARNING: keep the secret key used in production secret! SECRET_KEY = '<secret hidden key>' # SECURITY WARNING: don't run with debug turned on in production! DEBUG = True ALLOWED_HOSTS = ['localhost', '127.0.0.1'] INSTALLED_APPS = [ 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', # helpers 'rest_framework', 'rest_framework.authtoken', 'corsheaders', # my apps 'Bets', 'Users', ] MIDDLEWARE = [ "django.middleware.security.SecurityMiddleware", "django.contrib.sessions.middleware.SessionMiddleware", … -
Signals django not working on ubuntu server
I have a site on the server where I work with signals.py The problem is that when I add a db file through the admin panel signals.py does not work EXACTLY ON THE SERVER on my computer everything works fine But there is another model involving signals.py and it works great models.py The model that works class History(models.Model): tg_id = models.BigIntegerField(verbose_name='Telegram ID') amount = models.FloatField(verbose_name='Кол-во') date = models.DateTimeField(verbose_name='Дата транзакции') Problem model class database_sqlite3(models.Model): file = models.FileField(verbose_name='Файл', upload_to='db_file/', help_text='Вы можете добавить сюда базу пользователей') app.py from django.apps import AppConfig class MainConfig(AppConfig): default_auto_field = 'django.db.models.BigAutoField' name = 'main' verbose_name = "Бот" def ready(self): import main.signals signals.py The model that works @receiver(post_save, sender=History) def create_profile(sender, instance, created, **kwargs): if created: obj = User.objects.get(tg_id=int(instance.tg_id)) wallet = obj.wallet if wallet == None: wallet = 0 else: pass User.objects.filter(tg_id=instance.tg_id).update(wallet=wallet + instance.amount)0 Problem model @receiver(post_save, sender=database_sqlite3) def create_profile(sender, instance, created, **kwargs): if created: env = Env() env.read_env() gre = psycopg2.connect( database=env.str('POSTGRES_DB'), user=env.str('POSTGRES_USER'), password=env.str('POSTGRES_PASSWORD'), host=env.str('POSTGRES_HOST'), port=env.str('POSTGRES_PORT') ) cur_gre = gre.cursor() conn = sqlite3.connect(str(instance.file)) cursor = conn.cursor() table_names = cursor.execute("SELECT name FROM sqlite_master WHERE type='table';").fetchall() table_name = [] for i in table_names: table_name.append(i[0]) if 'main_admin_bot' in table_name: cursore = conn.execute(f"SELECT * FROM main_admin_bot").fetchall() for i in cursore: try: sql … -
Make longer access tokens with django_oauth_toolkit
I have setup the OAuth 2.0 authentication in a Django Rest Framework project with the django_oauth_toolkit library. But I have noticed access_token length is quite short. How can I make these tokens larger? I mean, increase the number of characters each token has. I have been searching for a setting to do this, but I haven't found anything. I have read all the avaiable settings in the OAUTH2_PROVIDER setting, but I have found nothing. -
heroku H10 issue
I get the Error: at=error code=H10 desc="App crashed" method=GET path="/" host=quiz-iu.herokuapp.com request_id=9ee6412c-b248-4eeb-8eba-066f07b38a4f fwd="93.201.118.59" dyno= connect= service= status=503 bytes= protocol=https 2022-12-19T17:47:36.743985+00:00 heroku[router]: at=error code=H10 desc="App crashed" method=GET path="/favicon.ico" host=quiz-iu.herokuapp.com request_id=071363bb-8ce2-4eed-bdc5-93cd3b39581f fwd="93.201.118.59" dyno= connect= service= status=503 bytes= protocol=https And if i set into the consul : heroku run rails console I get: bash: line 1: rails: command not found Can please someone help to fix this issue I try to devolope a app but get the a error -
Restrict access of static files to permission groups
i am fairly new to web-development and i can't really find the best way to handle serving files with django. My situation is: I have users from different departments that can upload, edit and download files. Users should have access to files from other users of the same department, but not of the others. The way it works until now is: each filepath is written in a database, with a reference to which department it belongs. If requesting a file django checks if the department of the user is the same as the file, and denies the access if that not the case. After researching a bit it seemed that serving files that way isnt the standard way, and i should serve them as static files (from the webserver, not directly by django). My question is: can i still restrict the access of static files, or can anyone read them? -
Django: save() prohibited to prevent data loss due to unsaved related object 'predictions'
I am a creating a Django project, where i am using inline_formset to add multiple forms from the frontend (Just like the backend). I am trying create a new object now from the frontend, the main models get saved but the the model that is a foreignKey to the main model is not saving (Inline Model). I am getting the error message: save() prohibited to prevent data loss due to unsaved related object 'predictions'. Here is my CreateView Code. views.py class ProductInline(): form_class = PredictionForm model = Predictions template_name = "core/create/create_bet.html" def form_valid(self, form): named_formsets = self.get_named_formsets() if not all((x.is_valid() for x in named_formsets.values())): return self.render_to_response(self.get_context_data(form=form)) # self.object = form.save() new_form = form.save(commit=False) new_form.user = self.request.user new_form.save() # for every formset, attempt to find a specific formset save function # otherwise, just save. for name, formset in named_formsets.items(): formset_save_func = getattr(self, 'formset_{0}_valid'.format(name), None) if formset_save_func is not None: formset_save_func(formset) else: formset.save() return redirect('core:dashboard') def formset_variants_valid(self, formset): """ Hook for custom formset saving.. useful if you have multiple formsets """ variants = formset.save(commit=False) # self.save_formset(formset, contact) # add this, if you have can_delete=True parameter set in inlineformset_factory func for obj in formset.deleted_objects: obj.delete() for variant in variants: variant.product = self.object variant.save() … -
How can I determine the order of files/sub-folders within user-generated folders in Django?
I am building a Django web app where users can upload files into a folder structure that they also create/control. I know how to facilitate uploading of files and understand the solution proposed in this question about how to "assign" files (or sub-folders) to their parent folders, without having to create actual folders in the underlying file storage. However, in my web-app I would also like to allow users to determine the order of files and sub-folders within each folder without relying on the actual filenames. I know I can set the order of the returned one-to-many model instances by setting the index variable in a meta class (see this question). In my case I could thus insert an "order" field into the file/folder models and then set this value appropriately for each file/sub-folder in a given parent folder. However, this would mean that when a user moves a file from the bottom to the top of the parent folder, for example, every single one of the parent folder's file/sub-folder model instances would need to be edited to reflect their new position in the folder. Maybe my lack of coding experience is misleading me, but this setup looks to me … -
Why do people code flutter apps with dart instead of flet for mobile applications?
Multiple sources encouraged developers to learn dart language so that users can develop flutter apps for both iOS and android platforms. However, I can hardly find sources that say flet language can achieve the same results. For one thing, I think I am somehow fluent in python. If I code in flet language on flutter, I would've skipped few weeks to learn dart just so I can code a mobile app. Coding the app in python would make the code language consistent across both front-end and back-end (django) but I am afraid that would I be missing out on something by not learning to code in dart. What are the implications for me to develop a mobile app for both iOS and android platforms if I coded my app in flet instead of dart with flutter? -
Using Model Manager on queryset
In my admin panel i want to do some functions from my ModelManager. I have admin.py def change_status(modeladmin,request,queryset): status = queryset.change_value() return status model.py class ItemManager(models.Manager): @classmethod def change_value(cls): list = Item.objects.filter(value=5) list.update(value=6) return list.list_values("id", flat=True) class Item(models.Model): name = models.TextField() value = models.FloatField() objects = ItemManager() But i get QuerySet object has no attribute 'change_value'. But queryset is Item Queryset so why i cant use manager methods on it? -
What is the easy way to validate scheduling data in python
Well everyone. Honestly my head is about to explode on this situation. My whole day spent on this thing to solve it but i could not do that, so finally here i am on stackoverflow and asking for help from some of you experts. who can help me out in solving this problem. Well i have json object that contain the scheduling of a single day. and let me explain each part of this so you guys understand where i'm struggling so far. { "timings":{ "id":43, "partition":7, "day_name":"Tuesday", "full_day":false, "close_day":false, "start_time":"2022-12-20 00:00:00", "close_time":"2022-12-20 23:00:00" }, "pricings":[ { "partition":7, "day_name":"Tuesday", "peak_hours":true, "start_time":"2022-12-20 17:00:00", "close_time":"2022-12-20 23:00:00", "price":"1300" }, { "partition":7, "day_name":"Tuesday", "peak_hours":true, "start_time":"2022-12-20 00:00:00", "close_time":"2022-12-20 04:00:00", "price":"1300" }, { "id":54, "partition":7, "day_name":"Tuesday", "peak_hours":false, "start_time":"2022-12-20 04:00:00", "close_time":"2022-12-20 17:00:00", "price":2000 } ] } as you can see the first key is timings. Which contains the detail of shop when it will open and when it'll close. simple and nice. then we move on second key which is pricings. its a list of objects that contains that is it a peak hour or off_peak_hours or when they start and when they end. Now problem arise here : How can we validate all timing values such … -
How do I turn off CSRF checks with Django auth's PasswordResetView?
I'm using Django 3.1 with Django's auth application. I have the following middleware defined 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', 'directory.middleware.extend_token_response.ExtendTokenResponse' ] I would like to use Django auth's reset password functionality so I added this in my urls.py view path('reset_password', views.ResetPasswordView.as_view(), name='password_reset'), and in my views.py file I have defined from django.views.decorators.csrf import csrf_exempt ... class ResetPasswordView(SuccessMessageMixin, PasswordResetView): template_name = 'users/password_reset.html' email_template_name = 'users/password_reset_email.html' subject_template_name = 'users/password_reset_subject' success_message = "We've emailed you instructions for setting your password, " \ "if an account exists with the email you entered. You should receive them shortly." \ " If you don't receive an email, " \ "please make sure you've entered the address you registered with, and check your spam folder." success_url = reverse_lazy('users-home') @csrf_exempt def post(self, request, *args, **kwargs): email = request.data.get('email') try: if User.objects.get(email=email).active: print("email: %s " % email) return super(ResetPasswordView, self).post(request, *args, **kwargs) except: # this for if the email is not in the db of the system return super(ResetPasswordView, self).post(request, *args, **kwargs) However, the CSRF check doesn't seem to be getting checked for, because when I submit a request like the below curl 'http://127.0.0.1:8000/reset_password' \ -H 'Accept: */*' \ -H 'Accept-Language: en-US,en;q=0.9' \ … -
How can I let my users watch Netflix, Prime video etc inside my webpage if they have accounts?
We are developing a website for users to be able to watch tv shows/movies together synchronously. We are aware of extensions such as Teleparty, Scener etc. We want to embed it within the site so that no one needs to install an extension. We have solely used Django because it was mandatory to use it. Is there a way to do it? Or should we just develop an extension as well? P.S: There is an app called Rave and they stream all of the aforementioned platforms and more through their apps (including Mac, Windows and Android). We are not sure how that is possible. -
Django Ecommerce View problem with incrementing a quantity up or down on products with same Product Id but different Option ID values
My issue is probably something simple but Ive been stuck on it. I am attempting to make my ecommerce shopping cart increment quantity up and down while deleting the instance when quantity gets to zero. The issue is that when you add options to a product that is in another cart_item instance with the same base Product_id its throwing an error. Im aware it is pulling different instances of the same product_id into the same get request but im not sure how to resolve it. MultipleObjectsReturned at /cart/add_cart/2/ get() returned more than one CartItem -- it returned 2! Request Method: GET Request URL: http://127.0.0.1:8000/cart/add_cart/2/ Django Version: 3.1 Exception Type: MultipleObjectsReturned Exception Value: get() returned more than one CartItem -- it returned 2! Exception Location: C:\Users\dave\Desktop\tnaecommerce\venv\Lib\site-packages\django\db\models\query.py, line 433, in get Python Executable: C:\Users\dave\Desktop\tnaecommerce\venv\Scripts\python.exe Python Version: 3.11.0 Python Path: ['C:\\Users\\dave\\Desktop\\tnaecommerce\\ecomwebsite\\tnaecom', 'C:\\Python311\\python311.zip', 'C:\\Python311\\DLLs', 'C:\\Python311\\Lib', 'C:\\Python311', 'C:\\Users\\dave\\Desktop\\tnaecommerce\\venv', 'C:\\Users\\dave\\Desktop\\tnaecommerce\\venv\\Lib\\site-packages'] Server time: Mon, 19 Dec 2022 16:19:11 +0000 views.py ` from django.shortcuts import render, redirect, get_object_or_404 from .models import Cart, CartItem from store.models import Product, ProductOption from django.core.exceptions import ObjectDoesNotExist from decimal import Decimal from django.http import HttpResponse from decimal import Decimal from django.views import View from django.views.generic.edit import DeleteView def _cart_id(request): cart = request.session.session_key if … -
How can I change the URL that points to a File on the FileInput widget in the Django Admin frontend to point to my view
In my django project I want the user to be able to upload files, that are only accessible to users from the same company and from users that are staff. The solution I found is, that I upload the Files to a custom FileSystemStorage with a base_url that is not in urls, so files are not accessible over that url, the only way to access them is through my view. The problem is, that in the django admin frontend on a FileInput widget, it links to the url that is not accessible. How can I link it to my view? This is my model: upload_storage = FileSystemStorage(location='/private/', base_url='/private/') class Datei(models.Model): datei = models.FileField(upload_to='vertraege', storage=upload_storage) ... This is my view: @login_required(login_url='/login/') def serve_file(request, file_id): file = Datei.objects.get(id=file_id) user = User.objects.get(id=request.user.id) if file.firma == user.firma or user.is_staff: return FileResponse(file.datei) else: return HttpResponseForbidden() -
How can a celery task accept a list of files as an argument?
Actually, I don't know how I could make the task have a list of files as an argument. files = {} for file in request.FILES.getlist('files'): files[file.name] = file.file.read() my_celery_task.apply_async( kwargs={ 'files': files, } ) This throws the error 'Object of type bytes is not JSON serializable'. I also tried to add these files to the constructor of a class, but it's still not good because the object cannot be serialized. If I use files[file.name] = file, throws InMemoryUploadedFile is not JSON serializable, or if I use files[file.name] = file.file.read().decode('utf-8') => 'utf-8' codec can't decode byte 0xff in position 0: invalid start byte I actually have no idea how to solve it. I need that dictionary of the form name: content as an argument given to the task -
why does 'Django mssql connection error' happen?
i have an ready database and I wanna use it in django web project. but I have an error about connection. here is the error raise NotSupportedError('SQL Server v%d is not supported.' % ver) django.db.utils.NotSupportedError: SQL Server v16 is not supported. here is the packeges asgiref 3.5.2 Django 4.1.4 django-mssql-backend 2.8.1 django-pyodbc-azure 2.1.0.0 django-pyodbc-azure-2019 2.1.0.0 mssql-django 1.2 pip 22.0.4 pyodbc 4.0.35 pytz 2022.7 setuptools 58.1.0 sqlparse 0.4.3 tzdata 2022.6 and database settings DATABASES = { 'default': { 'ENGINE': 'sql_server.pyodbc', 'NAME':'veritabanıProje2', 'USER': 'sa', 'PASSWORD':'**', 'HOST':'DESKTOP-MDLFE99', 'PORT':'', 'OPTIONS':{ 'driver':'ODBC Driver 17 for SQL Server', }, }, } I'm using SQL server 2022. also the db file's name DB.sql in project directory. but I write here the name that is written while I create database. (I tried with DB.sql also of course) I can understand the fault is about version but which one is wrong I dont know. -
How to get data from api and load site at same time
I am making a website in Django that gets all stock data for the previous day from API. My problem is that when we take that data we run a few calculations and save data in DB (that process takes about 4 hours to finish) in that time I can't load my home page because that's where part of getting, calculating, and saving data is. So basically is there any way to do all things that I mentioned and use the site normally while getting, calculating, and saving data is running in the background?