Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Django socketio process
I'm dealing with a little problem that I need to solve. I have an application in Django and I need a websocket, but I don't like Django channels, so I created a socket server in Flask and I'm trying to connect Django to it, by creating middleware that when called starts a process that sends messages through the process what it has in the queue But either the shared variable doesn't work or the process itself doesn't work properly. Please if you have any advice or solution write also how to terminate the process with socket when django terminates This is my code: socket.py --- import socketio import json from project.settings import SOCKET_CONFIG, MANAGER from multiprocessing import Process sio = socketio.Client() class Socket: queue = MANAGER.list() def __init__(self, get_response): self.get_response = get_response thread = Process(target=Socket.process_loop, args=()) thread.start() def __call__(self, request): return self.get_response(request) @staticmethod def process_loop(): sio.connect('http://{}:{}'.format(SOCKET_CONFIG["host"],SOCKET_CONFIG["port"])) while True: try: import time time.sleep(1) data = Socket.queue.pop(0) sio.emit('message', data) except BaseException as e: print(e) settings.py --- import os, subprocess from multiprocessing import Process, Manager MANAGER = Manager() SOCKET_CONFIG={ "host":"localhost", "port":8001 } ... -
Unable to get Docker with React and Django to work in Ubuntu - forbidden access
I am trying to get my React and Django project that is using docker-compose to work on AWS Ubuntu. It works on my mac. However, I cant get it working on my IP. I have allowed port 80 inbound traffic. Here are the docker-compose up logs https://gist.github.com/axilaris/5844a146a08ae80256f064572a1f0ab6 One thing I noticed is nginx where it serves the React files seems to be forbidden: nginx_1 | 2024/03/31 14:57:00 [error] 29#29: *1 directory index of "/var/www/frontend/" is forbidden, client: 172.20.4.193, server: , request: "GET / HTTP/1.1", host: "172.21.4.130" nginx_1 | 172.20.4.193 - - [31/Mar/2024:14:57:00 +0000] "GET / HTTP/1.1" 403 153 "-" "ELB-HealthChecker/2.0" "-" nginx_1 | 2024/03/31 14:57:01 [error] 29#29: *2 directory index of "/var/www/frontend/" is forbidden, client: 172.20.1.172, server: , request: "GET / HTTP/1.1", host: "172.21.4.130" nginx_1 | 172.20.1.172 - - [31/Mar/2024:14:57:01 +0000] "GET / HTTP/1.1" 403 153 "-" "ELB-HealthChecker/2.0" "-" Here is my docker-compose.yaml file version: '3.7' services: # Redis redis: image: redis:alpine container_name: redis ports: - "6379:6379" backend: volumes: - .:/django - static:/static env_file: - .env build: context: ./backend ports: - "8000:8000" container_name: backend_container frontend: build: context: ./frontend volumes: - frontend:/app/build container_name: frontend_container nginx: build: context: ./nginx volumes: - static:/static - frontend:/var/www/frontend ports: - "80:80" depends_on: - redis - backend … -
Root path analogue in uWSGI as in Uvicorn
Uvicorn has the option --root-path (https://www.uvicorn.org/settings/#http) that helps a lot if the application is mounted to a specific path, distinct to /. For example, in case of a Django application I can run it with: uvicorn myproj.asgi:application --host=localhost --port=8001 --root-path="/myproj-custom-path" So if I configure the Nginx location /myproj-custom-path/ as proxy_pass http://localhost:8001/, I can access the application by http://localhost:80/myproj-custom-path with all the functionality, including the Admin panel, without the need to specify the root path anywhere else in the project. Is there a similar option or a way to do the same with uWSGI? -
Django register function accepting a new user while the login function can't find it
I'm creating a site using django, python and html. I have an app called account which I have currently written two functions for: register and login_view. My register function works properly, accepting a user unless their username is already taken or their two passwords are not a match. However, my login_view function doesn't seem to recognize the same user that has just been created in the register page, giving me this error: return render(request, 'account/login.html', {'error': 'Wrong username or password.'}) Here are the files inside my account folder I've worked on so far: views.py: from django.shortcuts import render from django.contrib.auth.models import User from django.contrib.auth import authenticate, login, logout def register(request): if request.method == 'POST': if request.POST['password1'] == request.POST['password2']: the_username = request.POST['username'] try: the_user = User.objects.get(username = the_username) return render(request, 'account/register.html', {'error': 'Username already taken. Please choose another one!'}) except User.DoesNotExist: new_user = User.objects.create(username = the_username, password = request.POST['password1']) return render(request, 'account/profile.html') else: return render(request, 'account/register.html', {'error': 'Passwords do not match.'}) else: return render(request, 'account/register.html') def login_view(request): if request.method == 'POST': the_user = authenticate(username = request.POST['username'], password = request.POST['password']) if the_user is not None: login(request, the_user) return render(request, 'account/profile.html') else: return render(request, 'account/login.html', {'error': 'Wrong username or password.'}) else: return render(request, … -
Django - ModuleNotFoundError: No module named 'backend'
I have problem with "ModuleNotFoundError" in my Django app. This problem start when i write serializers.py and other files in my app. All code you see it in my Github This code is without syntax errors because I use PyCharm IDE. When I start server I get this error: PyCharm IDE with terminal after run python server I would appreciate any comments on where I made a mistake. I expect my code to work correctly. -
Does Python being a loosely typed programming language make it less secure?
We have this huge issue as a team in choosing a programming stack to develop a web application for a client, one group prefers Django, while the other prefer Springboot claiming that python is a loosely typed programming language, and that makes it less secure unlike Java. In terms of security is Java better than Python? -
sorl-thumbnail adds a background color when padding is used
I'm using sorl-thumbnail and it works as expected except for when I use padding (which I have to) a white background is added. I know I can change that color, but I want no color (i.e transparency). Is there any hack or another library to fix this? -
Can't connect to local postgresql server from my docker container
I'm trying to connect to local postgresql server from my docker container. I'm using Ubuntu 22.04.4. This is my docker-compose.yml. version: '3' services: ... backend: build: context: '.' dockerfile: 'Dockerfile' ports: - '8000:80' - '8001:8001' env_file: - .env-docker image: backend-django:latest ... This is my .env-docker. DEBUG=True SECRET_KEY=****** DATABASE_USER=postgres DATABASE_NAME=postgres DATABASE_PASSWORD=postgres DATABASE_HOST=host.docker.internal DATABASE_PORT=5432 This is my Dockerfile. FROM python:3.11 ENV PYTHONBUFFERED 1 ... EXPOSE 8000 CMD ["gunicorn", "-b", "0.0.0.0", "config.wsgi"] It was working in Windows but not in Ubuntu now. Is it related to postgresql? I'm using the same version of postgresql and I can connect to local postgresl using PgAdmin. How can I connect to postgresql server from my docker container? -
Why ProductHunt api dont work with Python?
Why i can not work with Product Hunt api in python. My api key is correct `ph = ProductHunt(api_key='WUY0eh1BU_-BnIOtYcFBSEk2UuwUsFCTOXzbZe0CYFY') daily_products = ph.get_daily()` Traceback (most recent call last): File "C:\Users\eesca\PyProjects\solkit\test.py", line 4, in <module> daily_products = ph.get_daily() ^^^^^^^^^^^^^^ File "C:\Users\eesca\PyProjects\solkit\.venv\Lib\site-packages\producthunt\producthunt.py", line 41, in get_daily products = data.get('data', {}).get('posts', {}).get('edges', []) ^^^^^^^^^^^^^^^^^^^^^^^^ AttributeError: 'NoneType' object has no attribute 'get' -
why i have to put extra space in before write option selected because it show error if i don't ' option:selected'
data: { product_id: $(this).data('index'), product_quantity: $('#select' + theproductid + ' option:selected').text(), csrfmiddlewaretoken:"{{csrf_token}}", action:'post' }, why in product_quantity where i used option selected i have to put space before option because if i don't put space it show this error product_quantity = int(request.POST.get('product_quantity')) ValueError: invalid literal for int() with base 10: '' can anyone explain. -
Django Arrayfield migration to cloud sql (Postgresql) not creating the column
The project is already running and I tried adding an ArrayField to one of the models. When makemigrations and migrate it applies all migrations but when trying insert a record to the field it says: django.db.utils.ProgrammingError: column "<ArrayField>" of relation "<app>_<model>" does not exist. When checking Cloud SQL (PostgreSQL) have create all columns except for this one in particular. -
how can debugg field id error in the database schema?
TypeError at /contact2/ Field 'id' expected a number but got datetime.datetime(2024, 3, 31, 9, 52, 52, 728466, tzinfo=datetime.timezone.utc). Request Method: POST Request URL: http://127.0.0.1:8000/contact2/ Django Version: 4.2.7 Exception Type: TypeError Exception Value: Field 'id' expected a number but got datetime.datetime(2024, 3, 31, 9, 52, 52, 728466, tzinfo=datetime.timezone.utc). Exception Location: C:\Users\Hamprey Aganyo Ndemo\AppData\Local\Programs\Python\Python312\Lib\site-packages\django\db\models\fields_init_.py, line 2055, in get_prep_value Raised during: djangoagain.views.contact Python Executable: C:\Users\Hamprey Aganyo Ndemo\PycharmProject\djangoagain\venv\Scripts\python.exe Python Version: 3.12.0 Python Path: ['C:\Users\Hamprey Aganyo Ndemo\PycharmProject\djangoagain', 'C:\Users\Hamprey Aganyo ' 'Ndemo\AppData\Local\Programs\Python\Python312\python312.zip', 'C:\Users\Hamprey Aganyo ' 'Ndemo\AppData\Local\Programs\Python\Python312\DLLs', 'C:\Users\Hamprey Aganyo ' 'Ndemo\AppData\Local\Programs\Python\Python312\Lib', 'C:\Users\Hamprey Aganyo Ndemo\AppData\Local\Programs\Python\Python312', 'C:\Users\Hamprey Aganyo Ndemo\PycharmProject\djangoagain\venv', 'C:\Users\Hamprey Aganyo ' 'Ndemo\PycharmProject\djangoagain\venv\Lib\site-packages', 'C:\Users\Hamprey Aganyo ' 'Ndemo\AppData\Local\Programs\Python\Python312\Lib\site-packages'] Server time: Sun, 31 Mar 2024 09:52:54 +0000 to access the database -
operator class "gin_trgm_ops" does not exist for access method "gin"
psycopg2.errors.UndefinedObject: operator class "gin_trgm_ops" does not exist for access method "gin" Hello everybody, this is the whole message when I try to run pytest on my project which is written in Python/Django + db is postgresql and all sitting inside docker. I build a project on docker with django-cookiecutter template, all settings are default. I put a gin index to one of my string fields, migrations running successfully, pg_trgm extention is being created successfully, but if I try to test my project with pytest I got this error. Here is my pytest.ini [pytest] DJANGO_SETTINGS_MODULE = config.settings.test Here is my test settings file's database configuration: test.py DATABASES['test'] = { # noqa 'ENGINE': 'django.contrib.gis.db.backends.postgis', 'NAME': 'test', 'PASSWORD': 'test', 'USER': 'test', 'HOST': 'localhost', 'PORT': 5454, } This is part of the migration which creates the extention pg_trgm and puts an index to the field given migrations.AddIndex( model_name='<model_name>', index=django.contrib.postgres.indexes.GinIndex(fields=['field_name'], name='field_name_gin_idx', opclasses=['gin_trgm_ops']), ), And this is the whole traceback which I am getting: self = <django.db.backends.utils.CursorWrapper object at 0xffff7244dbb0> sql = 'CREATE INDEX "bank_name_gin_idx" ON "financing_graincreditagrobankworksheet" USING gin ("bank_name" gin_trgm_ops)', params = None ignored_wrapper_args = (False, {'connection': <django.contrib.gis.db.backends.postgis.base.DatabaseWrapper object at 0xffff7d096b80>, 'cursor': <django.db.backends.utils.CursorWrapper object at 0xffff7244dbb0>}) def _execute(self, sql, params, *ignored_wrapper_args): self.db.validate_no_broken_transaction() with self.db.wrap_database_errors: if … -
How do I connect a website to the postgres database?
I am developing a website using django rest framework and react. And I transferred from the test VM to the timeweb cloud virtual cloud and ran into the problem that when connecting to the site, the site starts without information from the postgres database. And also when starting the react web server.the js command "npm run start" outputs an error in browsers on remote client computers: JSON.parse: unexpected character at line 1 column 1 of the JSON data I think this is due to the fact that there is no connection to the database server in postgresql. But, I've already tried adding addresses to ALLOWED HOSTS. I changed both the database and Django. P.S. The username, passwords and addresses are not real. $ cat node_modules/react-scripts/config/webpackDevServer.config.js ... // want to allow setting the allowedHosts manually for more complex setups allowedHosts: disableFirewall ? 'all' : [allowedHost], headers: { 'Access-Control-Allow-Origin': '*', 'Access-Control-Allow-Methods': '*', 'Access-Control-Allow-Headers': '*', }, allowedHosts: [ // Ваш список разрешенных хостов здесь 'localhost', '127.0.0.1', 'IPADDR1' ], ... $ cat settings.py ... ALLOWED_HOSTS = ['127.0.0.1', 'localhost', 'IPADDR1', 'HOST1'] ... DATABASES = { 'default': { 'ENGINE': 'django.db.backends.postgresql', 'NAME': 'BASE', 'USER': 'USER', 'PASSWORD': 'PASSWORD', 'HOST': 'IPADDR1', 'PORT': '5432', } } $ cat /etc/postgresql/14/main/pg_hba.conf ... … -
when clicked, JS is taking mw to wrong url in backend (django)
when i click on link it is taking me to '/product/api/product/2' URL but I have defined /api/product/str:pk/ for backend I'm using django. import React from 'react' import { Card } from 'react-bootstrap' import Rating from './Rating' import { Link } from 'react-router-dom' // we are using this to load in the same page without reloading whole page function Product({ product }) { return ( <Card className="my-3 p-3 rounded"> <Link to={`/product/${product._id}`}> {/* here we are using link in place of a & to in place of href */} <Card.Img src={product.image} /> </Link> <Card.Body> <Link to={`/product/${product._id}`}> <Card.Title as="div"> <strong>{product.name}</strong> </Card.Title> </Link> <Card.Text as="div"> <div className="my-3"> <Rating value={product.rating} text={`${product.numReviews} reviews`} color={'#f8e825'} /> </div> </Card.Text> <Card.Text as="h3"> ${product.price} </Card.Text> </Card.Body> </Card> ) } export default Product; when I place my cursor on product link it is showing the correct URL, but when i click on that link it is taking to wrong pattern on backend server. -
Add an http GET/POST entry point to a Django with channels websocket
I'm new in Django and I'm building a site for booking. I build the front-end in vue 3 and the back-end in django using channels. I've implemented the websockets but now I'm trying to add a GET or POST entry point for the confirmation via link (like "url/api/confirm/confirm_code" or "url/api/confirm/confirm_code=code") in a mail I sent from the back-end. The problem is that my back-end never receive the request. I tried like this: app_name.urls from django.contrib import admin from django.urls import path, include urlpatterns: list[path] = [ path('admin/', admin.site.urls), path('api/', include('app.routing')), ] app.routing from django.urls import path from app.consumers.view import ViewConsumer from app.consumers.booking import BookingConsumer from app.consumers.account import AccountConsumer from app.consumers.profile import ProfileConsumer from app.http.confirm_reservation import confirm_reservation websocket_urlpatterns = [ path(r"ws/view/", ViewConsumer.as_asgi()), path(r"ws/booking/", BookingConsumer.as_asgi()), path(r"ws/account/", AccountConsumer.as_asgi()), path(r"ws/profile/", ProfileConsumer.as_asgi()), ] urlpatterns = [ path(r"confirm/<str:confirm_code>/", confirm_reservation, name="confirm_reservation"), ] app.http.confirm_reservation from django.http import JsonResponse from app.services.booking import BookingService def confirm_reservation(request, confirm_code: str): print(request) print(confirm_code) return JsonResponse(BookingService().confirm_reservation(request)) Least but not last, if you have any suggestions for a better code than I wrote, please tell me in a comment. Thanks. I'm using my own site and postman (http://192.168.1.5:8080/api/confirm/1234/) to try sending the confirmation code but the front-end get "Cannot GET /api/confirm/1234/" and the back-end doesn't … -
Cannot make Django run the frontend from Vite's build ("was blocked because of a disallowed MIME type (“text/html”)")
My frontend is a React app that I compiled using npm run build. Once the build folder is copied to the django project, I go in my Django virtualenv and run python3 manage.py collectstatic and python3 manage.py runserver When I run the server, I can read two errors in the console: Loading module from “http://127.0.0.1:8000/assets/index-sLPpAV_Z.js” was blocked because of a disallowed MIME type (“text/html”). The resource from “http://127.0.0.1:8000/assets/index-6ReKyqhx.css” was blocked due to MIME type (“text/html”) mismatch (X-Content-Type-Options: nosniff). and one warning: Loading failed for the module with source “http://127.0.0.1:8000/assets/index-sLPpAV_Z.js”. (Django) settings.py STATIC_URL = 'static/' STATICFILES_DIRS = [ os.path.join(BASE_DIR, 'build/static'), ] STATIC_ROOT = os.path.join(BASE_DIR, 'static') package.json ... "scripts": { "dev": "vite", "build": "rm -rf ../backend/build && tsc && vite build && cp -r build ../backend/build", "lint": "eslint . --ext ts,tsx --report-unused-disable-directives --max-warnings 0", "preview": "vite preview" }, ... I am confuse because there is no static folder in the build folder. Django gives me this warning: WARNINGS: ?: (staticfiles.W004) The directory '/home/user/project/backend/build/static' in the STATICFILES_DIRS setting does not exist. The build folder looks like this: build/ ----assets/ --------index-<randomString>.css --------index-<anotherString>.js ----index.html ----vite.svg -
Open-Source Discord Bot Verification System
I am contributing to an open source project that works as a verification system for discord servers. It deletes all data immediately after the user is verified and is prevented spam on many servers and websites.. Here is the Github link: https://github.com/human-internet. Do you have any feedback or points of improvement for me, in particular on how to receive an independent security review? Do you have any feedback or points of improvement for me, in particular on how to receive an independent security review? -
unable to create user account
my create user work currectlly until i use a signal to create customer (user profile) after user created and i get error unable to create user account # signal from django.conf import settings from django.db.models.signals import post_save from django.dispatch import receiver from store.models import Customer @receiver(post_save, sender=settings.AUTH_USER_MODEL) def create_customer_for_new_user(sender, instance, created, **kwargs): if created: Customer.objects.create(user=instance) # app from django.apps import AppConfig class StoreConfig(AppConfig): default_auto_field = 'django.db.models.BigAutoField' name = 'store' def ready(self): import store.signals.handlers -
django allauth settings.SOCIALACCOUNT_ENABLED overwritten?
django-allauth provides a seettings parameter SOCIALACCOUNT_ENABLED that is used in urls.py to add conditionally socialaccount urls: allauth/urls.py: if app_settings.SOCIALACCOUNT_ENABLED: urlpatterns += [path("social/", include("allauth.socialaccount.urls"))] in html templates there is the same parameter used e.g. in allauth/templates/account/login.html: {% if SOCIALACCOUNT_ENABLED %} {% include "socialaccount/snippets/login.html" with page_layout="entrance" %} {% endif %} BUT: in templates it does not reflect settings.SOCIALACCOUNT_ENABLED but is taken from the apps.is_installed status: allauth/app_settings.py: class AppSettings(object): .... @property def SOCIALACCOUNT_ENABLED(self): return apps.is_installed("allauth.socialaccount") .... That means in summary: settings.SOCIALACCOUNT_ENABLED -> effect on included allauth url patterns settings.INSTALLED_APPS[..., 'allauth.socialaccount'..] -> effect on html templates {% if SOCIALACCOUNT_ENABLED %} Can anyone explain why this makes sense?? It did cost me quite some time to understand why templates do not react on "normal" settings parameter. -
How to open specific Accordion item in Django using Bootstrap?
I have a Django app with a page that contains a Bootstrap Accordion. I have a form in the third accordion item. On submit within that form I want the page to refresh to the same accordion item - I have some feedback messaging there that want to display to the user. Currently on Submit the page refreshes to the default item - in my case that's the first accordion item. I have tried appending /#collapseThree to the url, but the page refreshes to the default view. Thanks, Andrew -
Unable to get SaaS data for tenant using django-tenants, showing all data not tenant specific data
I am building a web application using django-tenants and have followed the documentation thoroughly, but still having issues showing data for a tenant specific to its subdomain and schema. Instead, I am getting all the data from the public schema, not the tenant specific schema regardless of the URL I am accessing. tenant.models has my tenant and subdomain models. And then apps are my django apps I want across tenants. I believe my issue is how I have my shared and tenant apps, but from many different combinations nothing changes on the front end. tenant.models.py: class MspCompany(MyBaseModel, TenantMixin): company_name = models.CharField(max_length=60) industry_type = models.CharField(max_length=68, choices=INDUSTRY_TYPE) email = models.EmailField(max_length=150, unique=True) owner_name = models.CharField(max_length=60, blank=True, null=True) description = models.TextField(blank=True, null=True) picture = models.ImageField(upload_to='images/company',blank=True,null=True) users = models.ForeignKey(settings.AUTH_USER_MODEL, related_name='users', on_delete=models.CASCADE ) class Domain(DomainMixin): pass shared apps and tenant apps: SHARED_APPS = [ 'django_tenants', 'tenants', 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'whitenoise.runserver_nostatic', 'django.contrib.sites', "mathfilters", "crispy_forms", # Crispy Forms "social_django", "django_extensions", 'allauth', 'allauth.account', 'allauth.socialaccount', 'allauth.socialaccount.providers.google', 'multiselectfield', 'phone_field', 'djstripe', 'chat', 'ckeditor', 'ckeditor_uploader', 'taggit' ] TENANT_APPS = [ 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'django.contrib.sites', "dashboards", "apps", 'accounts', "layouts", "components", "pages", ] You will see from the images below, the data is the same regardless of the subdomain … -
query in objects with django orm with a containing sentence
i have some city like this: In [99]: City.objects.filter(title='Hamilton') Out[99]: <QuerySet [<City: hamilton>] i have some sentences like this: sentence = '3101A 1280 Main Street West Hamilton ON L8S 4K1' how can i find cities that contains its title with this sentence? Note: i have used this method but it is not True. because this query is useful for list not string in django: In [100]: City.objects.filter(slug__in=sentence) Out[100]: <QuerySet []> -
Django-Cross Model Query 3 Models
I am working on a practice project to create 3 separate pages that is Brand Page, Car Model Page and Car Model Variant detail page. I am working on a project with three models car brands, car model, car model variants When an user opens the Car model page they should see the list of variants in that car model class BrandName(models.Model): FullName = models.CharField(max_length= 100) Slogan = models.CharField(max_length = 255) slug = models.SlugField(unique=True) def __str__(self): return f"{self.FullName}" class CarModel(models.Model): Brand = models.ForeignKey(BrandName, on_delete = models.CASCADE,null=True, related_name = "brands") ModelName = models.CharField(max_length = 200) slug = models.SlugField(unique=True) def __str__(self): return f"{self.ModelName}" class CarModelVariant(models.Model): ModelVariantName = models.CharField(max_length = 100) Brandname = models.ForeignKey(BrandName, on_delete = models.CASCADE, null = True, related_name="brands1") Model1 = models.ForeignKey(CarModel, on_delete = models.CASCADE, null = True, related_name = "model1") Doors = models.IntegerField SeatingCapacity = models.IntegerField def __str__(self): return f"{self.ModelVariantName}" **In views.py of the app ** from django.shortcuts import render from django.http import HttpResponse from . models import CarModelVariant, CarModel, BrandName from django.views.generic import ListView, DetailView class CarModelVariantView(ListView): template_name = "carlist.html" model = CarModelVariant def get_queryset(self): list_model = super().get_queryset() data = list_model.filter(Model1= CarModel_instance) return data In urls.py of the app `from django.urls import path from . import views urlpatterns = … -
Python Django. No URL to redirect to. Either provide a url or define a get_absolute_url method on the Model
Всем привет. Столкнулся с проблемой, которую не могу решить. В моделях прописаны get_absolute_url, но почему-то получаю ошибку: "No URL to redirect to. Either provide a url or define a get_absolute_url method on the Model." Вот код (models.py): class Vendor(models.Model): name = models.CharField(max_length=255, default='') vendor_type = models.ForeignKey('VendorType', on_delete=models.PROTECT, null=False) def __str__(self): return self.name def get_absolute_url(self): return reverse_lazy('motherboard_vendors') class VendorType(models.Model): class Type(models.IntegerChoices): MOTHERBOARD = 1, 'Материнская плата' CPU = 2, 'Процессор' STORAGE = 3, 'Накопитель памяти' VIDEOCARD = 4, 'Видеокарта' RAM = 5, 'Оперативная память' MONITOR = 6, 'Монитор' SOFTWARE = 7, 'Программное обеспечение' PROJECTOR = 8, 'Проектор' PRINTER = 9, 'Принтер' name = models.CharField(choices=Type.choices, max_length=255, default='') def __str__(self): return self.name def get_absolute_url(self): return reverse_lazy('motherboards') forms.py: class AddMotherboardVendorForm(forms.ModelForm): class Meta: model = Vendor fields = ['name'] widgets = { 'name': forms.TextInput(attrs={'class': 'form-input'}), } def clean_name(self): name = self.cleaned_data['name'] if len(name) > 50: raise ValidationError("Длина превышает 50 символов") return name def save(self): vendor = super().save(commit=False) vendor.vendor_type_id = VendorType.Type.MOTHERBOARD vendor.save() return vendor.get_absolute_url() views.py: class AddMotherboardVendor(LoginRequiredMixin, CreateView): form_class = AddMotherboardVendorForm template_name = "home/motherboard/addmotherboardvendor.html" title_page = 'Добавление производителя материнской платы' def get_context_data(self, **kwargs): context = super().get_context_data(**kwargs) context['title'] = self.title_page return context urls.py: path('motherboard_vendors/add_motherboard_vendor/', views.AddMotherboardVendor.as_view(), name='add_motherboard_vendor') Раньше была другая сущность Vendor: class MotherboardVendor(models.Model): motherboard_vendor_name = models.CharField(max_length=255, default='') …