Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Django combing multiple managers from inherited classes
I have model that inherits from 2 abstract classes with overridden managers: class ManagerA(models.Manager): def get_queryset(self): return super().get_queryset().filter(attrA="A") class A(models.Model): objects = ManagerA() class Meta: abstract = True class ManagerB(models.Manager): def get_queryset(self): return super().get_queryset().filter(attrB="B") class B(models.Model): objects = ManagerB() class Meta: abstract = True class Main(A, B): pass How to override manager in Main class, that it combines both filters from ManagerA and ManagerB? I want ot have something like: Main.objects.all() -> works like Main.objects.filter(attrA="A", attrB="B") -
django Direct assignment to the forward side of a many-to-many set is prohibited. Use user.set() instead
hi i have aproject in django when i try to runserver the message above is shwon this is models.py fo class Display(models.Model) : url=models.URLField(unique=True) text = models.CharField(max_length=150) class Display_Data(models.Model) : displays = models.ManyToManyField(Display) user= models.ManyToManyField(User) choosenum=models.IntegerField() puplish_date =models.DateTimeField(default=datetime.now) and this the view.py tdef submit_operation(request): if request.method == 'POST': url = request.POST.get('url') text = request.POST.get('title') choosenum = request.POST.get('CHOOSE') if Display.objects.filter(url=url).exists(): display = Display.objects.get(url=url) display_data = Display_Data.objects.create(choosenum=choosenum, user=request.user, date_published=datetime.now()) display_data.displays.add(display) else: display = Display.objects.create(url=url, text=text) display_data = Display_Data.objects.create(choosenum=choosenum, user=request.user, date_published=datetime.now()) display_data.displays.add(display) # ... (إعادة توجيه المستخدم) #return redirect('searchpage') return redirect(request.META.get('HTTP_REFERER'))ype herea `and when i try to refer to vidion saved before the message above abeer i make a site show video from youtube in a frame and asked a user to value the vidio i saved vidio url and when i want from user to again evluate the vidio the mistake apeer -
Html template from contributions-django libraty not rendering properly
I want to use a GitHub-like contributions calendar in my Django project. After a quick research, I found the contributions_django library. After some problems, I managed to install it, but even after following the instructions, the contributions graph does not load properly on the page. What should be an empty contributions graph looks like this: First I imported the library to my views.py file: from contributions_django.graphs import generate_contributors_graph Then I used 'generate_contributions_graph' method in my view: contributions = [] calendar = generate_contributors_graph(contributions, title="Decks reviews") return render(request, "myapp/user_stats.html", {"calendar":calendar} Finally, I placed this line of code in the "user_stats" HTML template: {% include "contributions_django/graph.html" %} And that's it. It should display an empty graph, but it doesn't. I also tried to insert some dates in the "calendar", but it didn't work; nothing changed: today = timezone.now() last_week = today - timedelta(days=7) contributions = [last_week, today] calendar = generate_contributors_graph(contributions, title="Decks reviews") If you have any idea what the cause of the problem might be, please help. Thanks in advance. -
directly compute a geohash with django without creating a model
is it possible to use this GeoHash class directly without creating a model on a db? e.g.: from django.contrib.gis.geos import Point from django.contrib.gis.db.models.functions import GeoHash p = Point(x=lon, y=lat, srid=4326) geohash_str = GeoHash(p).??? # i want the actual geohash string here -
White screen while trying to make auth through google in Django project
I followed this guide https://www.photondesigner.com/articles/google-sign-in?ref=yt-google-sign-in First of all, I could not create button through the https://developers.google.com/identity/gsi/web/tools/configurator, but I copied the code from guide and changed the client id, but anyway I get this, when I click the button to auth through google after clicking the google auth button I tried to follow the guide, but it didn't help. Maybe someone got the same problem and know how to fix it -
Django REST Authentication credentials were not provided
I'm developing an API using Django Rest Framework. but when i'm trying to access the console gives me this error: @api_view(['GET']) @authentication_classes([TokenAuthentication]) @permission_classes([IsAuthenticated]) def get_all_messages(request, user_id): messages = Message.objects.filter(receiver_id=user_id) serializer = MessageSerializer(messages, many=True) return Response(serializer.data) from rest_framework_simplejwt.views import TokenObtainPairView, TokenRefreshView urlpatterns = [ path('api/token/', TokenObtainPairView.as_view(), name='token_obtain_pair'), path('api/token/refresh/', TokenRefreshView.as_view(), name='token_refresh'), path('admin/', admin.site.urls), path('api/get-all-messages/<int:user_id>/', get_all_messages), ] REST_FRAMEWORK = { 'DEFAULT_RENDERER_CLASSES': [ 'rest_framework.renderers.JSONRenderer', 'rest_framework.renderers.BrowsableAPIRenderer', ], 'DEFAULT_AUTHENTICATION_CLASSES': [ # Corrected typo here 'rest_framework.authentication.TokenAuthentication', ], 'DEFAULT_PERMISSION_CLASSES': [ 'rest_framework.permissions.IsAuthenticated', ] } http://localhost:8000/api/token/ copy the token I have searched but they say to change the REST_FRAMEWORK's AUTHENTICATION PERMISSIONS which I have done as you can see, but to no avail. -
Drawbacks of customer save method to avoid user getting a userprofile_id with a specific value. (Django/Heroku)
In my Django project, I need to avoid users creating a userprofile_id with a value of 3 (3, 13, 203...). This is an interim workaround another issue which will probably take longer to result. I posted the code below. But my question relates more to the drawbacks of this interim fix. What sort of problem could this generate. This is the list I came up with and my answers to each of them: User_id will be different than userprofile_id - cant see any problems here. Affect to database integrity when custom method is removed - I cannot see how the remove of the method would affect the database. Hopefully I am right.; Some performance issue - The save is at the database level which might cause some delays I suppose. This is for a pilot+. I dont expect 1000s of new users a day. Could two users who signup at the same time end up with the same userprofile_id? Would there be a wait to limit potential of deadlocks? the code for those who are curious: class UserProfile(models.Model): user = models.OneToOneField(User, null=True, on_delete=models.CASCADE) def __str__(self): return str(self.user) def save(self, *args, **kwargs): if not self.pk: # Logic for generating userprofile_id without … -
How can I diagnose slow response times from Google App Engine and Django to serve a web app?
I've deployed a Django based portfolio website - http://johnmcgurk.no - on App Engine and I am struggling to diagnose why one app has such a poor response time. When running google PageSpeed Insights the "core" app on the root url has an initial server response time of ~6s, while the secondary app (an e commerce demo) has a still bad, but much better response time of around 0.8s. The app uses Google Cloud SQL with Postgres 14 for the database, and a Google Image bucket to serve the static and image files. I'm completely new to hosting webapps, so an advice is much appreciated, thank you in advance! I've searched online for tools to help me diagnose where the bottleneck is, and have run the website on my local machine using google-sql-proxy in an attempt to rule out the database as the root of the issue (also the e commerce site uses far more database queries), and haven't managed to find anything of use. -
Django: POST request returns GET not allowed
I have a page which requires a POST request: When I click on POST at the bottom, which presumably makes a POST request, I get the same error as when I make a GET request, which you can see at the top: "detail": "Method \"GET\" not allowed." Why does Django think my POST request is a GET request? Thank you. PS The login credentials I have provided exist. When I provide incorrect credentials I get an error telling me that. -
Using django-tinymce inline with its configuration
I'm using django-tinymce and have it successfully working on Django Admin fields, and fields in standard non-Admin forms, to update an object. I'm now trying to use it "inline" and, while this submits and saves, it doesn't use django-tinymce's configuration – specified in my settings.py – like the others. I have a Django form like this: class TestModelInlineUpdateForm(forms.ModelForm): class Meta: model = TestModel fields = ("description",) widgets = {"description": TinyMCE()} And my template contains: <form method="post" id="testForm"> {% csrf_token %} {{ form.media }} <div class="tinymce" id="inline-editor"> {{ object.description|safe }} </div> {% for hidden in form.hidden_fields %} {{ hidden }} {% endfor %} <input type="hidden" name="description" value=""> <button type="submit">Update</button> </form> <script type="text/javascript"> tinymce.init({ selector: '#inline-editor', inline: true }); // Set the description field to the new HTML on form submission. document.querySelector("#testForm").addEventListener("submit", function(ev) { ev.preventDefault(); let descriptionHTML = document.querySelector("#inline-editor").innerHTML; let descriptionField = document.querySelector("input[name='description']"); descriptionField.value = descriptionHTML; this.submit(); }); </script> I had to make up that last bit of JS, that ensures the edited HTML is copied from TinyMCE to the hidden form field and, while that works, I feel there is probably a better way? On page load the console is showing: SyntaxError: JSON Parse error: Unexpected identifier "undefined" which probably isn't … -
Use wagtail form into other templates
So I have created a Form with the Wagtail Form Builder and works well. Now I want to use the created from into other templates throughout my project. I have originally created the form for the Contact Page, but now I want this same form to be use in other templates such as lets say a Blog Page, under the post as a contact form. Is there any way to do that? Thanks a lot! I dont know where to start because i cant really bring the ID or value of the specific form. -
Django is unable to connect to your MySQL server running on 'localhost' at port 3306
enter image description here enter image description here can any one help me with this error ? and i tried many ways but still there is issue with my sql server, django is not getting connected to sql server ! Expecting resolution. -
Unable to get both access and refresh cookies in http only cookies
I'm creating a Django jwt authentication web app and I am trying to get both access and refresh tokens via HTTP-only cookies. But the front end can only get the refresh token, not the access token so I can't log in. Frontend is done in React and I have used {withCredentials: true} yet I only get a refresh token, not the access token Authentication.py file import jwt, datetime from django.contrib.auth import get_user_model from django.utils import timezone from django.conf import settings from rest_framework import exceptions from rest_framework.authentication import BaseAuthentication, get_authorization_header User = get_user_model() secret_key = settings.SECRET_KEY class JWTAuthentication(BaseAuthentication): def authenticate(self, request): auth = get_authorization_header(request).split() if auth and len(auth) == 2: token = auth[1].decode('utf-8') id = decode_access_token(token) user = User.objects.get(pk=id) return (user, None) raise exceptions.AuthenticationFailed('Unauthenticated') def create_access_token(id): return jwt.encode({ 'user_id': id, 'exp': timezone.now() + datetime.timedelta(seconds=60), 'iat': timezone.now() }, 'access_secret', algorithm='HS256') def decode_access_token(token): try: payload = jwt.decode(token, 'access_secret', algorithms='HS256') return payload['user_id'] except: raise exceptions.AuthenticationFailed('Unauthenticated') def create_refresh_token(id): return jwt.encode({ 'user_id': id, 'exp': timezone.now() + datetime.timedelta(days=10), 'iat': timezone.now() }, 'refresh_secret', algorithm='HS256') def decode_refresh_token(token): try: payload = jwt.decode(token, 'refresh_secret', algorithms='HS256') return payload['user_id'] except: raise exceptions.AuthenticationFailed('Unauthenticated') views.py file import random import string from django.contrib.auth import get_user_model from .models import UserTokens, PasswordReset from django.http import JsonResponse from rest_framework.views … -
Not having write permissions for a file in a docker container
Every time I want to edit and save a file using a text editor like Sublime Text or VS Code, it requires my password. The files are part of a Django project in a docker container. Only the root user has write permissions. How can I set this so it doesn't require password? Also there's a lock icon on the project folders that have this problem. I tried adding my user to docker group to solve this problem but it didn't resolve. -
Is there any way in Python to run code with parameters from string variable?
I'm developing website with interactable algorithms. The problem is that i get code as string from database and i need to execute it with parameters that came from user interface. Is there any Python library that can solve this problem? I'm new to Python and Django and I don't really know is this possible or not. Example of code: class CombinationColex: def __init__(self, n, k): self.total_elements = n self.combination_size = k self.combination_array = [0] * (self.combination_size + 1) self.combination_array[self.combination_size] = self.total_elements + 2 self.first() def first(self): for i in range(self.combination_size): self.combination_array[i] = i def next(self): if self.combination_array[0] == self.total_elements - self.combination_size: self.first() return self.combination_size j = 0 while self.combination_array[j + 1] - self.combination_array[j] == 1: self.combination_array[j] = j j += 1 self.combination_array[j] += 1 return j def data(self): return self.combination_array[:-1] def Start(self): while True: for i in range(self.total_elements): present = i in self.data() print("1" if present else "0", end="") print() if self.next() == self.combination_size: break combination_generator = CombinationColex(n, k) combination_generator.Start() -
django.core.exceptions.AppRegistryNotReady: Apps aren't loaded yet, on django channels
My app run both using HTTP and Websocket using django channels. I am preparing for deployment and yet when I run daphne MarketPlace.asgi:application it throws this error. I am not sure if I had circular imports because my User model has been used a lot on other models from other applications. Traceback (most recent call last): File "/home/luser/.local/share/virtualenvs/MarketPlace-8dI9Cb42/bin/daphne", line 8, in <module> sys.exit(CommandLineInterface.entrypoint()) File "/home/luser/.local/share/virtualenvs/MarketPlace-8dI9Cb42/lib/python3.10/site-packages/daphne/cli.py", line 171, in entrypoint cls().run(sys.argv[1:]) File "/home/luser/.local/share/virtualenvs/MarketPlace-8dI9Cb42/lib/python3.10/site-packages/daphne/cli.py", line 233, in run application = import_by_path(args.application) File "/home/luser/.local/share/virtualenvs/MarketPlace-8dI9Cb42/lib/python3.10/site-packages/daphne/utils.py", line 17, in import_by_path target = importlib.import_module(module_path) File "/usr/lib/python3.10/importlib/__init__.py", line 126, in import_module return _bootstrap._gcd_import(name[level:], package, level) File "<frozen importlib._bootstrap>", line 1050, in _gcd_import File "<frozen importlib._bootstrap>", line 1027, in _find_and_load File "<frozen importlib._bootstrap>", line 1006, in _find_and_load_unlocked File "<frozen importlib._bootstrap>", line 688, in _load_unlocked File "<frozen importlib._bootstrap_external>", line 883, in exec_module File "<frozen importlib._bootstrap>", line 241, in _call_with_frames_removed File "/home/luser/Desktop/MarketPlace/./MarketPlace/asgi.py", line 11, in <module> from chats.routing import websocket_urlpatterns File "/home/luser/Desktop/MarketPlace/./chats/routing.py", line 3, in <module> from . import consumers File "/home/luser/Desktop/MarketPlace/./chats/consumers.py", line 10, in <module> from .models import Conversation, Message File "/home/luser/Desktop/MarketPlace/./chats/models.py", line 8, in <module> from accounts.models import User File "/home/luser/Desktop/MarketPlace/./accounts/models.py", line 4, in <module> from django.contrib.auth.models import AbstractUser File "/home/luser/.local/share/virtualenvs/MarketPlace-8dI9Cb42/lib/python3.10/site-packages/django/contrib/auth/models.py", line 3, in <module> from django.contrib.auth.base_user import … -
Chained ModelSelect2Widget
I have these models: from django.db import models class ValidationCheckType(models.Model): name = models.CharField(max_length=255) nicename = models.CharField(max_length=255) description = models.CharField(max_length=255, blank=True) def __str__(self): return self.nicename class ValidationCheckTarget(models.Model): name = models.CharField(max_length=255) nicename = models.CharField(max_length=255) type = models.ForeignKey('ValidationCheckType', on_delete=models.PROTECT) def __str__(self): return ' - '.join([self.type.nicename, self.nicename]) class DirectiveCheck(models.Model): directive = models.ForeignKey(Directive, on_delete=models.CASCADE) check_type = models.ForeignKey(ValidationCheckType, on_delete=models.PROTECT, related_name='types') check_target = models.ForeignKey(ValidationCheckTarget, on_delete=models.PROTECT, related_name='targets') target_value = models.CharField(max_length=255, blank=True) So, ValidationCheckType represents the top-level category, filtering ValidationCheckTarget choices to ensure only relevant targets are displayed based on the selected type. Or so it should be. Now to the forms. According to django_select2.forms.ModelSelect2Widget and customizing-a-form I should be able to do something like this: from django import forms from django_select2 import forms as s2forms from .models import DirectiveCheck, ValidationCheckTarget, ValidationCheckType class DirectiveCheckForm(forms.ModelForm): class Meta: model = DirectiveCheck fields = ['check_type', 'check_target', 'target_value'] widgets = { 'check_type': s2forms.ModelSelect2Widget( model=ValidationCheckType, search_fields=['nicename__icontains'], ), 'check_target': s2forms.ModelSelect2Widget( model=ValidationCheckTarget, search_fields=['nicename__icontains'], dependent_fields={'check_type': 'id'}, max_results=10, attrs={ "data-minimum-input-length": 0, "data-placeholder": "Select a check_type first", } ) } The good news is, the check_type dropdown works. The bad news is, the check_target dropdown does not. It does not filter the results according to the selection in check_type. If I access the auto-generated AJAX URL created by the … -
django-python3-ldap Auth only specific groups
Hoping someone can help me debug an issue I have using django-python3-ldap. I have been able to get authentication working but need to be able to only authenticate users that are in a specific AD Group ("BI - Admin" within MSBI), Here is my code that is working (for authenticating all users) Settings.py: `AUTHENTICATION_BACKENDS = ["django_python3_ldap.auth.LDAPBackend"] #AUTH_LDAP_SERVER_URI = "LDAP://SERVERNAME" LDAP_AUTH_URL = ["LDAP://SERVERNAME:389"] LDAP_AUTH_USE_TLS = False import ssl LDAP_AUTH_TLS_VERSION = ssl.PROTOCOL_TLSv1_2 LDAP_AUTH_SEARCH_BASE = "cn=users,dc=DOMAIN,dc=org" LDAP_AUTH_OBJECT_CLASS = "user" LDAP_AUTH_USER_FIELDS = { "username": "sAMAccountName", "first_name": "givenName", "last_name": "sn", "email": "mail", } LDAP_AUTH_USER_LOOKUP_FIELDS = ("username",) LDAP_AUTH_CLEAN_USER_DATA = "django_python3_ldap.utils.clean_user_data" LDAP_AUTH_SYNC_USER_RELATIONS = "django_python3_ldap.utils.sync_user_relations" from apprum.ldap_filters import custom_format_search_filters LDAP_AUTH_FORMAT_SEARCH_FILTERS = "apprum.ldap_filters.custom_format_search_filters" LDAP_AUTH_FORMAT_USERNAME = "django_python3_ldap.utils.format_username_active_directory_principal" LDAP_AUTH_ACTIVE_DIRECTORY_DOMAIN = "domain.org"` ldap_filters.py : ` from django_python3_ldap.utils import format_search_filters def custom_format_search_filters(ldap_fields): #ldap_fields["memberOf"] = "BI - Admin" search_filters = format_search_filters(ldap_fields) # Advanced: apply custom LDAP filter logic. #search_filters.append("(|(memberOf=BI - Team))") #search_filters.append("(&(memberOf=cn=BI - Admin,OU=MSBI,DC=mookynet,dc=org))") # All done! print(search_filters) return search_filters ` **Structure of Active Directory:** Domain.org Groups |---MSBI |---BI - Admin Users |--- Adam.Wally "Adam.Wally" is a user in my test AD and a member of BI - Admin. So in theory that account should be authenticated.. Well, Thats what I am aiming for, If I uncomment ldap_fields["memberOf"] = "BI - Admin", I get … -
Invalid block tag on line 126: 'set', expected 'empty' or 'endfor'. Did you forget to register or load this tag?
i want to use {% set … } but it has problem is django.template.exceptions.TemplateSyntaxError: Invalid block tag on line 126: ‘set’, expected ‘empty’ or ‘endfor’. Did you forget to register or load this tag? what should i do ? <div class="carousel-inner"> {% for knowledge in knowledges %} {% set count = 0 %} {% for photo in photo01s %} {% if photo.category01 == knowledge %} {% set count = count + 1 %} <div class="carousel-item {% if forloop.first %}active{% endif %}"> <div class="row"> <div class="card" style="background-image: url('{{ photo.image01.url }}');"></div> </div> </div> {% endif %} {% endfor %} {% endfor %} </div> i have tried several ways but it does not work. -
Send Zip as a response in Django Rest framework
I am creating Barcodes in an API inj both png as well as pdf format and then trying to compress them and send them as zip file in response, for that I am doing this: class DownloadBarcodeImageAPIViewV2(APIView): # permission_classes = (permissions.IsAuthenticated,) def convert_image_to_pdf(self, image_path): image = Image.open(image_path) pdf_path = os.path.splitext(image_path)[0] + '.pdf' image.convert('RGB').save(pdf_path) return pdf_path def get(self, request): obj_relative_url = self.request.user.company.branding_logo.document obj_url = obj_relative_url.url po_id = request.GET['po'] company = request.user.company.pk barcodes = CompanyBarcodes.objects.filter( po_id=po_id, company=company, ).prefetch_related('company', 'product', 'grn_id', 'asn_id', 'itemGroup') items = [] for i in barcodes: items.append({'bar': i.barcode, 'name': str(i.product.name) + " - " + str(i.product.sku)}) zip_buffer = io.BytesIO() # Create a BytesIO buffer to hold the zip file with zipfile.ZipFile(zip_buffer, 'a', zipfile.ZIP_DEFLATED, False) as zipf: for item in items: EAN = barcode.get_barcode_class('code128') d = {'module_width': 0.15, 'module_height': 2.0, 'quiet_zone': 0.5, 'text_distance': 1.5, 'font_size': 3, 'text_line_distance': 3, 'dpi': 900} w = ImageWriter(d) ean = EAN(item['bar'], writer=ImageWriter()) a = ean.save("{} - {}".format(item['name'], item['bar']), options=d) pdf_path = self.convert_image_to_pdf(a) zipf.write(pdf_path, os.path.basename(pdf_path)) # Add PDF to the zip file zip_buffer.seek(0) # Move the cursor to the beginning of the buffer zip_data = base64.b64encode(zip_buffer.getvalue()).decode() # Encode the zip buffer as base64 return HttpResponse(zip_data, content_type='application/zip') # Return the zip file in the response and the … -
persian slug in django urls in page start with persian slug address
when I use persian slug to get my post details I have a special problem.. in the pages with persian slug urls in the page start with corrent page address like this : in the page : example.com/سلام-دنیا when I click on the signUp button istead of this url: example.com/signUp is example.com/سلام-دنیا/signUp with english slug everything ok and working great and whole this proccess is ok in the my localhost but on the cpanel host This problem occurs. my urls.py posts app : `from django import urls from django.urls import path , re_path from . import views urlpatterns = [ path('', views.posts , name='posts'), path('new_post/', views.new_post , name='new_post'), re_path(r'(?P<slug>[^/]+)/?$', views.post, name="post"), ]` in my template: ` <a class="btn btn-sm btn-outline-secondary" href="{%url "login"%}">عضویت/ورود</a> my post function in views.py in posts app: import os from uuid import uuid4 from django.shortcuts import render , redirect from django.contrib import messages from config import settings from posts.forms import CommentForm, PostCreatorFrom from .decorators import user_is_superuser from posts.utils import paginatePosts, searchPosts from .models import Category, Comment, Post from django.core.paginator import Paginator from django.views.decorators.csrf import csrf_exempt from django.http import JsonResponse from pathlib import Path from urllib.parse import unquote from django.views.decorators.http import require_POST from django.utils.text import slugify from django.utils.encoding … -
Define return value after chained mocks
I am using unittest.mock to test my Django application. The set-up is the following: I want to test a function foo foo uses a method X which is a constructor from an external package X is called in foo with some parameters argsA to return an object x x.create_dataset is called in foo with some parameters argsB to return an object ds ds.load is called in foo with some parameters argsC to store data in ds.data ds.data is manipulated (merge, agg...) in foo to create the return value of foo I want to test that the function foo works as expected, knowing the return values of the other functions calls given argsA, argsB, argsC. At the moment, I can't even run my test as I have a TypeError when ds.data is being manipulated : TypeError: expected pandas DataFrame or Series, got 'MagicMock' -
How to use multiple databases in a single Django app?
I'm trying to set up my Django application to use multiple databases within a single app. I have defined different database in my settings.py I have only one app polls. DATABASES = { 'default': { 'ENGINE': 'django.db.backends.mysql', 'NAME': 'mypage', 'USER': 'root', 'PASSWORD': '', 'HOST': 'localhost', 'PORT': '3306', }, 'ringi_db':{ 'ENGINE': 'django.db.backends.mysql', 'NAME': 'ringi', 'USER': 'root', 'PASSWORD': '', 'HOST': 'localhost', 'PORT': '3306', }, } I have added mapping in settings.py DATABASE_APPS_MAPPING = { 'ringi':'ringi_db', } database router is defined like this class dbrouter: def db_for_read(self, model, **hints): if model._meta.app_label == 'ringi': return 'ringi_db' else: return None def db_for_write(self, model, **hints): if model._meta.app_label == 'ringi': return 'ringi_db' else: return None def allow_relation(self, obj1, obj2, **hints): if obj1._meta.app_label == 'ringi' or obj2._meta.app_label == 'ringi': return True return None def allow_migrate(self, db, app_label, model_name=None, **hints): if app_label == 'ringi': return db == 'ringi_db' return None models.py #### Book table should be stored in mypage db #### class Book(models.Model): title = models.CharField(max_length=100) author = models.CharField(max_length=100) publication_date = models.DateField() isbn = models.CharField(max_length=13) def __str__(self): return self.title class Meta: db_table = 'book' # Member table should be stored in ringi db # class Member(models.Model): name = models.CharField(max_length=100) email = models.EmailField(unique=True) address = models.CharField(max_length=255) def __str__(self): return self.name … -
Relation does not exist when running Django Unit Tests
I am having trouble running unit tests in my django app when it is running through Jenkins. I have a CI/CD pipeline which runs python manage.py test which is currently failing with the error: django.db.utils.ProgrammingError: relation "auth_user" does not exist. Running tests locally works fine and the test database is normally created and the tests are ran normally. I SSH-ed into the server where Jenkins is set up to try and manually run the tests but I get the same results, so I wouldnt' say it's anything Jenkins specific. The postgres user has all privileges and CREATEDB on the database so postgres side seems to all be good. This is the complete exception: Traceback (most recent call last): File "/home/agent/jenkins/workspace/INP-Backend/venv/lib/python3.9/site-packages/django/db/backends/utils.py", line 89, in _execute return self.cursor.execute(sql, params) psycopg2.errors.UndefinedTable: relation "auth_user" does not exist The above exception was the direct cause of the following exception: Traceback (most recent call last): File "/home/agent/jenkins/workspace/INP-Backend/manage.py", line 22, in <module> main() File "/home/agent/jenkins/workspace/INP-Backend/manage.py", line 18, in main execute_from_command_line(sys.argv) File "/home/agent/jenkins/workspace/INP-Backend/venv/lib/python3.9/site-packages/django/core/management/__init__.py", line 446, in execute_from_command_line utility.execute() File "/home/agent/jenkins/workspace/INP-Backend/venv/lib/python3.9/site-packages/django/core/management/__init__.py", line 440, in execute self.fetch_command(subcommand).run_from_argv(self.argv) File "/home/agent/jenkins/workspace/INP-Backend/venv/lib/python3.9/site-packages/django/core/management/commands/test.py", line 24, in run_from_argv super().run_from_argv(argv) File "/home/agent/jenkins/workspace/INP-Backend/venv/lib/python3.9/site-packages/django/core/management/base.py", line 402, in run_from_argv self.execute(*args, **cmd_options) File "/home/agent/jenkins/workspace/INP-Backend/venv/lib/python3.9/site-packages/django/core/management/base.py", line 448, in execute output = … -
Problems between django and django-filter
My problem is that the django-filter library does not work correctly with the choice fields in django rest framework: model: class Incident(models.Model): caller = models.ForeignKey( 'core.Caller', verbose_name='caller', on_delete=models.PROTECT, related_name='incidents', blank=True, null=True, ) declarant = models.ForeignKey( 'core.Declarant', verbose_name='declarant', on_delete=models.CASCADE, related_name='incidents', blank=True, null=True, ) kind = models.ForeignKey( IncidentKind, verbose_name='kind', on_delete=models.SET_NULL, related_name='incidents', blank=True, null=True, ) duplicate_of = models.ForeignKey( 'self', verbose_name='duplicate', on_delete=models.CASCADE, related_name='duplicates', blank=True, null=True, ) source = models.CharField( 'source', max_length=255, default=consts.IncidentSource.APP, choices=consts.IncidentSource.CHOICES, ) status = models.CharField( 'status', max_length=255, choices=consts.IncidentStatus.CHOICES, default=consts.IncidentStatus.REQUEST_112, ) filter: class Incident(django_filters.FilterSet): description = django_filters.CharFilter(lookup_expr='icontains') declarant_phone = django_filters.CharFilter(field_name='declarant__phone', lookup_expr='icontains') incident_address = django_filters.CharFilter(field_name='address__full_address', lookup_expr='icontains') source = django_filters.ChoiceFilter(choices=consts.IncidentSource.CHOICES, lookup_expr='icontains') status = django_filters.ChoiceFilter(choices=consts.IncidentStatus.CHOICES, lookup_expr='icontains') service = django_filters.Filter(method='filter_service') address_caller = django_filters.CharFilter(field_name='caller__address', lookup_expr='icontains') victims = django_filters.BooleanFilter(method='filter_victims') death = django_filters.BooleanFilter(method='filter_death') dt_create = django_filters.Filter(method='filter_dt_create') incident_moment = django_filters.Filter(method='filter_incident_moment') class Meta: model = models.Incident fields = [ 'is_needs_reaction', 'is_social_significant', 'is_risk_emergency', 'description', 'declarant_phone', 'status', 'source', 'operator', 'incident_address', 'kind', 'service', 'address_caller', 'victims', 'death', 'dt_create', ] Source and status choices field. Error: super()._set_choices(value) AttributeError: 'super' object has no attribute '_set_choices' If I use CharFilter, then the filtering works, but not quite as it should source = django_filters.CharFilter(choices=consts.IncidentSource.CHOICES, lookup_expr='icontains') status = django_filters.CharFilter(choices=consts.IncidentStatus.CHOICES, lookup_expr='icontains') My traceback: Traceback (most recent call last): File "/core/tests/test_incident.py", line 60, in test_update response = self.client.put(self.detail_url) File "/venv/lib/python3.10/site-packages/rest_framework/test.py", line 304, in …