Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
how to add children to a table
I want to create a comment thread system and the problem is that I know how to create a table containing children I followed a tutorial in PHP for the realization of a system of comment and I want to do it in python django $comments = commentary table $comments_by_id = [] empty board foreach($comments as $comment){ $comments_by_id[$comment->id] = $comment;`enter code here` } foreach($comments as $k => $comment){ if($comment->parent_id != 0) { $comments_by_id[$comment->parent_id]->children[] = $comment; unset($comments[$k]) } } python code? -
Django, CORS, CSRF - am I doing it right?
My setup (local) is the following: Vue.js running on localhost:8080 (npm run serve) REST API built with Django running on localhost:8000 (./manage-py runserver) In order to enable this to work I've made the following additions: ALLOWED_HOSTS = [ ... 'localhost', 'localhost:8000', 'localhost:8080', ] INSTALLED_APPS = [ ... 'rest_framework', 'corsheaders', ] MIDDLEWARE = [ ... 'django.contrib.sessions.middleware.SessionMiddleware', 'corsheaders.middleware.CorsMiddleware', 'django.middleware.common.CommonMiddleware', ... ] CORS_ORIGIN_WHITELIST = ( 'localhost:8080', 'localhost:8000', ) CORS_ALLOW_CREDENTIALS = True from corsheaders.defaults import default_headers CORS_ALLOW_HEADERS = default_headers + ( 'credentials', ) One of my API functions: @ensure_csrf_cookie def try_login(request): # this is just to get the initial CSRF token: if request.method == "GET" or request.method == "OPTIONS": return JsonResponse({'status': 'ok'}) # else, an actual login request: else: data = JSONParser().parse(request) user = authenticate(request, username=data['user'] , password=data['pass']) if user is not None: login(request, user) return JsonResponse({'login_succ': 'ok'}); else: return JsonResponse({'login_succ': 'fail'}); Finally, in Vue: api: function(endpoint, method, data) { var headers = new Headers(); headers.append('content-type', 'application/json'); if (... this is not the first request ever ...) { csrftoken = document.cookie.replace(/(?:(?:^|.*;\s*)csrftoken\s*\=\s*([^;]*).*$)|^.*$/, "$1"); headers.append('X-CSRFToken', csrftoken); } method = method || 'GET'; var config = { method: method, body: data !== undefined ? JSON.stringify(data) : null, headers: headers, }; config['credentials'] = 'include'; return fetch(endpoint, config) .then(response … -
How to change m2m object's fields of an object in django admin
I have 2 models: class Payment(models.Model): checks = models.ManyToManyField('Check', blank=True, null=True) class Check(models.Model): status = models.CharField(max_length=10) I want to change Check's status when users add or delete checks in Payment's checks (m2m field) in django admin. -
Get timezones of a country
I have a form in which I need the user to choose their timezone. I have a dropdown where one chooses their country and I want to be able to populate the possible timezones for that country as a dropdown for the user to choose. Eg : The users chooses Mexico and I show the timezones as 'America/Mexico_City', 'America/Cancun', 'America/Merida', 'America/Monterrey', 'America/Matamoros', 'America/Mazatlan', 'America/Chihuahua', 'America/Ojinaga', 'America/Hermosillo', 'America/Tijuana', 'America/Santa_Isabel', 'America/Bahia_Banderas' and the User will be able to choose one of them for me to process. What is the best way to be able to do this? I am using Django framework and will be populating the dropdown using js. -
Call function right after starting django developement server. (Django/Python)
I'm trying to call function right after command python manage.py runserver it can be simple print. I read some stuff and I find quite interesting topics about def ready(self) like this one Overriding AppConfig.ready() or Execute code when Django starts ONCE only? I follow the instructions but for django 2.1.3 version it doesn't work. One time ready function just isn't called another time I get bunch of AppRegistryNotReady exceptions. I think that call function after server start is quite common thing. It shoulnd't give so much trouble but still I don't find proper solution -
Updating base.html before rendering index.html
I have a base template (masterpage.html) and a index page (index.html). There is a navbar in masterpage.html which i want to be populated before index.html page is shown. def index(request): render (request,'homeapp/masterpage.html',all_dict) return render(request,'homeapp/index.html',pic_dict) I want masterpage.html to be populated by all_dict values before index.html page is shown -
Correct way to test a function
Is it okay to call build_admins_message in the tests to build expected result that will be used in mock assertion? Implementation: @slack_messages.on_pattern('(?i)^admins$') def handle_admins_message(event, body, match): team_id = event['team_id'] user_id = body['user'] message = build_admins_message(team_id, user_id) Slack(team_id).send_message(user_id, **message) Tests: class TestAdminsMessageHandler(TestCase): def setUp(self): team = SlackTeam.objects.create(team_id='TEAMID') SlackUser.objects.create(team=team, user_id='USERID') def tearDown(self): SlackUser.objects.all().delete() SlackTeam.objects.all().delete() @mock.patch('slango.slack.Slack.send_message') def test_correct_text(self, send_message_mock): event = { 'team_id': 'TEAMID', 'event': { 'text': 'admins', 'user': 'USERID' } } handle_admins_message(event, event['event']) expected_message = build_admins_message('TEAMID', 'USERID') send_message_mock.assert_called_with('USERID', **expected_message) -
Django login authenticate() always returns None
I'm creating a custom django login view but whenever I try to login authenticate() always returns None even when I type in the right password. I don't want django's builtin login system because it didn't work either and I can't define a SignInForm. forms.py: class SignInForm(forms.Form): username = forms.CharField(error_messages={"required": "Bitte fülle dieses Feld aus.", "invalid": "Dieser Wert ist ungültig."}, min_length=3, max_length=31, required=True, widget=forms.TextInput(attrs={ "placeholder": "Benutzername oder E-Mail-Adresse", #Username or e-mail "id": "username", "class": "select selected" })) password = forms.CharField(error_messages={"required": "Bitte fülle dieses Feld aus.", "invalid": "Dieses Passwort ist ungültig."}, min_length=8, max_length=1023, required=True, widget=forms.PasswordInput(attrs={ "placeholder": "Passwort", "id": "password" })) stayLoggedIn = forms.BooleanField(help_text="Angemeldet bleiben?", required=False, widget=forms.CheckboxInput(attrs={ "checked": "False", })) class Meta: model = User exclude = () field_order = ("username", "password", "stayLoggedIn") def clean(self): cleaned_data = super(SignInForm, self).clean() username = cleaned_data.get("username") if "@" in username: try: username = User.objects.get(email__iexact=username).username except ObjectDoesNotExist: raise forms.ValidationError("Diese E-Mail-Adresse wurde nicht gefunden.") else: try: username = User.objects.get(username=username).username except ObjectDoesNotExist: raise forms.ValidationError("Dieser Benutzername wurde nicht gefunden.") user = authenticate(username=username, password=cleaned_data.get("password")) print(user) #Thats always None if not user or not user.is_active: raise forms.ValidationError("Falsches Passwort.") cleaned_data["user"] = user return cleaned_data views.py def login(request): if request.method == "POST": form = SignInForm(request.POST) if form.is_valid(): cleaned_data = form.clean() if cleaned_data.get("user"): auth_login(request, cleaned_data.get("user")) try: … -
How to get page_size set in query into pagination metadata django rest framework
I have setup custom pagination for one of my apps, the issues I am facing is the page_size shows only the default value that is set in the app but does not change according to the values sent in the query parameter. Where am I going wrong? class CustomPagination(PageNumberPagination): page_size = 10 page_size_query_param = 'page_size' def get_paginated_response(self, data): return Response({"status": True, "data": { 'results': data, "meta": { 'page_count':self.page.paginator.num_pages, 'total_results': self.page.paginator.count, 'current_page_no': self.page.number, 'limit': self.page_size, 'last_page': self.page.has_next() }}}, status=status.HTTP_200_OK) The output of page_size is always 10 even if I set the query parameter to a different value. Eg: it should change to 2 if the user set page_size =2 in the query parameters. -
django permision check box form - ACL (Access Control List)
I want to create Access Control List using permission table, similar to the image. Where I want to display permission form with a checkbox. On the check, permission should bbe given to that user and group. Please help me to create ACL. -
Query the items related to current user in template
I have two models in my Django app like the following: class Movie(models.Model): title = models.CharField() # some movie-related fields class Rating(models.Model): user = models.ForeignKey(User, on_delete=models.CASCADE) movie = models.ForeignKey(Movie, on_delete=models.CASCADE) score = models.IntegerField() So users can rate any movies they want. I have also a templated named index.html and here is how I'm sending the data to this template using the views.py: def index(request): movies = Movie.objects.all() return render(request, 'index.html', {'movies': movies}) The index.html: {% for movie in movies %} {{movie.title}} <br /> # The rating score that current user has gave to this movie in the iteration {% endfor %} I've tried the following, but it displays all scores that all users have given to the movie, not only the current user: {% for rating in movie.rating_set.all %} {{rating.score}} {% endfor %} How can I display the score that current user (that is seeing the movie page) has given to the movie in the index.html page? -
Heroku does not seem to add my admin static files to static_root
This is my settings file: import os import logging import logging.config import sys import django_heroku # Build paths inside the project like this: os.path.join(BASE_DIR, ...) BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__))) # Quick-start development settings - unsuitable for production # See https://docs.djangoproject.com/en/dev/howto/deployment/checklist/ # SECURITY WARNING: keep the secret key used in production secret! SECRET_KEY = 'this is not my secret key' # SECURITY WARNING: don't run with debug turned on in production! # DJANGO_DEBUG must be 'true' (any case) to turn on debugging DEBUG = os.environ.get('DJANGO_DEBUG', '').lower() == 'true' ALLOWED_HOSTS = [ '*' ] # Application definition INSTALLED_APPS = [ 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'myapp', ] 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', 'whitenoise.middleware.WhiteNoiseMiddleware', ] ROOT_URLCONF = 'myapp.urls' TEMPLATES = [ { 'BACKEND': 'django.template.backends.django.DjangoTemplates', 'DIRS': [], 'APP_DIRS': True, 'OPTIONS': { 'context_processors': [ 'django.template.context_processors.debug', 'django.template.context_processors.request', 'django.contrib.auth.context_processors.auth', 'django.contrib.messages.context_processors.messages', ], }, }, ] WSGI_APPLICATION = 'myapp.wsgi.application' # Database # https://docs.djangoproject.com/en/dev/ref/settings/#databases DATABASES = { 'default': { 'ENGINE': 'django.db.backends.sqlite3', 'NAME': os.path.join(BASE_DIR, 'db.sqlite3'), } } # Password validation # https://docs.djangoproject.com/en/dev/ref/settings/#auth-password-validators AUTH_PASSWORD_VALIDATORS = [ { 'NAME': 'django.contrib.auth.password_validation.UserAttributeSimilarityValidator', }, { 'NAME': 'django.contrib.auth.password_validation.MinimumLengthValidator', }, { 'NAME': 'django.contrib.auth.password_validation.CommonPasswordValidator', }, { 'NAME': 'django.contrib.auth.password_validation.NumericPasswordValidator', }, ] # Internationalization # https://docs.djangoproject.com/en/dev/topics/i18n/ LANGUAGE_CODE = 'en-gb' TIME_ZONE = 'Europe/London' USE_I18N = True USE_L10N … -
Getting the list of timezones supported by PostgreSQL in Django using RawSQL
I am trying to get the list of all the timezones supported by PSQL database in my Django project, so I can validate timestamps with timezones before sending them to the the database. I asked another question and got an answer regarding the PSQL query here: How to get the list of timezones supported by PostgreSQL? Using that, I am trying to do the following: from django.db.models.expressions import RawSQL RawSQL("SELECT name, abbrev, utc_offset, is_dst FROM pg_timezone_names;", []) However, it does not seem to work. I saw the docs for RawSQL, and it usually has a model attached to it, which I can't really have. How to do solve this issue? Thanks. -
Django - ORA-01438: value larger than specified precision allowed for this column
I have a table in my Oracle database that one of her columns is a NUMBER(38,0). If I directly do an insert in the database with a number like "6688930737147338195" , the insert goes OK. But, when I use django object.save() with the number it gives me this error: django.db.utils.DatabaseError: ORA-01438: value larger than specified precision allowed for this column I ran this code in my oracle database to try fix this: ALTER TABLE XYZ MODIFY Z NUMBER(38,0); COMMIT; But the problem in Django still occurs. It gives the same error. But, for some reason, the object it's saved in the database even after this error. What should I do? -
How does Django Rest Framework serialize multi-object without using SQL Foreign key
take performance of sql server into consideration, I design the sql without using any foreign key, Instead I use the id reference to join two table. but when I use the serialization of Django Rest Framework to serialize multi-table, it's only support foreign key(is this right?). Another solution is using mysql view mapping to a django model which can represent multi joined table. In this case, I need to split GET and POST method to two separate APIView, instead of generics.ListCreateAPIView as a whole(GET for mysql view model. POST for non-myql-view model), but in restful design they are the same URI. GET /school -- mapping to mysql view for more information POST /school -- just create a new host Code: class LocationSerializer(model.Model): pass class SchoolSerializer(models.Model): pass class LocationSerializer(serializers.ModelSerializer): class Meta: model = LocationModel fields = ("region", "state", "country") class SchoolSerializer(serializers.ModelSerializer): location = LocationSerializer() class Meta: model = SchoolModel fields = ("name", "level", "location") class SchoolList(generics.ListCreateAPIView): queryset = SchoolModel.objects.all() serializer_class = SchoolSerializer class SchoolDetail(generics.RetrieveUpdateDestroyAPIView): queryset = SchoolModel.objects.all() serializer_class = SchoolSerializer -
How can i stop django background task permanently which is running parallely?
i have 3-4 django background_tasks which runs parallely,but i want to stop all tasks except a single task.i am using django background_task,which is a inbuilt library in django.how can i solve this issue? -
Can I somehow call logic from form_valid() in Django tests?
I am trying to test form for Post model creation in my simple forum application. The problem I am having is that after I try to save the form in tests I get an error NOT NULL constraint failed: forum_web_post.user_id because I am assigning the user in the form_valid() method in the view. The user is not passed via the form since the user that creates the post is the signed in user that sent the request. models.py class Post(models.Model): category = models.ForeignKey(Category, on_delete=models.PROTECT) user = models.ForeignKey(User, on_delete=models.CASCADE) title = models.CharField(max_length=100) text = models.TextField() created_at = models.DateTimeField(auto_now=True) user is imported form django.contrib.auth.models and Category model looks like this. class Category(models.Model): name = models.CharField(max_length=100) created_at = models.DateTimeField(auto_now=True) in views.py after the user submits the form he is the redirected to his profile page views.py class PostCreate(generic.CreateView): model = Post form_class = PostForm template_name = 'forum_web/post_edit.html' def form_valid(self, form): post = form.save(commit=False) post.user = models.User.objects.get(id=self.request.user.id) post.save() return HttpResponseRedirect(reverse_lazy('forum:user_detail', kwargs={'pk': self.request.user.id})) forms.py class PostForm(ModelForm): class Meta: model = Post fields = ['category', 'title', 'text'] tests.py def test_post_form_create_should_pass(self): # this dict is in setUp() as well as the test_category but for simplicity I will include it in this method post_data = { 'category': self.test_category.pk, … -
Django admin's default autocomplete_fields combined with Chained Foreign Key of smart-selects
I am using Django 2.1.3, django-smart-selects 1.5.4 and three simple models for example Client, Billing Account and Order. What needs to be done is upon Order creation the user should choose a Client (presuming that the count of all registered clients will be a large number) as an autocomplete_field. Upon choosing Client there should be another select with all billing accounts associated for this client. In Order i have related Client as a ForeignKey and BillingAccount as a ChainedForeignKey to Client using smart-selects as following: class Order(models.Model): client = models.ForeignKey(Client, on_delete=models.PROTECT, null=True) billing_account = ChainedForeignKey(BillingAccount, chained_field="client", chained_model_field="client", show_all=False, auto_choose=True, on_delete=models.PROTECT, null=True) The problem is when the user chooses a given Client, the BillingAccount select wont autofill. Note: When Client is not associated in OrderAdmin's autocomplete_fields BillingAccount is filled as it should be with all accounts associated for this Client. -
My pre_save signal isn't applying my string generator
I wrote a simple string generator for my order_id field. I tested the generator script in shell, and it works perfectly. But when I run the server, and try to create an order in django admin, the order id field remains empty when I click save. What am I doing wrong? from datetime import date from django.db import models from django.db.models.signals import pre_save from cartapp.models import Cart class Order(models.Model): order_id = models.CharField(max_length=120) cart = models.ForeignKey(Cart, on_delete=models.CASCADE) status = models.CharField(max_length=50, default='Waiting', null=True, blank=True) order_total = models.DecimalField(default=0.0, max_digits=10, decimal_places=1) date_created = models.DateTimeField(auto_now_add=True) def order_id_generator(instance): today = date.today().strftime("%Y-%m-%d") last_order_raw = Order.objects.latest('order_id').date_created last_order_date = str(last_order_raw).split(' ')[0] if today != last_order_date: new_order_id = str(today + " 1") else: last_order = Order.objects.latest('order_id') extract = last_order.order_id.split(' ')[1] increment = int(extract) + 1 new_order_id = today + " " + str(increment) return new_order_id def pre_save_order_id(sender, instance, *args, **kwargs): if not instance.order_id: instance.order_id = order_id_generator(instance) pre_save.connect(pre_save_order_id, sender=Order) -
Incorrect django-tables2 table rendering and accessor issues
This is a two part problem. I would like to display any publications that are related to a sample, and I would like to render this publication table on the detail page for a sample. As always, any assistance is greatly appreciated. Problem 1. Rendering the table (django-tables2) When I render the table (see top row of image), a) none of the fields present themselves as hyperlinks (tables.LinkColumn) and b) the excluded fields are present in the table. While reviewing this post, I realized that I am not rendering the table I outlined in the tables/views/url!! Question 1. How do I render a table with publication objects that are related to a specific sample when the sample is a foreign key for publication model? For example, I can render the publication table as follows: #from samples/template/samples/publication_list.html {% render_table publication_table %} If I try the same code in another file I will get an error: #from samples/template/samples/sample_detail.html {% render_table publication_table %} ValueError at /samples/sample/116 ... Expected table or queryset, not str Problem 2. Hard-coding the table To get around problem 1, I hard-coded the table but cannot get the linked title_p field to go to samples/template/samples/publication_detail.html without a NoReverseMatch error. I … -
same token is getting on token request in django
Hi I am using django rest-framework, i want to implement token base authentication, i am using basic rest-framework token authentication module. but it return same token on every request. ex(87d97bb2df56e39c12b38131087bcfd232720d9a), i am getting this string on every request i sent to my server. my setting.py file INSTALLED_APPS = [ 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'restApp2', # Local Apps (My project's apps) 'rest_framework', 'rest_framework.authtoken', 'rest_auth', ] REST_FRAMEWORK = { 'DEFAULT_AUTHENTICATION_CLASSES': [ 'rest_framework.authentication.TokenAuthentication', # <-- And here ], } urls.py file from django.contrib import admin from django.urls import path, include from restApp2 import views from rest_framework.authtoken.views import obtain_auth_token urlpatterns = [ path('admin/', admin.site.urls), path('hello/', views.HelloView.as_view(), name='hello'), path('api-token-auth/', obtain_auth_token, name='api_token_auth'), # <-- And here ] urlpatterns += [ path('accounts/', include('django.contrib.auth.urls')), ] i am calling bellow url using post method from POSTMON. POST http://localhost:7070/rest-auth/login/ and in response i get 87d97bb2df56e39c12b38131087bcfd232720d9a. but i want different token on new request. please help me, Thank You -
Condition in Model Django
i want company_name to be unique=True when company_is_deleted=False. Similarly when company_is_deleted=True then company_name to be unique=False. Where i am using soft delete means that i am just setting company_is_deleted=True and not deleting it from database table. Company Model class Company(models.Model): company_name = models.CharField(max_length=20, unique=True) # Here company_description = models.CharField(max_length=100) company_address = models.CharField(max_length=100) company_email = models.EmailField() company_website = models.URLField() company_phone = models.CharField(max_length=30) company_monthly_payment = models.DecimalField(max_digits=5, decimal_places=2) company_logo = models.ImageField(upload_to='company_logo', default='default_company.png',blank=True, null=True) company_created = models.DateTimeField(auto_now_add=True) company_is_deleted = models.BooleanField(default=False) View.py class CompanyCreateView(LoginRequiredMixin, generic.CreateView): model = Company fields = ['company_name', 'company_description', 'company_email', 'company_website', 'company_address', 'company_phone', 'company_status', 'company_monthly_payment', 'company_logo'] -
Django-bitfield : Access a bitfield in django queryset values
I was trying to list of values of a bitfield in a django queryset but was unable to do so as i couldn't find anything related to fetching bitfield flag values. Let's say I have a field in one of my models flags = Bitfield(flags=( 'a', 'b')) now I want to use this value from a queryset is there a way to get the value in the queryset by doing something like this m=model.objects.values('flags__a__is_set') -
ReportLab: Save PDF to filesystem/server
I am working on a project in Python/Django and I am using ReportLab for PDF creation. I would like to save PDF files on my server, but I am not able to find much information about that, so I wonder if there is someone with experience of storing PDF from ReportLab to a web server? -
Unhandled exception in thread started by <function check_errors.<locals>.wrapper at 0x10deb92f0>
Having issues running django site with python3 manage.py runserver command. When starting, I get an error below: MacBook-Pro-Lev:mysite levpolomosnov$ python3 manage.py runserver Performing system checks... Unhandled exception in thread started by <function check_errors. <locals>.wrapper at 0x10deb92f0> Traceback (most recent call last): File "/Library/Frameworks/Python.framework/Versions/3.6/lib/python3.6/site-packages/django/utils/autoreload.py", line 228, in wrapper fn(*args, **kwargs) File "/Library/Frameworks/Python.framework/Versions/3.6/lib/python3.6/site-packages/django/core/management/commands/runserver.py", line 124, in inner_run self.check(display_num_errors=True) File "/Library/Frameworks/Python.framework/Versions/3.6/lib/python3.6/site-packages/django/core/management/base.py", line 359, in check include_deployment_checks=include_deployment_checks, File "/Library/Frameworks/Python.framework/Versions/3.6/lib/python3.6/site-packages/django/core/management/base.py", line 346, in _run_checks return checks.run_checks(**kwargs) File "/Library/Frameworks/Python.framework/Versions/3.6/lib/python3.6/site-packages/django/core/checks/registry.py", line 81, in run_checks new_errors = check(app_configs=app_configs) File "/Library/Frameworks/Python.framework/Versions/3.6/lib/python3.6/site-packages/django/core/checks/urls.py", line 16, in check_url_config return check_resolver(resolver) File "/Library/Frameworks/Python.framework/Versions/3.6/lib/python3.6/site-packages/django/core/checks/urls.py", line 26, in check_resolver return check_method() File "/Library/Frameworks/Python.framework/Versions/3.6/lib/python3.6/site-packages/django/urls/resolvers.py", line 256, in check for pattern in self.url_patterns: File "/Library/Frameworks/Python.framework/Versions/3.6/lib/python3.6/site-packages/django/utils/functional.py", line 35, in __get__ res = instance.__dict__[self.name] = self.func(instance) File "/Library/Frameworks/Python.framework/Versions/3.6/lib/python3.6/site-packages/django/urls/resolvers.py", line 407, in url_patterns patterns = getattr(self.urlconf_module, "urlpatterns", self.urlconf_module) File "/Library/Frameworks/Python.framework/Versions/3.6/lib/python3.6/site-packages/django/utils/functional.py", line 35, in __get__ res = instance.__dict__[self.name] = self.func(instance) File "/Library/Frameworks/Python.framework/Versions/3.6/lib/python3.6/site-packages/django/urls/resolvers.py", line 400, in urlconf_module return import_module(self.urlconf_name) File "/Library/Frameworks/Python.framework/Versions/3.6/lib/python3.6/importlib/__init__.py", line 126, in import_module return _bootstrap._gcd_import(name[level:], package, level) File "<frozen importlib._bootstrap>", line 978, in _gcd_import File "<frozen importlib._bootstrap>", line 961, in _find_and_load File "<frozen importlib._bootstrap>", line 950, in _find_and_load_unlocked File "<frozen importlib._bootstrap>", line 655, in _load_unlocked File "<frozen importlib._bootstrap_external>", line 678, in exec_module File "<frozen importlib._bootstrap>", line 205, in _call_with_frames_removed File …