Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
How to write a Case() SQL expression with an aggregated field (Sum) using Django's query builder
I am trying to recreate this SQL statement using Django's query builder: CASE WHEN sum(imps) = 0 THEN NULL ELSE SUM(total_expenses) / (sum(imps) / 1000) END as "cpm" I have tried: MyModel.objects.annotate( cpm=Case( When( Sum("imps")>0, then=Sum("total_expenses") / Sum("imps"), ), default=0, output_field=FloatField(), ) ) However it doesn't work because of this TypeError '>' not supported between instances of 'Sum' and 'int'. If there was a field lookup that enabled me to do total_imps__sum__gt=0, I am sure that would solve the problem. Note: Adding Sum("imps") as an annotation (total_imps=Sum("imps")) and doing total_imps__gt=0 works but it is not an ideal solution as I would have to create multiple annotations for fields I won't need. -
Postgresql SELECT optimisation into Django ORM
Please see below a PostgreSQL SELECT statement. This presently returns around 300k rows, which is the grouped result of several million underlying rows. The dataset is only going to get larger. Using the ANALYSE EXPLAIN function the cost of this select is 111847 units. This select statement is being used in a Django ORM query set model. So the results are queried and mapped into an object. Due to the time taken for the SELECT to complete my Django application is timing out. The underlying data is made of up daily times series data, but I don't need the whole history. I am using the dataset for current day, MTD, QTD, YTD, ITD grouped values. How can I optimise this? I have been investigating indexing but am struggling to apply here. Or should I just try and re-structure the whole query? Or even build other tables to hold the aggregated results for my Django ORM to call? SELECT customers_data.position_date, customers_data.code_id, customers_data.book_id, customers_data.base_lmv, book_tags.book, book_tags.market, book_tags.employee, pnl_data.base_daily_pnl, disasters_data.disaster_5_pnl FROM ( SELECT daily_customers_holding_scenario.code_id, daily_customers_holding_scenario.position_date, daily_customers_holding_scenario.book_id, sum(daily_customers_holding_scenario.base_lmv) AS base_lmv FROM daily_customers_holding_scenario GROUP BY daily_customers_holding_scenario.position_date, daily_customers_holding_scenario.code_id, daily_customers_holding_scenario.book_id) customers_data LEFT JOIN book_tags ON customers_data.book_id = book_tags.book_id FULL JOIN ( SELECT products.position_date, products.code_id, products.book_id, sum(products.palliser_base_pnl) AS … -
I need help to solve this
I'm encountering an issue with one of my Django views, and I'm hoping someone can help me troubleshoot it. When I try to access the URL: https://tout-talent.com/forfait/, the browser or site displays a different page with the message: {"success": false, "message": "Invalid request method"} However, on my server and in the debug.log file, I see the following log entry: "GET /forfait/ HTTP/1.1" 200 indicating a 200 OK HTTP status code. But the template that should normally display is not being rendered. Here's the code for the view : @login_required def subscribe(request): if not hasattr(request.user, 'company'): print("Utilisateur non connecté ou sans compagnie associée.") return redirect('login') # Or show an appropriate message company = request.user.company print(f"Company: {company}") active_subscription = None try: active_subscription = CompanySubscription.objects.get(company=company, is_active=True) print(f"Active subscription found: {active_subscription}") except CompanySubscription.DoesNotExist: print("No active subscription found.") if request.method == 'POST': form = SubscriptionForm(request.POST) if form.is_valid(): plan = form.cleaned_data['plan'] print(f"Selected plan: {plan}") if plan.name == 'lite': print("Redirecting to Lite plan duration view.") return redirect('days_duration_for_lite_plan', plan_ref=plan.ref) else: days = plan.duration_days amount = plan.price_per_month if days >= 30 else plan.price_per_day * days print(f"Days: {days}, Amount: {amount}") if plan.name == 'free': subscription, created = CompanySubscription.objects.get_or_create( company=company, defaults={ 'plan': plan, 'start_date': timezone.now(), 'end_date': timezone.now() + timedelta(days=days), 'is_active': True, … -
How to access set of objects in reverse Foreign Key in Django
I have 2 tables defined like this: class Optimization(BaseModel): name = models.TextField(unique=True, null=False) is_active = models.BooleanField(null=False, default=True) class Meta: db_table = 'optimization' class OptimizationInput(BaseModel): name = models.TextField(null=False) optimization = models.ForeignKey(Optimization, null=False, on_delete=models.CASCADE) class Meta: db_table = 'optimization_input' I want to get some Optimizations with their inputs. I can't figure out how to access the set of OptimizationInputs I'm trying to do this: optimizations = Optimization.objects.filter(is_active=True).only('name').values('name', 'optimizationinputs_set') but I also tried this optimizations = Optimization.objects.filter(is_active=True).first() print('inputs', optimizations.optimizationinputs_set) Either way, it tells me there is no such attribute as optimizationinputs_set -
Alternative of django-boolean-switch for new version django
I used the package of django-boolean-switch for new django but it wasn't work because it is for old version. I trying to change its codes to usable for new django but it so crazing ! is there new package or new solution for this idea? -
Django Rest Framework RetrieveUpdateAPIView not working
I'm having an issue with using RetrieveUpdateAPIView and RetrieveDestroyAPIView. I'm trying to Update or Delete a Newsletter object while logged in as an administrator. Unfortunately, after clicking 'PUT' or 'DELETE', it automatically logs me out and Django Rest Framework shows an error: { "detail": "CSRF Failed: CSRF token missing." } Postman also displays an error: { "detail": "Authentication credentials were not provided." } Code below: settings.py MIDDLEWARE = [ "django.middleware.security.SecurityMiddleware", "django.contrib.sessions.middleware.SessionMiddleware", "django.middleware.common.CommonMiddleware", "django.middleware.csrf.CsrfViewMiddleware", "django.contrib.auth.middleware.AuthenticationMiddleware", "django.contrib.messages.middleware.MessageMiddleware", "django.middleware.clickjacking.XFrameOptionsMiddleware", ] REST_FRAMEWORK = { "DEFAULT_PAGINATION_CLASS": "rest_framework.pagination.LimitOffsetPagination", "PAGE SIZE": 10, "DEFAULT_FILTER_BACKENDS": [ "django_filters.rest_framework.DjangoFilterBackend", ], } serializers.py from rest_framework import serializers from core.models import Newsletter import re class NewsletterSerializer(serializers.ModelSerializer): class Meta: model = Newsletter fields = "__all__" extra_kwargs = { "created_at": { "format": "%Y-%m-%d %H:%M:%S", } } class NewsletterCreateSerializer(serializers.ModelSerializer): email = serializers.CharField( required=False, allow_blank=True, ) class Meta: model = Newsletter fields = [ "id", "created_at", "email", ] extra_kwargs = { "created_at": { "format": "%Y-%m-%d %H:%M:%S", "read_only": True, }, } def validate_email(self, email): print(email) if email == "": raise serializers.ValidationError( detail="E-mail Address is required.", ) if email and not re.match(pattern=r"(^[a-zA-Z0-9_.+-]+@[a-zA-Z0-9-]+\.[a-zA-Z0-9-.]+$)", string=email): raise serializers.ValidationError( detail="The e-mail address format is invalid.", ) if self.instance is None: if email and re.match(pattern=r"(^[a-zA-Z0-9_.+-]+@[a-zA-Z0-9-]+\.[a-zA-Z0-9-.]+$)", string=email) and Newsletter.objects.filter(email=email).exists(): raise serializers.ValidationError( detail="The newsletter already exists.", … -
custom delete action admin class in django
I want to custom delete action admin class with overwrite function delete in admin.py , but it dosn't work ! this is the error : Post with ID “<django.db.models.query_utils.DeferredAttribute object at 0x0000020BF060A450>” doesn’t exist. Perhaps it was deleted? I read and used this code at following site but it wasn't work: the site I used it class PostAdmin(admin.ModelAdmin): list_display = ('delete',) def delete(self, obj): view_name = "admin:{}_{}_delete".format(obj._meta.app_label, obj._meta.model_name) link = reverse(view_name, args=[Post.id]) html = '<input type="button" onclick="location.href=\'{}\'" value="Delete" />'.format(link) return format_html(html) -
Adding a filter to a Django Module
I'm working in a Django project. I've created a model to save the last 50 errors that happen. models.py class Error(models.Model): ERROR_TYPE_CHOICES = [ ('ERROR', 'ERROR'), ('WARNING', 'WARNING'), ] user_mail = models.CharField(max_length=500, blank=True, null=True) error_type = models.CharField(max_length=7, choices=ERROR_TYPE_CHOICES) error_message = models.CharField(max_length=1000, blank=True, null=True) error_message_detail = models.CharField(max_length=500, blank=True, null=True) created_at = models.DateTimeField(default=timezone.now) # Static field for maximum errors limit max_errors = 50 def __str__(self): return f"{self.error_type}: {self.error_message}" class Meta: ordering = ['-created_at'] # Order by descending creation date @classmethod def check_and_trim(cls): # # Obtain all errors ordered by creation date errors = cls.objects.all().order_by('-created_at') # If there are more than 50 errors, delete the older ones if errors.count() > cls.max_errors: errors_to_delete = errors[cls.max_errors:] for error in errors_to_delete: error.delete() admin.py class ErrorAdmin(admin.ModelAdmin): list_display = ('user_mail', 'error_type', 'error_message', 'error_message_detail', 'created_at') admin.site.register(Error, ErrorAdmin) So as you can see when there are more than 50 errors the oldest one is erased so that the new one can be saved. In the future maybe is needed to be saved more than 50 errors, so instead of changing the code I'd like to add a feature now so in the localhost:8000/admin/Error you can input how many errors you want to be saved. -
Forwarding messages from telegram web app
Good afternoon, now work on algorithm like user press "invite friends" button in telegram web app, then he see list of his telegram contats and choose reciever of "forwarded" message from himself, but writen by bot or web app. I wrote telegram bot on aiogramm, web app builded on django framework. Maybe someone know how to implemnt this, i tried but didnt found anything in network, maybe someone know way to implemt this (method or anything else), thaks to everyone here who can give any help! -
Best frameworks to choose for high scale web applications including databases and architectures
I'm getting started with [tag: web development] which frameworks do you recommend for designing a high scale web application should I go with java or python javascript with microservices as my backend architecture and what kind of database is best suited for these kind of highly scalable web apps sql nosql. Best pick for frontend and backend frameworks for a highly scalable web application with microservice as my backend architecture. -
TemplateDoesNotExist by inheriting LoginView
django cannot find my template but I give it correct path I make customize view for login by inheriting LoginView and form_class of AuthenticationForm from django. I give correct template_name to view but django cannot find it. I used mixin views for register and give template like this and I did'nt give error, so I check definition of LoginView and modify it's template_name to that I writed on my view class and it run without error this is my view class: class LoginAuthView(LoginView): form_class = AuthenticationForm template_name = 'login.html' success_url = reverse_lazy('accounts:test') def get_context_data(self, **kwargs): kwargs = super().get_context_data(**kwargs) if 'form' not in kwargs: kwargs['form'] = self.get_form() return kwargs def form_valid(self, form: AuthenticationForm) -> HttpResponse: response = super().form_valid(form) messages.success(self.request, f'Welcome {self.request.user}!') return response -
Using structlog with Datadog
We're using the logging module from the stdlib to send logs from our Django app to Datadog and we have customised our logging based on django-datadog-logger We're exploring a move to structlog, and I was wondering if there is a package that gives a good starting point to get log formatted for Datadog, similar to what the above library does as Datadog expects a few top level keys. Has anyone built something reusable already? Is there a recipe that we could reuse? PS: I already found the structlog Django extension, my question is more around formatting for Datadog -
What is the best approach to handle class instances in django application in a production environment?
I would like to consider 2 approaches. First, you could create a class and its instance in a class and inside views import the instance and call its methods. Second, you import the class and create instance of the class inside the view function when you handle a request. which one do you think is better. Also I am not saying about any class like , models, forms or serializer etc that are related to Django , but the ones I manually create for myself. Approach 1: Create an instance at module level and import it # utils.py class Calc: def run(self): # perform calculations return result calc_instance = Calc() # views.py from utils import calc_instance def view_function(request): result = calc_instance.run() # rest of the view logic Approach 2: Import the class and create an instance inside the view function # utils.py class Calc: def run(self): # perform calculations return result # views.py from utils import Calc def view_function(request): calc_instance = Calc() result = calc_instance.run() # rest of the view logic Also, I see Approach 1 creates a single instance that remains in memory for the lifetime of the process, at least in the development server. So based on your … -
Twig Tags are not allowed in django-html
I am Learning django , i have learnt python , html , and basic css. I was trying to sort things out, like peoples who are above 18 they can vote and peoples below 18 they cannot vote, this is a part of code of my templates/home/index.html image, You can understand the problem by seeing this output in the webpage,, I used ChatGPT to try to identify the main problem in my code, but it returned the same code, suggesting it was error-free. I also conducted a Google search, but I couldn't find a solution. Could someone please help me resolve this issue? -
How to resolve this NoReverseMatch error?
I am currently try make a task manager such that there are folders which have tasks in them, I have been stuck on this problem for hours now and am not sure at all what is the issue this is urls.py from django.urls import path from . import views app_name= 'tasks' urlpatterns = [ path('', views.folders_list,name="list"), path('new-folder/', views.folder_new,name="new-folder"), path('<slug:slug>', views.tasks_list,name="folder-page"), path('<slug:folder_slug>/<int:task_id>/', views.task_page,name="task-page"), path('new-task/', views.task_new,name="new-task"), ] this is models.py from django.db import models from django.contrib.auth.models import User # from .models import Folder # Create your models here. class Folder(models.Model): folder_id=models.AutoField(primary_key=True) title=models.CharField(max_length=75) created=models.DateTimeField(auto_now_add=True) slug=models.SlugField() author = models.ForeignKey(User, on_delete=models.CASCADE, default=None) class Task(models.Model): PRIORITY_CHOICES=[ ('LOW','LOW'), ('MEDIUM','MEDIUM'), ('HIGH','HIGH'), ] task_id=models.AutoField(primary_key=True) title=models.CharField(max_length=75) description=models.TextField() slug=models.SlugField() deadline=models.DateField() uploaded=models.DateTimeField(auto_now_add=True) author = models.ForeignKey(User, on_delete=models.CASCADE, default=None) folder = models.ForeignKey('Folder', on_delete=models.CASCADE, default=None) priority = models.CharField(max_length=10, choices=PRIORITY_CHOICES, default='LOW') def __str__(self): return self.title this is views.py from django.shortcuts import render,redirect from django.utils.regex_helper import re from .models import Task,Folder from django.contrib.auth.decorators import login_required from django.shortcuts import get_object_or_404 from . import forms # Create your views here. @login_required(login_url="/users/login/") def folders_list(request): user_folders = Folder.objects.filter(author=request.user) return render(request, 'tasks/folders_list.html', {'folders': user_folders}) #as folder_page == tasks_list.html def tasks_list(request, slug): # folder=get_object_or_404(Folder,slug=slug) folder=Folder.objects.get(slug=slug) folder_tasks = Task.objects.filter(folder=folder) return render(request, 'tasks/tasks_list.html', {'folder':folder,'tasks': folder_tasks}) def task_page(request, folder_slug, task_id): folder = get_object_or_404(Folder, slug=folder_slug) task = … -
when i am sending some data using post request in django and test it in postman it shows no error but in browser it is not responding correctly
from django.shortcuts import render from django.http import HttpResponse def register(request): if request.method == 'POST': name = request.POST['name'] #in this way we are collecting data email= request.Post['email'] password = request.Post['password'] print(f'Name :{name}') #in this way we are printing the data print(f'Email :{email}') print(f'Password :{password}') return HttpResponse('<h1> This is a post Request</h1>') elif request.method == 'GET': return HttpResponse('<h1> This is a get Request</h1>') else: return HttpResponse('<h1> This is an invalid Request</h1>') While testing in postman using post request it is showing it is a post request. But in browser it shows this is a get request why is it neglating post request -
Introducing custom-role in my Django based E-commerce application
I completed finish my Django E-commerce web-application. And now I want to add the facility of customer roles(admin,staff,merchant,customer). I'm having problems configuring this with my project. I'd really appreciate if someone can help me through the process. I am sharing the details of project. My existing Customer model class Customer(models.Model): user=models.OneToOneField(User,on_delete=models.CASCADE) # user=models.OneToOneField(User,on_delete=models.CASCADE) -change I made to add CustomUser model phone=models.CharField(max_length=10) city = models.TextField(max_length=30) state = models.TextField(max_length=30) def __str__(self): return self.user.username My CustomerUser model that I want to introduce in my project class CustomUser(AbstractUser): ROLES=( ('admin', 'Admin'), ('staff', 'Staff'), ('merchant', 'Merchant'), ('user', 'User'), ) role = models.CharField(max_length=8,choices=ROLES,default='Customer') def is_admin(self): return self.role == 'admin' def is_staff(self): return self.role == 'staff' def is_merchant(self): return self.role == 'merchant' The login, logout and registration stopped working as soon as I added this CustomUser model into my project. -
whitenoise module not found in production
Error: I ran into this error when trying to deploy my Django app using GAE: ModuleNotFoundError: No module named 'whitenoise'. The error occurs when starting the wsgi application. Attempted fixes: Wrapping the wsgi in whitenoise as mentioned here was done, (https://whitenoise.readthedocs.io/en/stable/index.html#quickstart-for-django-apps) but it didn't make a difference. whitenoise 6.7.0 is downloaded and is in requirements.txt, and the necessary whitenoise middleware is in settings.py. Question: How do I get wsgi to find my whitenoise (and wiki) module?. Or what is better approach to deploying my app? wsgi.py import os import sys from django.core.wsgi import get_wsgi_application from whitenoise import WhiteNoise # This application object is used by any WSGI server configured to use this # file. This includes Django's development server, if the WSGI_APPLICATION # setting points here. PROJECT_PATH = os.path.abspath(os.path.dirname(os.path.split(__file__)[0])) PROJECT_PARENT = os.path.abspath(os.path.split(PROJECT_PATH)[0]) sys.path.append(PROJECT_PATH) sys.path.append(PROJECT_PARENT) os.environ.setdefault("DJANGO_SETTINGS_MODULE", "testproject.settings") PROJECT_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__))) application = get_wsgi_application() application = WhiteNoise(application, root=os.path.join(PROJECT_DIR, 'static')) app.yaml with the url hidden for this post # app.yaml runtime: python311 env: standard entrypoint: gunicorn -b :$PORT testproject.wsgi env_variables: APPENGINE_URL: my_url DJANGO_SETTINGS_MODULE: "testproject.settings" handlers: - url: /.* static_dir: static/ - url: /.* script: auto runtime_config: python_version: 3 Logs 2024-07-16 22:15:28 default[20240716t221126] ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ 2024-07-16 22:15:28 default[20240716t221126] File "<frozen importlib._bootstrap>", line 1204, in _gcd_import … -
Static files issue in Django while deploying to AWS EC2 Machine
I made a multi-tenant app using django and now want to deploy it to AWS. When I run the server on EC2 machine and go to django admin this is what I get: It works fine locally though. Also when I open the main login page I cannot see the pics I added: and here is my folder structure: I have my pics in chatbot/app/login/static/pics As for my settings.py I setup it up like this: The pics and django-admin panel is not loading with its full css HELP I tried changing the paths too but I guess I am not able to understand that. also after changing the paths I tried running "python manage.py collectstatic" but it did not make a difference -
Django - dropdown (select widget) in form is not saving data to db
I'm using this form to get a dropdown menu in my html form : forms.py class forms_bdc(forms.ModelForm): [...] bdc_description_1 = forms.ModelChoiceField(required=False,queryset=models_products.objects.values_list('product_denomination', flat=True), widget=forms.Select(attrs={'id': 'editable-select-2','onchange': 'populate_selected_product(this.id)'}),empty_label=None ) models.py class models_bdc(models.Model): [...] bdc_description_1 = models.CharField(max_length=50) But when I save / submit the form, the data are not saving into the database. If I remove the select widget to a regular forms.charfield, the datas are saving correctly. So I assume the mistake is the forms.py but I can't see where. Thanks -
Frequent Deletion Failures in Django with CockroachDB
I'm using CockroachDb (version 24.2) with Django (version 5.0.7) but im currently running into an issue I don't really understand. When I trigger a certain view many times in a row which will delete an object from the Cockroach Database, it maybe works for like 4 out of 6 object I requested a deletion for, meaning 2 object will stay undeleted, I dont get any Error or stacktrace at all, the transaction simply does not get trough while Django reports back that everything went fine. The view can be very simple, like below.: @api_view(['DELETE']) @authentication_classes([]) @permission_classes([IsAuthenticated]) def delete_my_model_entry(request, pk): try: # Fetch the object to be deleted my_model_entry = MyModel.objects.get(pk=pk) # Delete the object my_model_entry.delete() return Response(status=status.HTTP_204_NO_CONTENT) except ObjectDoesNotExist: return Response({'error': 'Object not found'}, status=status.HTTP_404_NOT_FOUND) except Exception as e: return Response({'error': str(e)}, status=status.HTTP_500_INTERNAL_SERVER_ERROR) But if I fire against it many times in a short timeframe, the deletion actually dont happen at all ... For the moment I'm was not able to isolate the actual issue here I simply use django-cockroachdb==5.0 and psycopg2==2.9.9, exactly like described in the Readme file of the libraries. Thank in advance. -
Problem customizing search_get_results() method in Django Admin page to get Custom Search
I have an app in Django and I would like to use this template: {% load i18n static %} {% if cl.search_fields %} <div className="form-group"> <div class="search-notes col-md-6 col-sm-12">Para busqueda de terminos exactos poner el texto entre comillas Ej para editorial "VANGUARDIA PICTORICA" o en ISBN "978-959-7126-52-2"</div> </div> <div class="for-group-container row"> <div class="form-group col-md-3"> <input type="text" name="no_reg" class="form-control" placeholder="Número de Registro" /> <br> <input type="text" name="inputTitulo" class="form-control" placeholder="Título" /> <br> <br/> <input type="text" name="inputAutor" class="form-control" placeholder="Autor" /> <br/> </div> <div class="form-group col-md-3"> <input type="text" name="inputEditorial" class="form-control" placeholder="Editorial" /> <br/> <input type="text" name="inputDescriptor" class="form-control" placeholder="Descriptor" /> <br/> <div class="form-group col-md-3"> <input type="text" name="inputResumen" class="form-control" placeholder="Resumen" /> <br/> <input type="submit" value="{% translate 'Search' %}"> </div> {% if show_result_count %} <span class="small quiet">{% blocktranslate count counter=cl.result_count %}{{ counter }} result{% plural %}{{ counter }} results{% endblocktranslate %} (<a href="?{% if cl.is_popup %}{{ is_popup_var }}=1{% endif %}">{% if cl.show_full_result_count %}{% blocktranslate with full_result_count=cl.full_result_count %}{{ full_result_count }} total{% endblocktranslate %}{% else %}{% translate "Show all" %}{% endif %}</a>)</span> {% endif %} {% for pair in cl.params.items %} {% if pair.0 != search_var %}<input type="hidden" name="{{ pair.0 }}" value="{{ pair.1 }}">{% endif %} {% endfor %} </div> {% if cl.search_help_text %} <br class="clear"> <div class="help" id="searchbar_helptext">{{ … -
Django/Python - How to assign a file path variable in a platform-independent way?
I have a Django project where one of the .env file variables is going to represent an absolute file path. E.g., DEBUG=True SECRET_KEY='blah_blah_blah' MY_STORAGE_PATH = 'D:\\files\\for\\my\\project' Obviously the above would work fine on a Windows machine with a D: drive, but it's no good if there's no D: drive or if the machine is using some other OS. Now I can think of any number of functioning ways to supply this .env string in a platform-independent way, and then use string manipulation and the os.path methods to assemble the actual path. I could break out the drive & path separately, using a 'neutral' path separator of my own choosing: MY_STORAGE_DRIVE_FOR_WIN = 'D:' MY_STORAGE_PATH = '|files|for|my|project' ...I could supply the configuration formatted as a list, convert it to a real list, then feed into os.path.join(): MY_STORAGE_PATH_ELEMENTS = '["files","for","my","project"]' ...and so on, and so on. But before I go roll my own that way, I wanted to know: is there some accepted convention for this kind of use case? (Surely this isn't the first time someone needed to provide an .env value to represent a platform-independent path?) -
Why is my schema execution timing out in python graphene?
I'm using graphene. I was using version 2.1.9. I'm now using version 3.3. This code has not been changed since the upgrade, I'm going to outline the relevant code and then explain the problem further build_schema: neither Query or Mutation are None so this will return graphene.Schema(query=Query, mutation=Mutation) @logf(level='debug') def build_schema(*args, **kwargs) -> graphene.Schema: """Builds the Query and Mutation classes for the given schema name and adds them a schema and returns the schema """ Query, Mutation = None, None qclasses, qprops = _build_props('queries', *args, **kwargs) if qclasses: Query = type('Query', qclasses, qprops) mclasses, mprops = _build_props('mutations', *args, **kwargs) if mclasses: Mutation = type('Mutation', mclasses, mprops) if Query is None and Mutation is None: raise ValueError('No Query or Mutation classes found') elif Query is None: gqlschema = graphene.Schema(mutation=Mutation) elif Mutation is None: gqlschema = graphene.Schema(query=Query) else: gqlschema = graphene.Schema(query=Query, mutation=Mutation) return gqlschema This is the test case that fails, it's not verbose about why it failed, it just hangs for 60 seconds and then says that it timed out def _mock_user(user='test', **kwargs): return MagicMock(username=user, **kwargs) def _mock_info(**kwargs): infomock = MagicMock() infomock.context.user = _mock_user(**kwargs) return infomock class TestSignUrlQuery(TestCase): def setUp(self): self.query = ''' query { signedUrl( gcsUrl: "bucket/path/to/file", method: "PUT", contentType: … -
Django Database Routers "allow_migrate_model" throws the following: "TypeError: allow_migrate() missing 1 required positional argument: 'app_label'"
the "allow_migrate_model" function within my database routers keeps throw the following error when I try to run python manage.py makemigrations: ... File "C:\Users\...\lib\site-packages\django\db\utils.py", line 262, in allow_migrate allow = method(db, app_label, **hints) TypeError: allow_migrate() missing 1 required positional argument: 'app_label' My Routers look like this: class BaseRouter: route_app_labels = {} db_name = "" def db_for_read(self, model, **hints) -> Union[str, None]: if model._meta.app_label in self.route_app_labels: return self.db_name return None def db_for_write(self, model, **hints) -> Union[str, None]: if model._meta.app_label in self.route_app_labels: return self.db_name return None def allow_relation(self, obj1, obj2, **hints) -> Union[bool, None]: if ( obj1._meta.app_label in self.route_app_labels or obj2._meta.app_label in self.route_app_labels ): return True return None def allow_migrate( self, db, app_label, model_name=None, **hints ) -> Union[bool, None]: if app_label in self.route_app_labels: return db == self.db_name return None class DefaultRouter(BaseRouter): route_app_labels = {"auth", "contenttypes", "sessions", "admin", "myapp"} db_name = "default" class LibraryRouter(BaseRouter): """ separate router for backend stuff """ route_app_labels = {"library"} db_name = "library" The above is basically a slightly modified version found on the Django Docs. If I comment out the allow_migrate the makemigrations works, however, I would like to modify the allow_migrate further so that's not a convincing option rn. Ah also for some reason if a rewrite it …