Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Error when trying to import shuffle in scikit-learn
I am trying to simply from sklearn.utils import shuffle but I am getting this error: File "D:\research\pape\papertwo\Directional_Partial_Charging\hppo\hppo_noshare.py", line 6, in <module> from sklearn.utils import shuffle File "D:\Program Files (x86)\anaconda3\envs\wrsn\lib\site-packages\sklearn\__init__.py", line 83, in <module> from .base import clone File "D:\Program Files (x86)\anaconda3\envs\wrsn\lib\site-packages\sklearn\base.py", line 19, in <module> from .utils import _IS_32BIT File "D:\Program Files (x86)\anaconda3\envs\wrsn\lib\site-packages\sklearn\utils\__init__.py", line 15, in <module> from scipy.sparse import issparse File "D:\Program Files (x86)\anaconda3\envs\wrsn\lib\site-packages\scipy\sparse\__init__.py", line 283, in <module> from . import csgraph File "D:\Program Files (x86)\anaconda3\envs\wrsn\lib\site-packages\scipy\sparse\csgraph\__init__.py", line 185, in <module> from ._laplacian import laplacian File "D:\Program Files (x86)\anaconda3\envs\wrsn\lib\site-packages\scipy\sparse\csgraph\_laplacian.py", line 7, in <module> from scipy.sparse.linalg import LinearOperator File "D:\Program Files (x86)\anaconda3\envs\wrsn\lib\site-packages\scipy\sparse\linalg\__init__.py", line 130, in <module> from . import isolve, dsolve, interface, eigen, matfuncs File "D:\Program Files (x86)\anaconda3\envs\wrsn\lib\site-packages\scipy\sparse\linalg\isolve\__init__.py", line 4, in <module> from .iterative import * File "D:\Program Files (x86)\anaconda3\envs\wrsn\lib\site-packages\scipy\sparse\linalg\isolve\iterative.py", line 8, in <module> from . import _iterative ImportError: cannot import name '_iterative' from partially initialized module 'scipy.sparse.linalg.isolve' How should I solve this problem? -
Run django application (Python 2.7.18) in mac m1 environment
I am having issue running django application running in python 2.7.18 version. I have tried everything but numpy and pandas are not being installed. Due to which I am unable to run the project. I tried building docker image as well. In that as well I am getting errors. Please help me out. -
Prevent videos from being downloaded
I want to upload some videos on my django site And I want users to be able to see that video, but not be able to download it or not be able to record the screen. and please explain if it different in production and development How should I do this? -
Can't Run Django Server
i wrote database connection code in separate dbconn.py. this file is in the same folder where is my views.py located. But when i try to run django server it give an error Exception in thread django-main-thread: Traceback (most recent call last): File "C:\Program Files\Python311\Lib\threading.py", line 1038, in _bootstrap_inner self.run() ..... to long error and at end from . import views File "D:\Dexdel_mysite\mysite\dexdel_app\views.py", line 3, in from dbconn import connection ModuleNotFoundError: No module named 'dbconn' but while running views.py file it run successfully .. from dbconn import connection import syntext is correct but i can't understand why this error. -
is there any method for storing anonymous user details in created_by foreign key field that reference to same table for unauthenticated users
when i try to register user as authenticated user it is storing user data and created_by field to the current user. but when i try to register user as unauthenticated user it is showing an error the error is `"ValueError at /hrms/api/userregister/ Cannot assign "<django.contrib.auth.models.AnonymousUser object at 0x0000018096CB8230>": "CustomUser.created_by" must be a "CustomUser" instance. Request Method: POST Request URL: http://127.0.0.1:8000/api/userregister/ Django Version: 5.0 Exception Type: ValueError Exception Value: Cannot assign "<django.contrib.auth.models.AnonymousUser object at 0x0000018096CB8230>": "CustomUser.created_by" must be a "CustomUser" instance."` `#models.py class CustomUser(AbstractUser): email = models.EmailField(("email address"), unique=True) CompanyRole = models.CharField(max_length=100,blank=True) ContactNumber = models.CharField() created_by = models.ForeignKey('CustomUser', on_delete=models.CASCADE, null=True, related_name='% (class)s_created_by' ,default=1) USERNAME_FIELD = "email" REQUIRED_FIELDS = \['username'\] objects = CustomUserManager() def __str__(self): return self.email` this is my model.py file `#serializer.py class CustomUserSerializer(serializers.ModelSerializer): class Meta: model = CustomUser fields =('id','username','first_name','last_name','is_staff','email','CompanyRole','ContactNumber','password','created_by') extra_kwargs = {'password': {'write_only': True}} def create(self, validated_data): password = validated_data.pop('password') user = CustomUser(**validated_data) user.set_password(password) user.save() return user` `#views.py class RegisterUserAPIView(generics.CreateAPIView): queryset = CustomUser.objects.all() permission_classes = (AllowAny,) serializer_class = CustomUserSerializer def perform_create(self, serializer): serializer.save(created_by=self.request.user)` -
Django database image stopped showing
The image from the django database was showing fine on the home page and the detail page of my project. But later when I clicked on the product image from the home page, the image disappeared on the detail page. The only data that get displayed are product name and product price but not product image. What could be the cause? [detail image] [image on home page]database model detail page viewview for home pagr I change the database from sqlite3 to postgreSql because I thought it could be the cause but it didn't work. I installed Pillow but it is still the same, it didn't work. -
Need help understanding working of react build artifacts in Django project
I have a Django backend in which I have pasted build directory of react project (after running npm run build). I see a bunch of web pages of react project opening when opened through code, i.e. <Link className='dropdown-item' to='/customer/dashboard'>Dashboard</Link> opens the component routed by <Route path="/customer/dashboard" element={<Dashboard />} /> (i.e. Dashboard component launches). But if I update the URL to http://127.0.0.1:8000/customer/dashboard or even refresh the page with the aforementioned URL, I get 404 error. I also have another problem where some of the pages don't even open through code. So I am wondering why this could be. Following is the code snippets I have in urls.py (Django project) path('api/token/refresh/', jwt_views.TokenRefreshView.as_view(), name='token_refresh'), path('', views.index, name = 'index'), views.py from django.views.generic import TemplateView from django.views.decorators.cache import never_cache index = never_cache(TemplateView.as_view(template_name='index.html')) -
I am doing predictive models with classifications with sklearn and keep getting the same error "Supported target types are: ('binary', 'multiclass') [closed]
I am using the following classification models: linear regression logistic regression KNeighborsClassifier DecisionTreeClassifier I am trying to make some prediction models and every time I try to use anything but the sex attribute from my dataset I get this error "Supported target types are: ('binary', 'multiclass'). Got 'continuous' instead." The majority of my data is continuous but I'm sure I'm doing something else wrong ill show some examples: from sklearn.linear_model import LinearRegression,LogisticRegression import seaborn import pandas data = pandas.read_pickle("processed/processeddata.pkl.gz") data = data[data["visit"] == 1] x = data. Drop(["ID","visit","MMSE",],axis = 1) y= data.MMSE #both these below give the same error classifier = LogisticRegression(multi_class="ovr") classifier = KNeighborsClassifier() imputer = impute.SimpleImputer() scaler = preprocessing.StandardScaler() p = pipeline.make_pipeline(imputer,scaler,classifier) cv = model_selection.StratifiedKFold(5,shuffle=True,random_state = SEED) #this is the line of the error scores = model_selection.cross_val_score(p, x, y,scoring="f1_macro",cv=cv) X = delay sex age YOE SES CDR eTIV nWBV ASF 0 0 1 87 14 2.0 0.0 1987.0 0.696 0.883 1 0 1 75 12 2.0 1.0 1678.0 0.736 1.046 2 0 0 88 18 3.0 0.0 1215.0 0.710 1.444 3 0 1 80 12 4.0 0.0 1689.0 0.712 1.039 4 0 1 71 16 2.0 1.0 1357.0 0.748 1.293 .. ... ... ... ... ... ... ... … -
NGINX auth_request using django
i have a NginX with protected location at 192.168.56.108, and my django app at 192.168.56.1 here is my nginx default site config server { listen 80 default_server; listen [::]:80 default_server; root /var/www/html; # Add index.php to the list if you are using PHP index index.html index.htm index.nginx-debian.html; server_name _; location /sflow-rt/ { proxy_buffering off; proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for; proxy_set_header X-Forwarded-Prefix /sflow-rt/; proxy_set_header Host $host; proxy_pass http://localhost:8008/; proxy_redirect ~^http://[^/]+(/.+)$ /sflow-rt$1; # insert access policy below auth_request /auth; } location /auth { internal ; proxy_pass http://192.168.56.1:8000/xpages/authonly; #proxy_set_header X-Forwarded-Host $host; #proxy_set_header X-Original-URL $scheme://$http_host$request_uri; #add_header Set-Cookie $auth_cookie; #auth_request_set $auth_cookie $upstream_http_set_cookie; } location / { # First attempt to serve request as file, then # as directory, then fall back to displaying a 404. try_files $uri $uri/ =404; } } And here is my django view that will called by 'proxy_pass http://192.168.56.1:8000/xpages/authonly' class authonly(FormView): template_name = 'auth_only.html' form_class = auth_only_form def get(self, request, *args, **kwargs): if request.user.is_authenticated: print(f'REQUEST USER: {request.user}') return HttpResponse('authenticated',status=200) print('Non Authenticated User') form = self.form_class() return render(request, self.template_name, {"form": form}) def form_valid(self, form): print(f'Cleaned data => {form.cleaned_data}') name = form.cleaned_data['name'] password = form.cleaned_data['password'] try : user = authenticate(username = name, password=password) login(self.request, user) return HttpResponse(status=200) except Exception as e: print(f'Failed Auth:\n\t{traceback.format_exc()}') return HttpResponse(status=400) … -
Serving images in Django that aren't part of static
I'm looking for a pattern for rendering images that aren't in static, but all of the documentation seems to require that they be in static. In my case I'd like to get the image from an Azure storage blob, but the file can't be hosted publicly. My ideal pattern is: view.py def view_my_scene(request): scene_id = request.GET.get('scene_id') context={'scene_id': scene_id} my_image = my_other_function_that_gets_image(scene_id) return render(request, "my_scene_with_an_image.html", context, my_image) And then be able to use that image, but I can't find a pattern like that. Is there a way to render images on the fly? How about if it was an image I just created? -
AttributeError: Manager isn't accessible via /2023/01/05/post-1 instances
Hi I'm adding comment section to my blog which are going to be lessons. For some reason I have this error: AttributeError at specific_lesson Manager isn't accessible via Lesson instances Error is reffering at the template: <form action="{% url 'lang_learning_app:lesson_detail' lesson.published.year lesson.published.month lesson.published.day lesson.slug %}" method="post" name="commentform" class="row comment-form"> I haven't received this error until now and I couldn't find example that is specific case to mine. urls.py path('<int:year>/<int:month>/<int:day>/<slug:lesson>/', views.lesson_detail, name='lesson_detail'), views.py def lesson_detail(request, year, month, day, lesson): lesson = get_object_or_404(Lesson, status=Lesson.Status.PUBLISHED, slug=lesson, publish__year=year, publish__month=month, publish__day=day) #comments comments = lesson.comments.filter(hide_comment=False) new_comment = None if request.method == 'POST': if request.user.is_authenticated: comment_form = CommentForm(data=request.POST) if comment_form.is_valid(): new_comment=comment_form.save(commit=False) new_comment.lesson = lesson new_comment.author = request.user new_comment.save() return redirect(lesson.get_absolute_url()) #redirect here else: messages.warning(request, 'You need to be logged in to add a comment.') else: if request.user.is_authenticated: comment_form = CommentForm(initial={'author':request.user}) else: comment_form = CommentForm() ....# other code return render(request, 'lessons/detail_lesson.html', {'lesson': lesson, 'similar_lessons': similar_lessons, 'comments':comments, 'new_comment':new_comment}) models.py class Lesson(models.Model): class Status(models.TextChoices): DRAFT = 'DF', 'Draft' PUBLISHED = 'PB', 'Published' title = models.CharField(max_length=250) slug = models.SlugField(max_length=250, unique_for_date='publish') author = models.ForeignKey(User, on_delete=models.CASCADE, related_name='blog_posts') body = models.TextField() tags = TaggableManager() publish = models.DateTimeField(default=timezone.now) created = models.DateTimeField(auto_now_add=True) updated = models.DateTimeField(auto_now=True) status = models.CharField(max_length=2, choices=Status.choices, default=Status.DRAFT) objects = models.Manager() published = … -
Django app hosted in Apache running on Windows - service won't start
So out of a massive haystack of similar issues, this article is the closest thing to a needle, that I could find. But its accepted answer (submitted by the OP) is far short of complete. And even the better researched upvoted answer misses something that I'm hitting. The situation is, I've got a Django 4.2.9 project hosted in Apache 2.4 using mod_wsgi 5.0.0, all on a Windows 2016 Server. When I run Apache from the command line of the server's Administrator account, it works perfectly. When I install the Apache 2.4 service using httpd.exe -k install and then manually reconfigure the service to log on as .\Administrator, it also works perfectly. However if I run the service logging on as LocalSystem, or logging on as any other user account, the service fails to start. (Side note: I've confirmed that all accounts have the Log on as a service privilege enabled, so that's not the issue.) The error is as shown below: And also -- if I try to run httpd.exe from the command line of a different user account, the executable fails out. The generated error in the log file is: [Fri Jan 05 14:28:08.201284 2024] [wsgi:info] [pid 5712:tid 372] … -
Django/React application error when port forwarding on remote CentOS7 Apache server: 'No routes matched location "/appname"'
I am new to Django/React development and have been practicing development/deployment on a remote CentOS7 Apache server. Due to the remote nature of the server, we are using port forwarding to allow external access. I am using Django (3.2.23), React (18.2.0), CentOS7 Linux, Apache (2.4.6), Mod_WSGI (4.7.1), Webpack (5.89.0) and Python 3.6 with a virtual environment. The development server runs fine on internal port 8000, forwarded to external port 40731 (as root, ie: www.hostsite.com:40731). The issue arises when I attempt to access the final deployment through internal port 80, accessing it remotely via external port 40730 (ie: www.hostsite.com:40730/cambraatz). To be clear, this is an issue specific to 'final' deployment and NOT an issue with the local Django development server. When I attempt to visit the website, www.hostsite.com:40730/cambraatz, my index.html file is successfully running (webpage title loads accordingly) however I am served a blank white page. Developer tools is raising a 'No routes matched location "/cambraatz"' error (see snip below). Additionally, the serving of a blank page does not seem to raise any issues with Apache/Linux...code 200 in access_log and no new entries in error_log. Developer Tools Error Message, request for hostsite.com:40730/cambraatz Given the aforementioned, I believe the issue is likely … -
how do i Insert code template in django template?
I want to show a part of code in webpage like below. is there a library in django or another solution for doing this? -
404 when rendering 3D model in django template three.js
So I was following this Tutorial on how to render a 3d object. Nothing gets loaded on my webpage because it throws a 404 error on the location of the model. Now I don't know where to place this 3d model because of the django structure. So my structure is the following. home templates/home home.html <--- here I import my 3d.js script theme static js 3d.js The script is loaded in correctly so there is no problem there, I just struggle to find where to place my models directory with the 3d models in. My 3d.js looks like this. import * as THREE from "https://cdn.skypack.dev/three@0.129.0/build/three.module.js"; import { OrbitControls } from "https://cdn.skypack.dev/three@0.129.0/examples/jsm/controls/OrbitControls.js"; import { GLTFLoader } from "https://cdn.skypack.dev/three@0.129.0/examples/jsm/loaders/GLTFLoader.js"; const scene = new THREE.Scene(); const camera = new THREE.PerspectiveCamera(75, window.innerWidth / window.innerHeight, 0.1, 1000); let mouseX = window.innerWidth / 2; let mouseY = window.innerHeight / 2; let object; let controls; let objToRender = 'eye'; const loader = new GLTFLoader(); var loc = window.location.pathname; var dir = loc.substring(0, loc.lastIndexOf('/')); console.log(loc); loader.load( `/models/${objToRender}/scene.gltf`, function (gltf) { object = gltf.scene; scene.add(object); console.log('Model loaded successfully:', object); }, function (xhr) { if (xhr.total !== undefined) { console.log((xhr.loaded / xhr.total * 100) + '% loaded'); } }, function … -
Componentization in Django apps using custom template tags with script tag
I'm developing a Django project, comprising of several apps. I have a base app that contains global stuff, such as CSS, JS, custom template tags (I will call them CTTs from now on), etc. The thing is, I would like to have some CTTs that include HTML and script tags with JS code (eg. autocomplete inputs, delete button with confirmation modal, etc). My intention here is to have self-contained components to be plugged all across the project. My concern is if this would be a good practice, as I would not separate JS code in '.js' files and stuff. I tend to think that this would be ok, as the behaviour provided by JS code would be in a certain way incapsulated in the CTTs. Would like to hear opinions about this =) -
HTMX one hx-post form not working in a Django project
In my Django portfolio project, I'm stuck with one weird bug. If you like puzzles, please read... On a page with a ListView (in which I already use HTMX), a button triggers a drawer/modal in which the logged in user can talk to ChatGPT (for films recommendations). It worked fine, until one day, for no apparent reason it stopped working a few days later (I didn't touch that part of the code, I was actually getting ready to send it to GitHub and find a host). The messages were not appearing in the textbox anymore. After hours of debugging (listening to ChatGPT telling me "your code seems ok"), I figured that the problem was coming from HTMX : the ChatGPT part works, I receive the messages (visible in the terminal), and if I don't use HTMX, the conversation appears in the textbox. Now, the problem thickens as I have the EXACT same code in an other project that works. I even changed all the little details of that previous project to match the new one, in order to see when will it stop working. It works. So, the hx-post doesn't work, but it does in the rest of the website … -
How can I add a discount and tax in Stripe checkout session in Django
I'm very new to Stripe and now I'm stuck with adding my Tax and Discount models to stripe checkout session and need some help with code. this is my models.py class Order(models.Model): first_name = models.CharField(max_length=50) last_name = models.CharField(max_length=50) email = models.EmailField() address = models.CharField(max_length=250) postal_code = models.CharField(max_length=20) city = models.CharField(max_length=100) created_at = models.DateTimeField(auto_now_add=True) updated = models.DateTimeField(auto_now=True) paid = models.BooleanField(default=False) items = models.ManyToManyField(Item, through='OrderItem') discount = models.ManyToManyField(Discount, through='OrderDiscount') tax = models.ManyToManyField(Tax, through='OrderTax') class Meta: ordering = ('-created_at',) def __str__(self): return f'Order {self.id} | {self.created_at.strftime("%d.%m.%Y %H:%M")}' def get_total_cost(self): total = sum(item.price for item in self.items.all()) if self.discount.exists(): discount = sum(discount.amount for discount in self.discount.all()) if discount <= total: total -= discount if self.tax.exists(): tax = sum(tax.rate for tax in self.tax.all()) tax_amount = total * tax / 100 total += tax_amount return int(total) As you can see, currently I calculate tax and discount directly in my model. And it's doing great. But now I need to visualize taxes and discounts in stripe checkout form. So this is my class for order checkout with stripe class CreateCheckoutSessionOrderView(View): def get(self, request, *args, **kwargs): order_id = self.kwargs["order_id"] DOMAIN: str = 'http://127.0.0.1:8000' order = Order.objects.get(id=order_id) # tax_rate = sum(order.tax.rate for order.tax in order.tax.all()) # tax_name = "Taxes" … -
TemplateDoesNotExist at /index.html
I want to run just the index.html file on the / path but I am getting multiple errors. I am new to django so don't know where to resolve the error. These are the errors views.py urls.py what I expected is a landing page to URL_Shortener website. -
Testing Dynamic call to function in a loop in Django
I am trying to write test cases for a function that looks similar to what we have below and in that test case, I want to verify if a function, that is called as a variable, was called or not. def func1(): print("func1") def func2(): print("func2") def func3(): print("func3") FUNCTION_MAP_DICT = { var1: func1, var2: func2, var3: func3 } def do_something: calls = [var1, var3] for call in calls: operation = FUNCTION_MAP_DICT[call] operation() @patch("func1") @patch("func2") @patch("func3") def test_do_something(mock_func3, mock_func2, mock_func1): mock_func1.assert_called_once() mock_func3.assert_called_once() In the above scenario, if I run the test case, I get an assertion error but if I call do_something directly, it works fine. How can I fix my test case to achieve the same result. I am using Django TestCase. AssertionError: Expected 'func1' to have been called once. Called 0 times. -
Bootstarp navbar
I don't really know much about the frontend, because I work mostly with the backend in python, but for my project I still need some kind of frontend to display data in my template, so I used bootstrap (version 4.1), please tell me how I can place the search field in the center of the navigation bar, and move the profile section to the end of the right side of the navigation bar. Example html and a screenshot of the navigation bar below {% load static %} <nav class="navbar navbar-expand-lg navbar-light bg-light" style="height: 100px;"> <a class="navbar-brand" href="#"> <img src="{% static 'home/logos/fishing_logo.svg' %}" alt="logo" width="120" height="100"> </a> <button class="navbar-toggler" type="button" data-toggle="collapse" data-target="#navbarNavAltMarkup" aria-controls="navbarNavAltMarkup" aria-expanded="false" aria-label="Toggle navigation"> <span class="navbar-toggler-icon"></span> </button> <div class="collapse navbar-collapse" id="navbarNavAltMarkup"> <div class="navbar-nav"> <a class="nav-item nav-link active" href="#"> Home <img src="{% static 'home/logos/house_logo.svg' %}" alt="logo" width="15" height="15" style="margin-bottom: 5px;"> </a> <a class="nav-item nav-link" href="#">News</a> <a class="nav-item nav-link" href="#">How to catch</a> <form class="d-flex" role="search"> <input class="form-control me-2" type="search" placeholder="Search" aria-label="Search"> <button class="btn btn-outline-success" type="submit">Search</button> </form> <li class="nav-item dropdown"> <a class="nav-link dropdown-toggle" href="#" role="button" data-bs-toggle="dropdown" aria-expanded="false"> Profile </a> <ul class="dropdown-menu"> <li><a class="dropdown-item" href="#">Log in</a></li> <li><a class="dropdown-item" href="#">Registration</a></li> <li><a class="dropdown-item" href="#">View profile</a></li> <li><a class="dropdown-item" href="#">Log out</a></li> </ul> </li> </div> </div> </nav> -
How to limit django-allauth to only give access to pre-defined social accounts
I have a B2B app written in Django. Currently all users are registered manually (no real signup page). Now I want to implement django-allauth to be able to authenticate users thru MS ADs or Google. The only limitation is, that I want to pre-define the users that can use this authentication. Is there any possibility to define these users in allauth? -
How can eliminate the migration error in Django?
When I try to migrate I get an error: django.db.migrations.exceptions.NodeNotFoundError: Migration posty.0038_remove_post_uzytkownik_post_grupa dependencies reference nonexistent parent node ('auth', '0048_alter_group_grupa_departament_and_more') Deleting folders pycache and migrations doesn't help Please help. Deleting folders pycache and migrations -
Problems using mdeditor markdown with Django
I'm trying to use the django-mdeditor plugin for markdown in my Django application, but following the documentation I was unable to implement it via form, only manually with static paths. Which brings me some questions: Why are the paths not identified on the client when loaded via form? Why when loaded manually does it cause incompatibilities with bootstrap? Should I talk to my team and migrate to ckeditor? Note: All settings described in the documentation were made (https://pandao.github.io/editor.md/en.html) Models.py class Entrega(models.Model): usuario = models.ForeignKey(User, on_delete=models.CASCADE, editable=False) descricao = MDTextField(blank=True) data_criacao = models.DateTimeField(auto_now_add=True) [...] Forms.py class EntregaForm(forms.Form): descricao = MDTextFormField () When I use just {{form}} in my template, errors are generated in the console When I manually load the paths, errors are generated in the selector-engine template [...] <link href="{% static 'mdeditor/css/editormd.min.css' %}" rel="stylesheet"> <script src="{% static 'mdeditor/js/editormd.min.js' %}"></script> <div class="mb-3" id="texteditor"><textarea class="form-control" id="descricao" name="descricao"></textarea></div> <script type="text/javascript"> $(function () { editormd("texteditor", { width : "100%", height : 500, path : "{% static 'mdeditor/js/lib/' %}", htmlDecode : "style,script,iframe", tex : true, emoji : true, taskList : true, flowChart : true, sequenceDiagram : true, placeholder : '' }); }) </script> -
Django Migrations Not Using Configured Database Connection
I am using supabase postgresql along with django. By default it uses the public schema, but now I want to link the user_id field in model to auth.users.id where auth is the schema, users is the table name and id is the UUID field Models definition here # auth/models.py class SupabaseUser(models.Model): id = models.UUIDField( primary_key=True, default=uuid.uuid4, verbose_name="User ID", help_text="Supabase managed user id", editable=False, ) class Meta: managed = False db_table = "users" # myapp/models.py class MyModel(models.Model): user = models.ForeignKey( SupabaseUser, on_delete=models.CASCADE, verbose_name="Supabase User", help_text="Supabase user associated with the screenshot account", null=False, ) In the settings I have two database connections DATABASES = { "default": dj_database_url.config(), "supabase_auth": dj_database_url.config(), } DATABASES["supabase_auth"]["OPTIONS"] = { "options": "-c search_path=auth", } And of course model router is configured as from django.db.models import Model from django.db.models.options import Options class ModelRouter: @staticmethod def db_for_read(model: Model, **kwargs): return ModelRouter._get_db_schema(model._meta) @staticmethod def db_for_write(model: Model, **kwargs): return ModelRouter._get_db_schema(model._meta) @staticmethod def allow_migrate(db, app_label, model: Model, model_name=None, **kwargs): return True @staticmethod def _get_db_schema(options: Options) -> str: if options.app_label == "auth": return "supabase_auth" return "default" When I use the ./manage.py shell and run the following script, it works from auth.models import SupabaseUser assert SupabaseUser.objects.count() == 1 But when I apply migration for myapp, I …