Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
the second form on the Django page is not being processed
I'm writing a site on Django and I ran into a problem. I have a page on the site that has a form. Then I added functionality so that when a button is pressed on this page, a modal window will appear, which also has a form. But if I want to send data from the form that is in the modal window, I am sent data from the form that is on the page, even if there is no data there and the button was not pressed. How can I change this behavior? This is my views.py file: @login_required(login_url='signin') def update_password_view(request, url_username): try: current_user = user_model.objects.get(url_username=url_username) except ObjectDoesNotExist: print("Incorrect user data") return redirect('index_page') if request.method == 'POST': form = UpdatePasswordForm(request.POST) if form.is_valid(): user_password = form.cleaned_data['password'] current_user.set_password(user_password) current_user.save() messages.success(request, "Your password has been updated successfully") else: print(form.errors) else: form = UpdatePasswordForm() img_base64, totp_secret = form_qrcode_service(current_user) return render(request, 'account/update-password.html', {'form': form, 'second_form': InputTokenForm(request.POST or None), 'qr_code': img_base64, 'totp_secret': totp_secret}) def input_code_form_view(request, url_username): try: current_user = user_model.objects.get(url_username=url_username) except ObjectDoesNotExist: print("Incorrect user data") return redirect('index_page') if request.method == 'POST': form = InputTokenForm(request.POST) if form.is_valid(): print(form.cleaned_data['code']) else: print(form.errors) return redirect('update-password', url_username=url_username) update_password_view should be responsible for processing the form on the main page, and … -
Post matching query does not exist. When post exists in DB
I'm creating a simple blog with a Django backend using MongoDB to store blog posts and their metadata. Everything worked find when I was testing with a local mongodb instance, but when I switched to an atlas hosted database I started getting the following error. The current Post model is ` class Post(models.Model): _id = models.UUIDField( primary_key=True, default=uuid.uuid4, editable=False) title = models.CharField( max_length=50, help_text='Post title. equivalent to obsidian file name') publish_date = models.DateField() last_edited = models.DateField(auto_now=True) content = models.TextField(blank=False) summary = models.TextField(blank=True) tags = models.CharField(max_length=20, blank=False) choices = [ ('published', 'published'), ('draft', 'draft'), ('private', 'private') ] status = models.CharField( choices=choices, default='published', max_length=20, blank=False,) class Meta: pass def get_absolute_url(self): return reverse('post', args=[self._id]) def __str__(self): return self.title To debug I overrode the get_object method as follows: ` def get_object(self, *args, **kwargs): kwargs = self.kwargs kw_id = kwargs.get('pk') all_results = Post.objects.filter() print(all_results.first()._id == str(kw_id)) result = Post.objects.get(_id=str(kw_id)) print("result:", result) return result assuming there is only one test post in the DB, all_results = Post.objects.filter() returns the post, but some of its element (e.g. all_results.first().content are None even though it is populated in the DB. the main problem is that when trying to filter or get based on the value of the _id field … -
How to pass form data to another Django class
Не могу решить проблему связанный с ошибкой Please tell me what is my mistake? from django.urls import path from .views import * app_name = 'data_array_do' urlpatterns = [ path('planFormView/', PlanFormView.as_view(), name='planFormView'), path('planListView/', PlanListView.as_view(), name='planListView'), ] from .forms import * from .models import * from django.shortcuts import render, redirect from django.views import View from django.urls import reverse from django.db.models import Q class PlanFormView(View): form_class = Filter template_name = 'planFormView.html' def get(self, request): form = self.form_class() return render(request, self.template_name, {'form': form}) def post(self, request): form = self.form_class(request.POST) if form.is_valid(): year = str(form.cleaned_data['year']) version = str(form.cleaned_data['version']) url = reverse('data_array_do:planListView', kwargs={"year": year, "version": version}) return redirect(url) return render(request, self.template_name, {'form': form}) class PlanListView(View): template_name = 'planListView.html' def get(self, request): year = request.GET.get('year', '') version = request.GET.get('version', '') if not year or not version: return render(request, self.template_name, {'error_message': 'Нет данных'}) my_data = FifthLevelCollection.objects.filter(Q(level_four_collection__third_level_collection__second_level_object__first_level_object__reporting_year__title=year) | Q(version=version)) return render(request, self.template_name, {'my_data': my_data}) from django import forms from .models import * # Форма для переменных фильтрации class Filter(forms.Form): year = forms.ModelChoiceField(label="Отчетный год", queryset=Year.objects.all()) version = forms.ModelChoiceField(label="Версия плана", queryset=Version.objects.all()) The user on the page fills out the form and sends it, then based on the form data, the data from the database is filtered and displayed on the page. … -
Caught in loop where timestamp value is overriding every other item's value in a list
New to Django and have been stuck on this issue for a couple days now. I am trying to display timestamp data for when an item was created in my database. I have two Django classes that look like this: class Game(models.Model): title = models.CharField(max_length=200) description = models.TextField(blank=True, null=True, max_length=500) image = models.URLField(blank=True, null=True, max_length=500) genre = models.CharField(blank=True, null=True, max_length=200) platform = models.CharField(blank=True, null=True, max_length=200) developer = models.CharField(blank=True, null=True, max_length=200) publisher = models.CharField(blank=True, null=True, max_length=200) added_by = models.CharField(max_length=64) def __str__(self): return f"ID# { self.id }: { self.title }" class Playinglist(models.Model): title = models.CharField(max_length=200) user = models.CharField(max_length=64) game_id = models.IntegerField() started_on = models.DateTimeField(auto_now_add=True) The Game model stores data about a game, and when I click a button I will add a game into my playinglist model, which should automatically get the time it was inserted into that model. To add a game into my playinglist I am using this function: def add_to_playinglist(request, game_id): obj = Playinglist.objects.filter(game_id=game_id, user=request.user.username) playing_game = Playinglist.objects.filter(game_id=game_id, user=request.user.username) game = Game.objects.get(id=game_id) if obj: obj.delete() game playing_game return redirect("profile") else: obj = Playinglist() obj.user = request.user.username obj.game_id = game_id obj.save() game playing_game return redirect("profile") And to display all the items in that respective user's Playlist I am using this … -
Django - Upload a file and populate field model with file name
I'm using Django and want to build an upload file page. When user upload a file, it stores it in a folder. I wan't to get the original file name to populate a field in my model (SourceFile.file). File is well uploaded, but I can't reach request.FILES properties, even with request.FILES.get('uploaded_to') or request.FILES['uploaded_to'] to fill in SourceFile.file with file name. How to achieve this ? My source is official documentation. models.py from django.db import models class SourceFile(models.Model): file = models.CharField() uploaded_to = models.FileField(upload_to ='/uploads/') serializers.py from rest_framework import serializers from .models import * class SourceFileSerializer(serializers.ModelSerializer): class Meta: model = SourceFile fields = ['file', 'uploaded_to'] views.py class SourceFileViewSet(viewsets.ModelViewSet): serializer_class = SourceFileSerializer def list(self, request): return Response("GET API") def upload_file(request): if request.method == "POST": form = SourceFile(request.POST, request.FILES) # Nothing happened file_uploaded = request.FILES.get('uploaded_to') file_name = file_uploaded.name request.POST['file'] = file_name # if form.is_valid(): form.save() return HttpResponseRedirect("/success/url/") else: form = SourceFile() return render(request, "upload.html", {"form": form}) -
How to access relation 'belongs to' from template?
I was wondering if there's a way to access the relation 'Belongs To' using Jinja in a Django project. What I mean is: I have this model representing Student: class Student(models.Model): name = models.CharField(max_length=200, verbose_name="Name:") ... and I have this model representing Enrollment, this class has a foreign key related to student: class Enrollment(models.Model): enroll_number = models.CharField(max_length=10, verbose_name='Number:') ... student= models.ForeignKey(Student, on_delete=models.CASCADE, related_name='enroll_student', verbose_name='Student:') ... If a pass sothing like enroll = Enrollment.objects.get(id=1) and pass to template {{"enroll": enroll}} I know that I can, using Jinja, access student with: {{enroll.student}} But, if I only the student (student = Student.objects.get(id=1)) and pass {{"student": student}} to template, how can access the enrollments with Jinja: something like: {{student.enroll}} (This doesn't work) Even If there's know way, what would be the best practice to resolve this in Django? Laravel, for instance allows us to define a function on the model that we can access in the template. Does anybody could help? -
Django: How to filter django objects based on month?
I am trying to get/count how many orders that were made in a month, i have written some logic to do this, but the issue is this: It does not count how many total orders were made in a month, it spreads different orders on the same month. To be more explicit, look at the reponse below: This is how to the queryset looks now <QuerySet [{'month': 4, 'count': 1}, {'month': 6, 'count': 1}, {'month': 6, 'count': 1}]> This is how to the expected queryset should look <QuerySet [{'month': 4, 'count': 1}, {'month': 6, 'count': 2}]> The 'month':4 is 'month':April and 'month':6 is 'month':June This is the code i have written to do this, but does not work models.py class CartOrder(models.Model): vendor = models.ManyToManyField(Vendor) ... date = models.DateTimeField(auto_now_add=False) views.py import calendar from django.db.models.functions import ExtractMonth orders = CartOrder.objects.annotate(month=ExtractMonth('date')).values('month').annotate(count=Count('id')).values('month','count') print(orders) terminal <QuerySet [{'month': 4, 'count': 1}, {'month': 6, 'count': 1}, {'month': 6, 'count': 1}]> -
How to more concisely make Google authorization on Django Rest Framework?
Began to study DRF. Now I have reached the topic "Google authorization". I started looking for materials on this topic, but there are a lot of them and some of them are already outdated. I'm looking for a more up-to-date description of how it's done now. It would be ideal to find a description with an example "for dummies", where everything is described in great detail. A little about the test project: for the user, a model based on AbstractUser is used now local registration and authorization is used using "Simple JWT" Request: djoser topics do not touch yet I read the topic "Authentication" on the official website of the DRF, I mainly considered "drf-social-oauth2", but I didn’t really understand -
Execute python on Django Queryset
Is there a way to execute python code on a Django Queryset? I am storing data in the db as bytes and I want to convert them to "B", "KB", "MB", "GB", "TB", "PB", "EB", "ZB", "YB". Is there any way I can convert the them before passing to the view? def get_context_data(self, *args, **kwargs): context = super().get_context_data(*args, **kwargs) context['user'] = ( DataVolume.objects.values('user') .order_by('user') .annotate( imgs=Sum('imgs'), size=SumConvertBytes('user_bytes'), ), ) -
Can I create multiple objects in django admin?
The questions is really simple. I have ItemPicture model which is class ItemPicture(models.Model): name = models.CharField(null=True, max_length=255) picture = models.ImageField(upload_to='shop/static/shop/images/') def __str__(self): return str(f"{self.name} id={self.pk}") def get_url(self): return self.picture.url How can I create, for example, 5 objects at once with django admin? I should be able to upload 5 photos and give them 5 names. django-bulk-admin and django-mass-edit didn't work for me -
sending value form views.py to html using jsonresponse
he=llo, i want to get a value from my view to html using jsonreponse, the problem is that my code work fine in views.py and i can print the data , but when i call the data in ajax it doesn't work it just give 0 as result ( because i declare round_surf = 0 at the beginning ) this the views.py code : def resultat (request): round_surf = 0 info = parametre.objects.filter(pk=1).values()[0] SEUIL = info['PAR_SEUIL'] COLOR = info['PAR_COLOR'] NBR_PAQ = info['PAR_NBRE_PAQUET'] SUR = info['PAR_SUR'] if request.method=="POST": if request.POST.get('captured_image'): captured_image = request.POST.get('captured_image') imgstr = re.search('base64,(.*)', captured_image).group(1) imgstr = base64.b64decode(imgstr) tempimg = io.BytesIO(imgstr) im = Image.open(tempimg) image = ImageOps.grayscale(im) # Appliquer un seuil pour convertir les pixels en valeurs binaires threshold = 100 # Choisir un seuil approprié image = image.point(lambda x: 0 if x < threshold else 1, '1') # Récupérer la longueur et la largeur de l'image width, height = image.size # Calculer le nombre total de pixels total_pixels = width * height image = image.convert('RGB') # Initialiser le compteur de pixels noirs black_pixels = 0 # Parcourir chaque pixel de l'image for x in range(width): for y in range(height): # test if the pixel is white if image.getpixel((x, … -
Custom functionality for editing popup text (like wikipedia link popups) in Summernote
I am trying to implement a feature into admin panel using Summernote to be able to add and edit popup information for parts of text like in Wikipedia. Wikipedia example I have found information on how to add custom buttons to summernote text editor, however implementation of functionality for described feature is too specific to be even referenced anywhere. I expect on a button press to appear a window (like for link insertion that is already implemented in Summernote) with fields for icon appearing in text and image/text appearing in popup. Populating those fields will add code to the editor, that is interpreted as an icon in text, hovering over which will show a popup window with before mentioned content. Maybe someone knows what documentation can help with implementation of such feature. -
ImportError: cannot import name 'displayadmin' from 'organizationsapp.models'
I'm new to python and django. admin.py in organizationsapp: from django.contrib import admin from .models import displa class displayadmin(admin.ModelAdmin): list_display = ['des','pic'] admin.site.register(displa,displayadmin) models.py in organizationsapp: from django.db import models class displa(models.Model): des = models.TextField(max_length=100,blank=True,null=True) pic = models.ImageField(upload_to='display/', blank=True) class Meta: verbose_name = 'ad' verbose_name_plural = 'ad' It says: ImportError: cannot import name 'displayadmin' from 'organizationsapp.models' import name 'displayadmin' from 'organizationsapp.models'? import name 'displayadmin' from 'organizationsapp.models'? -
How to pass link to file in Django views
I am very new to Django and trying display an image on an html page by passing the path to the src from the view. I have this in the 'task1.html' file <figure><img src={% static '{{ main_figure }}' %}></figure> <p>{{ description }}</p> and this in the 'views.py' file def task1(request): return render( request, "App/Tasks/task1.html", { 'main_figure' : "assets/placeholder_img.png", 'description' : "Placeholder image and text" } ) But the image does not show. If I remove the 'main_figure' : "assets/placeholder_img.png", line and change <figure><img src={% static '{{ main_figure }}' %}></figure> to <figure><img src={% static 'assets/placeholder_img.png' %}></figure> the image displays, so the issue seems to be with the views function. I have tried passing different parts of the src from the view, e.g. <img src={{ main_figure }}> with 'main_figure' : "{% static 'assets/placeholder_img.png' %}", and <img src={% static 'assets/{{ main_figure }}.png' %}> with 'main_figure' : "placeholder_img", but it always shows the little image not found icon. Any help would be greatly appreciated, thanks very much. -
How to modify or cancel the soft_time_limit for a running Celery task in Django?
Using Celery with Django, I encountered an issue while using the soft_time_limit on a task. Is there any way to stop or increase the soft_time_limit when a task is being executed? For example, after some lines of code are executed, can I increase the soft_time_limit for that particular task or cancel it altogether so that I can run the task without restrictions? I have tried modifying the soft_time_limit using update_state and signal, but it doesn't seem to work. I also tried using os.kill(os.getpid(), signal.SIGUSR1) to kill the current process, but it still raises the SoftTimeLimitExceeded exception. Any help or suggestions on how to achieve this would be greatly appreciated. Thank you. import signal from celery.exceptions import SoftTimeLimitExceeded @app.task(bind=True, soft_time_limit=10) app.task() def func(self) try: ..... ..... ..... some code app.current_task.request.timelimit = [None, None] or os.kill(os.getpid(), signal.SIGUSR1) .... some code except SoftTimeLimitExceeded: .... -
Django Modals To Admin Site
I want to Show Language of Book In Each BookInstance Table? How Do i do it. Please Guide me Everything Else is Working Fine. Here is the code :- Modals.py Modals.py Admin.py Admin.py Note :- i am new to django -
Django | Error in migration from sqlite3 to MySQL
I want to change my database from sqlite3 to mysql, but every time I do so, I encounter an error whenever I try to retrieve data from the database: Even when I try to log in to admin panel, I get the same error! (createsuperuser works fine): Here are my models: class Website(models.Model): name = models.CharField(max_length=500) URL = models.CharField(max_length=500) Logo = models.CharField(max_length=1000,null=True,blank=True) class Data(models.Model): website = models.ForeignKey(Website, on_delete=models.CASCADE , null=True, blank=True) Target_website= models.CharField(max_length=500,null=True,blank=True) URL = models.CharField(max_length=500,null=True,blank=True) Title = models.CharField(max_length=1000, unique=True) Description = models.TextField(null=True,blank=True) Keywords = models.TextField( null=True,blank=True) Text = models.TextField( null=True,blank=True) Links = models.TextField( null=True,blank=True) Images = models.TextField( null=True,blank=True) Videos = models.TextField( null=True,blank=True) Claps = models.IntegerField(default=0) TimeStamp = models.DateTimeField(auto_now_add=True) def __str__(self): return self.Title def change_claps(self, x): self.Claps += x self.save() class CustomUser(AbstractUser): username = None email = models.EmailField(unique=True) first_name = models.CharField(max_length=14) last_name = models.CharField(max_length=14) password = models.CharField(max_length=20) is_active = models.BooleanField(default=True) date_joined = models.DateTimeField(auto_now_add=True) #auto_now = True if you want to add a field like "updated_on" favourite_posts = models.ManyToManyField(Data, blank=True, null=True) USERNAME_FIELD = 'email' REQUIRED_FIELDS = [] objects = UserManager() class Claps(models.Model): user = models.ForeignKey(CustomUser, on_delete=models.CASCADE, related_name='user_likes') data = models.ForeignKey(Data, on_delete=models.CASCADE, related_name='post_likes') class Fav(models.Model): user = models.ForeignKey(CustomUser, on_delete=models.CASCADE, related_name='user_favs') data = models.ForeignKey(Data, on_delete=models.CASCADE, related_name='post_favs') Here are my serializers: from rest_framework import … -
What is your way of setting up a new project with Django? Using Docker, Github?
i was just wondering what's your way of starting a new project with django? Do you develop the project and then setup docker or you do it all at the beginning? I know there is no right or wrong but only what's right for us. But i've been struggling finding my way to optimise creating an app using all those services such as docker or railway.app Thanks for your feedbacks -
How to recreate my table in database in Django
i created a table in sqlite3 database by migrate command and then deleted it manually from database how can i recreate the table in database I tryed maigrate command again but its show No migrations to apply. pls someone tell how do i recreate the table in automatic way(by commands) -
Additional arguments to get_queryset in view
I’m looking at code which has: get_queryset(self, *args, **kwargs): return (super().get_queryset(*args, **kargs).order_by(self.name)) What is the purpose of the args and kwargs here and why not do this instead: get_queryset(self): return MyModel.objects.order_by(self.name))``` -
Hi iam getting this error TemplateSyntaxError at / Could not parse the remainder: ''' from '''
TemplateSyntaxError at / Could not parse the remainder: ''' from ''' i tried removing any extra space inside the tags but still it didnt work -
drf-spectacular with custom permission on endpoint
I've got problem with drf-spectacular library. I prepared decorators for my viewset, but I can't see endpoints in this viewset on my schema. I figured out that my custom permission to these endpoints blocks it (When I set my permissions to AllowAny the schema works fine). One permission checks if headers include header-x, the second one asks db about something (simple Queryset). Is there an option to allow swagger to disable these permissions? Or I must to refactor my code to delete them? I tried to modify DRF-spectacular settings, but I couldn't find the proper way to solve it. But when I change SERVE PUBLIC to True I see everything, even though I'm not authorized. I want to show mentioned endpoint only when I'm authorized. "TITLE": "My API", "DESCRIPTION": "My description", "SERVE_INCLUDE_SCHEMA": False, 'SERVE_PUBLIC': False, -
Django inherited template javascript is not working
I have a base template called 'baseUI.html'. I have loaded my static files using {% load static%} .when i inherited to another template the javascript and css seems broken. The console shows Refused to execute script from 'http://127.0.0.1:8000/Ticket/static/dashboard/script.js' because its MIME type ('text/html') is not executable, and strict MIME type checking is enabled. but the first rendering is working perfectly but when i rout it to another the directory changes instead calling /dashboard/style.css path('Ticket/<str:id>',RaiseTickets,name='raiseticket'), the django server console shows "GET /User_Management/vyshnav/static/dashboard/ajax.js HTTP/1.1" 404 3118 why the route path is including the code has given below <!DOCTYPE html> <html lang="en"> <head> {% load static %} {%block content%} <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <!-- Boxicons --> <link href='https://unpkg.com/boxicons@2.0.9/css/boxicons.min.css' rel='stylesheet'> <!-- My CSS --> <link rel="stylesheet" type="text/css" href="{% static 'dashboard/style.css' %}"> <script src="{% static 'dashboard/script.js' %}"></script> <script src="https://code.jquery.com/jquery-3.6.4.min.js" integrity="sha256-oP6HI9z1XaZNBrJURtCoUT5SUnxFr8s3BzRl+cbzUq8=" crossorigin="anonymous"></script> <title>Admin Dashboard</title> </head> <body> <!-- SIDEBAR --> <section id="sidebar"> <a href="#" class="brand"> <i class='bx bxs-institution'></i> <span class="text">{{LoggedUser.First_Name}} {{ LoggedUser.Last_Name}}</span> </a> <ul class="side-menu top"> <li class="active"> <a href="{% url 'home' id=LoggedUser.User_Id %}"> <i class='bx bxs-home'></i> <span class="text">Dashboard</span> </a> </li> <li> <a href="{% url 'User_Management' id=LoggedUser.User_Id %}"> <i class='bx bxs-user'></i> <span class="text">User Management</span> </a> </li> <li> <a href="{% url 'raiseticket' id=LoggedUser.User_Id %}"> <i class='bx … -
Daphne not picking up Websocket Requests in Django Rest Framework
I want to enable secure websocket connection to my Django Rest Framework application. I see that all services are starting correctly, but still when I try to connect via the following URL, the connection does not get established. It just fails with no trace. wss://127.0.0.1:8000/ws/notifications/ Where as it works fine over ws ws://127.0.0.1:8080/ws/notifications/ docker-compose.yml services: api: platform: linux/amd64 build: context: . dockerfile: Dockerfile.dev command: 'sh -c "./manage.py migrate && python manage.py runserver 0.0.0.0:8080"' restart: always networks: - default - fake_microservices volumes: - ./:/app - $HOME/.aws:/root/.aws:ro - /var/run/docker.sock:/var/run/docker.sock - type: bind source: ./docker/cpuinfo_with_fake_speed.txt target: /proc/cpuinfo ports: - 8080:8080 env_file: - ./.env depends_on: - db daphne: platform: linux/amd64 build: context: . dockerfile: Dockerfile.dev command: 'sh -c "daphne -v 3 --access-log daphne.log -b 0.0.0.0 -p 8000 apps.asgi:application"' restart: always working_dir: /app volumes: - ./:/app - /var/run/docker.sock:/var/run/docker.sock asgi.py os.environ.setdefault("DJANGO_SETTINGS_MODULE", "config.local") django_asgi_app = get_asgi_application() from channels.routing import ProtocolTypeRouter, URLRouter application = ProtocolTypeRouter( { "http": django_asgi_app, "websocket": URLRouter([path('ws/notifications/', NotificationConsumer.as_asgi())]), } ) I can see that Daphne starts with no problems: daphne_1 | 2023-04-06 09:05:27,576 INFO Starting server at tcp:port=8000:interface=0.0.0.0 daphne_1 | 2023-04-06 09:05:27,578 INFO HTTP/2 support enabled daphne_1 | 2023-04-06 09:05:27,578 INFO Configuring endpoint tcp:port=8000:interface=0.0.0.0 daphne_1 | 2023-04-06 09:05:27,580 INFO HTTPFactory starting on 8000 daphne_1 | … -
Django smart select not work if i add CSS style
I have a little problem with django's function: "django-smart-select". Basically django-smart-select works until I add a CSS class to a form-field. Here is my example: in models.py: from django.db import models from smart_selects.db_fields import ChainedForeignKey # Create your models here. class Company(models.Model): ID = models.AutoField(primary_key=True, unique=True) name = models.CharField(max_length=100) def __str__(self): return self.name class Subcompany(models.Model): ID = models.AutoField(primary_key=True) name = models.CharField(max_length=100) ID_company = models.ForeignKey(Company, on_delete=models.CASCADE) def __str__(self): return self.name class Interventions(models.Model): ID = models.AutoField(primary_key=True) start_date = models.DateField() end_date = models.DateField(blank=True, null=True) hours = models.DecimalField(max_digits=24, decimal_places=1, blank=True, null=True) description = models.TextField() signature = models.CharField(max_length=100, blank=True) ID_company = models.ForeignKey(Company, on_delete=models.CASCADE) ID_subcompany = ChainedForeignKey( Subcompany, chained_field="ID_company", chained_model_field="ID_company", show_all=False, auto_choose=True, sort=True) def __str__(self): return f'{self.start_date}' so in forms.py: from django import forms from django.forms import DateInput, TimeInput, NumberInput, TextInput, Textarea, Select from app1.models import Interventions # Create your forms here. class Forminterventions(forms.ModelForm): class Meta: model = Interventions exclude = ['ID'] fields = ['start_date', 'end_date', 'hours', 'description', 'signature', 'ID_company', 'ID_subcompany'] widgets = { 'start_date': DateInput(attrs={'class': 'inputDate'}), 'end_date': DateInput(attrs={'class': 'inputDate'}), 'hours': NumberInput(attrs={'class': 'inputNumber'}), 'description': Textarea(attrs={'class': 'inputText'}), 'signature': TextInput(attrs={'class': 'inputText'}), 'ID_company': Select(attrs={'class': 'inputCombo'}), 'ID_subcompany': Select(attrs={'class': 'inputCombo'}), } in style.css: .inputDate .inputNumber .inputText .inputCombo{ color: black; font-family: 'EB Garamond', sans-serif; font-size: x-large; text-align: center; width: 100%; } What …