Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Decode Base64 string to PDF File Django Python?
I have this problem, I have this string in base 64: eC1hbXotaWQtMjogRW1VZWtRZHhLTWViUWZQa0txT... My idea is to decode the string and download the file (pdf), but when I try to download the file I have this screen enter image description here I do not what happen, this is the code that I use to decode and download the file: @login_required def get_pdf_document_invoice(request, id): import base64 print('invoice_pdf') customer = request.user.company.customer invoice_pdf = customer.get_pdf_invoice(id) contentb64 = invoice_pdf['data'] decode_file = base64.b64decode(contentb64) print(invoice_pdf, "pdf") response = HttpResponse(content_type='application/pdf') response['Content-Disposition'] = 'attachment; filename=invoice.pdf' response.write(decode_file) return response -
Django Template Language - URL Based On Template {{ value }}
Let's say I have, in context, a JSON called "rows", and each row has 2 fields: a and b. I wish to make b a url parameter and pass to a url call, like this: {% for row in rows %} <tr> <td>{{ row.a }}</td> <td><a href = "{% url 'some url' param={{ row.b }} %}">{{ row.b }}</a></td> <tr> The above code is invalid. How to do this? -
django-DefectDojo postgres user disconnects & reconnects constantly
I am running DefectDojo on AWS using a serverless Aurora (Postgres 13.8) DB I see a large number of connect/disconnect events in the logs. They look like this: 2023-10-04 19:44:04 UTC:10.237.120.220(56990):[unknown]@[unknown]:[19442]:LOG: connection received: host=10.237.120.220 port=56990 2023-10-04 19:44:04 UTC:10.237.120.220(56990):postgres@defectdojo:[19442]:LOG: connection authorized: user=postgres database=defectdojo SSL enabled (protocol=TLSv1.2, cipher=AES128-GCM-SHA256, bits=128, compression=off) 2023-10-04 19:44:04 UTC:10.237.120.220(56990):postgres@defectdojo:[19442]:LOG: disconnection: session time: 0:00:00.011 user=postgres database=defectdojo host=10.237.120.220 port=56990 The logs are filled with these actions: connection received -> connection authorized -> disconnection. These sessions all last for less than a second. Is this behavior expected or is this a symptom of an underlying problem with my postgres user connection? -
Custom Middleware not worked on live server python django
When enable custom middleware in setting.py file in live server then the django application shows an error in browser: We're sorry, but something went wrong. The issue has been logged for investigation. Please try again later. error id: 1312e065. N.B in localhost server there was no issue. Setting.py: MIDDLEWARE = [ 'corsheaders.middleware.CorsMiddleware', 'django.middleware.security.SecurityMiddleware', 'django.contrib.sessions.middleware.SessionMiddleware', 'userAuth.custom_middleware.RequestLoggerMiddleware', 'django.middleware.common.CommonMiddleware', 'django.middleware.csrf.CsrfViewMiddleware', 'django.contrib.auth.middleware.AuthenticationMiddleware', 'userAuth.middleware.InactivityTimeoutMiddleware', 'django.contrib.messages.middleware.MessageMiddleware', 'django.middleware.clickjacking.XFrameOptionsMiddleware', ] middleware.py: class InactivityTimeoutMiddleware: def __init__(self, get_response): self.get_response = get_response def __call__(self, request): response = self.get_response(request) if request.user.is_authenticated: session_key = request.session.session_key if session_key: session = Session.objects.get(session_key=session_key) last_activity = session.get_decoded().get('_session_last_activity') if last_activity: idle_time = timezone.now() - last_activity if idle_time > timedelta(minutes=5): # User has been inactive for more than 5 minutes, log them out request.session.flush() return response thanks in advance. -
How can I solve problem with Django Template Language {{ form }}?
<div class="form-title"> {% if form.errors %} <p>{{ form.errors.error }}</p> {% endif %} <form action="{% url 'login' %}" method="post" class="fs-title"> {{ form }} {% csrf_token %} <button type="submit" class="btn btn-success">Join</button> </form> <a href="{% url 'password_reset' %}">Forgot password?</a> </div> I tried specifying the css name in the class attribute, but the output from {{form}} did not change its style. Is there a way to move the content of {{form}} to the center and set a style for it? -
Django runserver error: ModuleNotFoundError: No module named 'Deleted folder'
I hope you are doing well. I just started studying Django with the Meta back-end Cert. I created my first project inside a venv and ran the server just as instructed. Then I deleted the first folders, and tried to practice starting from zero. When I create the new project folder I do the following steps: create the venv -> py -m venv env activate the venv -> env\scripts\activate install django -> pip3 install django create the project -> django-admin startproject new_sample change directory -> cd new_sample try to runserver -> py manage.py runserver Error Below the console response, it tries to reach a deleted folder. ModuleNotFoundError: No module named 'C:\django_projects\project1' THE DELETED FOLDERS (env) PS C:\new_django_folder\project4\new_sample> py manage.py runserver Traceback (most recent call last): File "C:\new_django_folder\project4\env\Lib\site-packages\django\core\management\base.py", line 412, in run_from_argv self.execute(*args, **cmd_options) File "C:\new_django_folder\project4\env\Lib\site-packages\django\core\management\commands\runserver.py", line 74, in execute super().execute(*args, **options) File "C:\new_django_folder\project4\env\Lib\site-packages\django\core\management\base.py", line 458, in execute output = self.handle(*args, **options) ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ File "C:\new_django_folder\project4\env\Lib\site-packages\django\core\management\commands\runserver.py", line 81, in handle if not settings.DEBUG and not settings.ALLOWED_HOSTS: ^^^^^^^^^^^^^^ File "C:\new_django_folder\project4\env\Lib\site-packages\django\conf\__init__.py", line 102, in __getattr__ self._setup(name) File "C:\new_django_folder\project4\env\Lib\site-packages\django\conf\__init__.py", line 89, in _setup self._wrapped = Settings(settings_module) ^^^^^^^^^^^^^^^^^^^^^^^^^ File "C:\new_django_folder\project4\env\Lib\site-packages\django\conf\__init__.py", line 217, in __init__ mod = importlib.import_module(self.SETTINGS_MODULE) ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ File "C:\Program Files\Python312\Lib\importlib\__init__.py", line 90, in import_module return … -
I get the error while applying "python manage.py migrate"
when I run python manage.py migrate I get the following error TypeError: function missing required argument 'year' (pos 1) following is my showmigrations (https://i.stack.imgur.com/gqT42.png) how can i solve this migration error in my django project ..? -
Error: Failed to deploy web package to App Service. Error: Deployment Failed, Package deployment using ZIP Deploy failed. Refer logs for more details
Deployment Failed. deployer = GITHUB_ZIP_DEPLOY deploymentPath = ZipDeploy. Extract zip. Remote build. Error: Failed to deploy web package to App Service. Error: Deployment Failed, Package deployment using ZIP Deploy failed. Refer logs for more details. I am using GitHub cli to deploy mu Django app to Azure app service It was working fine until GitHub started to use zip deployment or package deployment than It gives me this error. I tried to add WEBSITE_RUN_FROM_PACKAGE=1in my app configurations and the deployments pass in GitHub without errors but the app doesn't work at all. -
I can't transfer data to an html template from the view
I'm trying to transfer data from the model to an html template, but it turns out a little crooked, help me figure it out and do it normally? models class SidesCaseInCase(models.Model): '''8. Промежуточная таблица для сторон по делу''' name = models.CharField( max_length=150, verbose_name='ФИО' ) sides_case = models.ForeignKey( SidesCase, on_delete=models.SET_NULL, blank=True, null=True, verbose_name='Стороны по делу', ) date_sending_agenda = models.DateField( blank=True, null=True, verbose_name='Дата направления повестки' ) recived_case = models.ForeignKey( ReceivedCase, on_delete=models.SET_NULL, blank=True, null=True, verbose_name='Поступившее дело', ) business_card = models.ForeignKey( BusinessCard, on_delete=models.SET_NULL, blank=True, null=True, verbose_name='Карточка на дело', ) class Meta: constraints = [ UniqueConstraint( fields=('sides_case', 'recived_case'), name='sides_cese_unique' ) ] verbose_name = 'Стороны по делу, в деле' verbose_name_plural = 'Стороны по делу, в деле' views def index(request): template = 'index.html' title = 'Первый проект. Главная страница' business_card = BusinessCard.objects.select_related( 'case_category', 'author' ) ` # card = get_object_or_404(BusinessCard, pk=card_id) sides_case_in_case_data = SidesCaseInCase.objects.all()` cards = BusinessCard.objects.select_related('case_category', 'author') page_obj = paginator_list(request, cards) context = { 'title': title, 'text': 'Главная страница', 'business_card': business_card, 'page_obj': page_obj, } return render(request, template, context) def business_card_detail(request, card_id): '''страница подробней о карточке''' card = get_object_or_404(BusinessCard, pk=card_id) ` side = get_object_or_404(SidesCase, pk=card_id) sides_case_in_case_data = SidesCaseInCase.objects.filter( business_card=card )` author = card.author author_card = author.cards.count() context = { 'card': card, 'author': author, 'author_card': author_card, 'side': side, … -
How to store and render HTML template files?
I am creating a web map with Django, Leaflet and PostgreSQL. I have a layer with points on the map. When I click on them, a popup shows up with some attribute data about that feature. This popup also has a button, which when clicked, opens o modal window with more details about the clicked feature. The text that shows up in the modal is a HTML template's text data stored in a field in the points table. The text has HTML tags, and are correctly shown, formatted and styled. I also have some images that should be rendered in the modal window, but they are not. As I am new to web development, I am wondering what would be the optimal way of storing this long HTML templates with images. Is it better to leave them as HTML files and render them when the appropriate button is pressed? I tried to render the images with django's static method. On my index page I can render the images, using the same img tag as in the modal window: . -
How i can replicate my Postgres database in CPanel
PLZ HEPL ME. I have problem -I can not find the answer to how I can do so that I could upload my real database in Postgress to the hosting and make it so that when you change data or add data in the database on the hosting it all automatically done in my database on the local machine (ie comp'yutera). I use CPanel to load my project on Django where my local Postgres database is connected. I need that somebody can me explain it, because in Internet i coudn't find ,y problem and AI too can't hepl me(((( -
pytest-django doesn't work in Github Actions
I have Django project that uses pytest and pytest-django. I have some tests, when I run them in docker-compose using docker exec -it <container name> pytest they are passing successfully. But when Github Actions run pytest command it gives me an error: ============================= test session starts ============================== platform linux -- Python 3.11.3, pytest-7.4.2, pluggy-1.3.0 django: settings: ***.settings (from env) rootdir: /home/runner/work/Meduzzen-backend-intership/Meduzzen-backend-intership/*** plugins: django-4.5.2 collected 3 items apps/api/tests/test_user_model.py EEE [100%] ==================================== ERRORS ==================================== ___________________ ERROR at setup of test_create_user_fail ____________________ request = <SubRequest '_django_db_marker' for <Function test_create_user_fail>> @pytest.fixture(autouse=True) def _django_db_marker(request) -> None: """Implement the django_db marker, internal to pytest-django.""" marker = request.node.get_closest_marker("django_db") if marker: > request.getfixturevalue("_django_db_helper") /opt/hostedtoolcache/Python/3.11.3/x64/lib/python3.11/site-packages/pytest_django/plugin.py:465: _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ /opt/hostedtoolcache/Python/3.11.3/x64/lib/python3.11/site-packages/pytest_django/fixtures.py:122: in django_db_setup db_cfg = setup_databases( /opt/hostedtoolcache/Python/3.11.3/x64/lib/python3.11/site-packages/django/test/utils.py:187: in setup_databases test_databases, mirrored_aliases = get_unique_databases_and_mirrors(aliases) /opt/hostedtoolcache/Python/3.11.3/x64/lib/python3.11/site-packages/django/test/utils.py:334: in get_unique_databases_and_mirrors default_sig = connections[DEFAULT_DB_ALIAS].creation.test_db_signature() /opt/hostedtoolcache/Python/3.11.3/x64/lib/python3.11/site-packages/django/db/backends/base/creation.py:371: in test_db_signature self._get_test_db_name(), _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ … -
Get raw SQL query for further execution in database client
How am I able to retrieve the produced plain SQL statement from a Django ORM query which I can use in another database client program? For example, having a ModelA.objects.filter(name='abc') queryset. I imagine setting a breakpoint somewhere in the Django/3rd-party-apps code to get a plain Select * from TabelModelA where name='abc'; statement which I can directly copy/paste into DBeaver or something else and execute without the need for further processing into the needed SQL dialect. We use Server SQL and the django-mssql package. I know the django.db.connection.queries thing and its resulting SQL/params strings, but that's not what I mean. Is there something else? Or is it doable in pyodbc? Or is there another technique? -
How can I make Django library code visible to VS2022 at develop- and run-time?
Following a Microsoft tutorial for Django, using VS2022, but I have hit what seems to be a simple scope / visibility problem. Intellisense shows references to some Django imports as "unresolvable by source". The specific error (sample): Import "django.urls" could not be resolved from source I think it indicates that the Django module is not visible to VS, and that is supported by the fact that the app does actually run OK. So I think that I have not successfully specified to VS which env it should use during development. A post from a few years ago suggests that development-time and run-time are using different Python environments, but I have followed the instructions to make sure that the (virtual) env ("env" below) is specified for the project. The project file includes this: <ItemGroup> <Interpreter Include="env"> <Id>env</Id> <Version>3.7</Version> <Description>env (Python 3.7 (64-bit))</Description> <InterpreterPath>Scripts\python.exe</InterpreterPath> <WindowsInterpreterPath>Scripts\pythonw.exe</WindowsInterpreterPath> <PathEnvironmentVariable>PYTHONPATH</PathEnvironmentVariable> <Architecture>X64</Architecture> </Interpreter> </ItemGroup> Any suggestions welcome. -
How to implement a maintenance mode for a backend on Django, Docker and AWS ECS?
I have a backend for an e-commerce app, built on Django, and hosted on AWS ECS (more precisely with Fargate). Django is in a container, and this container works with another based on Nginx. ECS is used to host several tasks of this group of containers. Theses tasks can be removed / replaced / duplicated depending on the load to the app. The aim is to respond with a 503 status codes when maintenance mode is activated. I already have a maintenance mode, based on a custom Django middleware. I use an environment variable to check if the site is in maintenance. class MaintenanceMiddleware(object): def __init__(self, get_response): self.get_response = get_response def __call__(self, request): try: maintenance = int(os.environ['MAINTENANCE']) except Exception: maintenance = 0 if maintenance: return HttpResponse(status=503) return self.get_response(request) Very simple and efficient. But to enable maintenance mode, I have to update my task definition in ECS in order to change the environment variable ; and then, redeploy the service. In this way, every running ECS task is replaced with a new task, which contains the new value of the environment variable. It's not something very easy to do. And in my point of view, a task definition must not be … -
Python django-oauth-toolkit client_credentials allows anything to go through and doesn't add user to the token
I'm using django-oauth-toolkit and I can't figure out why when I use client_credentials, I can literally insert any username/password combo and they always return a token even if the username/password combo is nowhere in the database. This is my postman request body: On the admin portal, I don't even see the user selected under "user": How do I only allow valid username/password combos to return an access token and how do I attach a user to an access token? -
Can we send form data picked up by Javascript from a html doc to Django views.py file ? If so what are the methods?
I need to pickup the data entered in a form in a HTML document using javascript and perform some operations on it and then send it to Django in the back-end to store the data in the Database. What are the ways/methods by which I can do the above scenario? I heard that we can use an Ajax call to do the described problem, but is there any other easy/secure method to do it? -
Connect my Flutter Mobile App to backend from my laptop with same internet connections
ClientException with SocketException:connection failed(OS Error: Permissio Denied,errno = 13),address = 192.168.43.155, port = 8000, uri=http://192.168.43.155:8000/api/login/ im facing this when i tried to run flutter app from mobile and connect to backend from my laptop what im going to do? -
Django AssertionError GraphQL
I have an error on my GraphQL instance, I load the /graphql endpoint and it pops up with the below error. AssertionError: You need to pass a valid Django Model in AuthorType.Meta, received "None". My schema for each is as follows: class UserType(DjangoObjectType): class Meta: model = get_user_model() class AuthorType(DjangoObjectType): class Meta: models = models.Profile class PostType(DjangoObjectType): class Meta: model = models.Post class TagType(DjangoObjectType): class Meta: model = models.Tag I also have a Query within that schema: class Query(graphene.ObjectType): all_posts = graphene.List(PostType) author_by_username = graphene.Field(AuthorType, username=graphene.String()) post_by_slug = graphene.Field(PostType, slug=graphene.String()) posts_by_author = graphene.List(PostType, username=graphene.String()) posts_bt_tag = graphene.List(PostType, tag=graphene.String()) def resolve_all_posts(root, info): return ( models.Post.objects.prefetch_related("tags").select_related("author").all() ) def resolve_author_by_username(root, info, username): return models.Profile.objects.select_related("user").get( user__username=username ) def resolve_post_by_slug(root, info, slug): return ( models.Post.objects.prefetch_related("tags") .select_related("author") .get(slug=slug) ) def resolve_posts_by_author(root, info, username): return ( models.Post.objects.prefetch_related("tags") .select_related("author") .filter(author__user__username=username) ) def resolve_posts_bt_tag(root, info, tag): return ( models.Post.objects.prefetch_related("tags") .select_related("author") .filter(tags__name__iexact=tag) ) Here is the model for the blog posts: class Profile(models.Model): user = models.OneToOneField( get_user_model(), on_delete=models.PROTECT, ) website = models.URLField(blank=True) bio = models.CharField(max_length=240, blank=True) def __str__(self) -> str: return self.user.get_username() class Tag(models.Model): name = models.CharField(max_length=50, unique=True) def __str__(self): return self.name class Post(models.Model): class Meta: ordering = ["-publish_date"] title = models.CharField(max_length=255, unique=True) subtitle = models.CharField(max_length=255, blank=True) slug = models.SlugField(max_length=255, … -
Django export PDF directly from view
I'm wondering if it's somehow possible to process the PDF export directly in the main view, and have it triggered by a button click in the template. The reasoning is that in the main view (dispatcher_single) I have 300 lines of code of data manipulation (including charts) that I would like to export to PDF and would like to avoid having to copy/paste all this code from main view to the PDF export view. Main view with a bunch of calculations: views.py def dispatcher_single(request, pk): dispatcher = Dispatcher.objects.select_related("company", "location").get(id=pk) # data manipulation here (about 300 lines of code) context = { 'dispatcher': dispatcher 'bunch_of_other_data': data } return render(request, 'dispatchers/dispatcher-single.html', context) Another view for exporting to PDF: views.py from renderers import render_to_pdf def dispatcher_statement_form(request, pk): dispatcher = Dispatcher.objects.get(id=pk) context = { 'dispatcher': dispatcher, } response = renderers.render_to_pdf("pdf/statement_form.html", context) if response.status_code == 404: raise Http404("Statement form not found.") filename = "Statement_form.pdf" content = f"inline; filename={filename}" download = request.GET.get("download") if download: content = f"attachment; filename={filename}" response["Content-Disposition"] = content return response And the render function: renderers.py def render_to_pdf(template_src, context_dict={}): template = get_template(template_src) html = template.render(context_dict) result = BytesIO() pdf = pisa.pisaDocument(BytesIO(html.encode("ISO-8859-1")), result) if pdf.err: return HttpResponse("Invalid PDF", status_code=400, content_type='text/plain') return HttpResponse(result.getvalue(), content_type='application/pdf') -
Why divs slide to the next row when setting margin, Bootstrap, Django
{% for plant in plants %} {% if forloop.counter0|divisibleby:3 %} <div class="row row-cols-3"> {% endif %} {% include 'included/_plant_cell.html' %} {% if forloop.counter|divisibleby:3 %} </div> {% endif %} {% endfor %} _plant_cell.html: <div class="plant-cell card col-md-4 m-1"> <div class="card-body"> <div class="card-text"> {{ plant.name }} </div> </div> </div> the following code results in rows that contain only two cards, and the third slides down to the next row (when margin m-1 is removed, then ok), so the general view is repeatedly row with two cards, row with one card. Expected to see rows with three cards in each. -
After submitting, data not visible on admin page
When I'm trying to submit my form, server gives me a successful GET and POST request, but when I come to the admin page it doesn't show me data from the Form. The problem is that I want to see submitted data on the admin page. I registered Model in admin.py, but still didn't help from django.contrib import admin from .models import Reservation # Register your models here. admin.site.register(Reservation) Here is my models.py from django.db import models # Create your models here. class Reservation(models.Model): name = models.CharField(max_length=100) phone_number = models.IntegerField() email = models.EmailField() reservation_date = models.DateField() reservation_slot = models.SmallIntegerField(default=10) def __str__(self): return self.email reservation.html where I trying to submit form {% extends 'base.html' %} {% load static %} {% block base%} <section> <article> <h1>Make a reservation</h1> <!--Begin row--> <div class="row"> <!--Begin col--> <div class="column"> {% csrf_token %} <form method="POST" id="form"> <!-- {% csrf_token %} --> <p> <label for="first_name">Name:</label> <input type="text" placeholder="Your Name" maxlength="200" required="" id="first_name"> </p> <p> <!-- Step 9: Part one --> <label for="reservation_date">Reservation date:</label> <input type="date" placeholder="Your reservation" maxlength="200" required="" id="reservation_date"> </p> <p> <label for="reservation_slot">Reservation time:</label> <select id="reservation_slot"> <option value="0" disabled>Select time</option> </select> </p> <button type="button" id="button">Reserve</button> </form> </div> <!--End col--> <!--Begin col--> <div class="column"> <h2>Bookings For <span … -
Poetry and Vercel issue
I have found out about Poetry recently, and I am amazed by how well it works compare to the regular pip and whatnot. But I am facing issues with when I try to host my Django app on Vercel. Since Vercel have no functionality of poetry I cannot host my django over there. I have tried chatgpt and the solution is to modify the vercel.json file which I did. { "build": { "env": { "POETRY_VERSION": "1.1.4" } }, "builds": [ { "src": "test/wsgi.py", "use": "@vercel/python", "config": { "maxLambdaSize": "15mb", "runtime": "python3.9" } } ], "routes": [ { "src": "/(.*)", "dest": "test/wsgi.py" } ] } but then I got these errors. [ERROR] Runtime.ImportModuleError: Unable to import module 'vc__handler__python': No module named 'django' then I tried this solution text but when I followed this solution my app would not even deploy it would give error even the building part Error: Command failed: python3.9 -m poetry export --without-hashes -f requirements.txt --output requirements.txt and ImportError: urllib3 v2.0 only supports OpenSSL 1.1.1+, currently the 'ssl' module is compiled with 'OpenSSL 1.0.2k-fips 26 Jan 2017'. See: https://github.com/urllib3/urllib3/issues/2168 so after exhausting everything that I could am here for help. -
multiple try/except , n etx one catch exception after first one handle it
I have 2 try except block, the second one trigger the first one exception i'm expecting that the first one handle the first exception and that the second one not trigger that exception the second try/catch block catch the exception generated in the first one unless i handle it, why ? can someone help me solve this issue ? try: if isinstance(request.data['name'],str): progetto.name = request.data['name'] progetto.save() else: raise TypeError('Validation error') except TypeError as te: print('type error catched error: ',te) errori.append({'name': str(te)}) except Exception as e: print('name catched error: ',e) errori.append({'name': str(e)}) try: progetto.expiration = request.data['expiration'] progetto.save() except Exception as ex: print('exp block catched error: ',ex) errori.append({'expiration': str(ex)}) -
Can't fill my custom user model in django with automatic script
Made a new custom django user model class UserProfile(User): phone_number = models.CharField(max_length=20, verbose_name='Номер телефона', unique=True) Trying to Automatize filling it wit information from API with this script: import requests import json from django.contrib.auth.models import User from tarifs.models import Software_Products, UserProfile url = "My API" headers = { "Content-Type": "application/json", "Authorization": "Basic ..." } subscribers = {} page = 0 size = 300 while True: data = {"page": page, "size": size} response = requests.post(url, data=json.dumps(data), headers=headers) data = json.loads(response.content) if not data.get('subscribers'): break for subscriber in data['subscribers']: code = subscriber['code'] name = subscriber['name'] subjects = subscriber.get('subjects', []) reg_numbers = subscriber.get('regNumbers', []) if reg_numbers: subscribers[name] = { 'code': code, 'name': name, 'subjects': subjects, 'reg_numbers': reg_numbers } page += 1 for name, reg_numbers_data in subscribers.items(): user_profile, created = UserProfile.objects.get_or_create(name=name) for reg_number in reg_numbers_data['reg_numbers']: software_product, created = Software_Products.objects.get_or_create( user_id=user_profile, reg_number=reg_number, defaults={'name': reg_numbers_data['name']} ) if not created: software_product.name = reg_numbers_data['name'] software_product.save() Running this script ends with this error: Traceback (most recent call last): File "c:\work\Bizstart\bizstart_django\bizstartprj\parse2.py", line 3, in from django.contrib.auth.models import User # Перенесите этот импорт в начало ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ File "C:\work\bizstart\bizstart_django\bizstartenv\Lib\site-packages\django\contrib\auth\models.py", line 3, in from django.contrib.auth.base_user import AbstractBaseUser, BaseUserManager File "C:\work\bizstart\bizstart_django\bizstartenv\Lib\site-packages\django\contrib\auth\base_user.py", line 49, in class AbstractBaseUser(models.Model): File "C:\work\bizstart\bizstart_django\bizstartenv\Lib\site-packages\django\db\models\base.py", line 127, in new app_config = apps.get_containing_app_config(module) …