Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
How do swap the indexes of a Posts?
I have model with order indices, for example - 1, 2, 3, 5, 8, 10... (empty indices were allegedly removed - 4, 6, 7, 9...) I need to get the index and swap it with the nearest index next to it. (for Up and Down move). What I have: def set_order_index(item: Posts, distinction: int): items_to_swap = Posts.objects.filter( order_index=item.order_index + distinction) if len(items_to_swap) > 0: item_to_swap = items_to_swap[0] item_to_swap.order_index = item.order_index item_to_swap.save() item.order_index += distinction item.save() And for Up views '+1': def up_item(request, id): item = Posts.objects.get(id=id) set_order_index(item, +1) return redirect('index') And for Down '-1'... But my set_order_index only does +1 and -1 always, and if it gets the same value, then swaps places. That is if index 3, the set_order_index will only make 4 (+1), but I need to swap 3 with 5. Because there is no index 4. And if I use Post with index 10 to Down - I need to swap with 8, but my set_order_index only do -1, and I get only 9. But I need 10 to swap with 8 immediately. In my head, I understand how to do this through QuerySet, getting the indices of all that is > and < and then select … -
Django Custom Filter Tags and access query
Hi need some help on Django custom filter tag, much appreciated! I have registered a filter tag to access dictionary in HTML files like below: DIRECTORY - blog>templatetags>post_extras.py @register.filter def get_item(dictionary, key): return dictionary.get(key) A dictionary named dict_post, the key is the post id, and the values is the query set. Let say to get dictionary key of 1: DIRECTORY - blog>templates>blog>home.html {{ dict_post|get_item:1 }} It returns 'title' and 'date_posted' in a queryset Post('dsdsdsdqqq111', '2021-10-03 10:24:40.623754+00:00') It worked well for the filter tag, but when I want to access some query after the filter tags , it return errors. How to only get the title? I have tried the code like below, but return errors DIRECTORY - blog>templates>blog>home.html {{ dict_post|get_item:1.title }} Error: VariableDoesNotExist at / Looking for help, thanks! -
Model idea to make add to cart service with exclusive sub_service
I am making project where user can add services Like pest_control to their cart. Also additionally user can also add Exclusive sub_service like cleaning_house, sanitizing_house to existing service -pest_control to their cart view cart data structure be like this: { "service":"Pest Control:, "service_price":500, "sub_service":[ { "service_name":"House Cleaning", "service_price":150, }, { "service_name":"Sanitizing House", "service_price":100, } ] } So, How would be Models for cart would be so that above data structure can be achieve, and if parent services is removed from cart then child also be removed. and child service is added without parent then it must not allow my Existing service model is: class Services(models.Model): service_id = models.AutoField(primary_key=True) parent_id = models.ForeignKey('self', on_delete=models.SET_NULL, null=True, blank=True,related_name='sub_service') price = models.FloatField(null=True, blank=True) service_name = models.CharField(max_length=100) service_icon = models.CharField(max_length=500, null=True, blank=True) service_image = models.CharField(max_length=500, null=True, blank=True) service_description = models.TextField( null=True, blank=True) duration = models.CharField(max_length=100,null=True,blank=True) crew = models.IntegerField(null=True,blank=True) -
Django crashes when two users run a C extension at the same time
Summary of the problem I am calling my own C extension for Python in Django, which is in charge of some long computations. The extension works fine and even the user can navigate through the Django app while the C extension makes its computations, since I have implemented Global Interpreter Lock (GIL) management inside the extension. However, when another user tries to execute the extension (while it is running for the initial user), Django crashes (process is killed) without any error message. Minimal Reproducible Example In the code below, you can see the Django view that calls (via a request POST) the C extension ftaCalculate. import ftaCalculate from django.views.generic.base import TemplateView # Computation class ComputationView(TemplateView): template_name = 'Generic/computation_page.html' @staticmethod def get_results(request): if request.method == "POST": # When button is pressed # Long computations cs_min = ftaCalculate.mcs(N, tree) else: cs_min = None return render(request, ComputationView.template_name, {'cs_min': cs_min}) Django crashes when two users run in parallel the function ftaCalculate.mcs. Is it normal that this behavior happens or am I missing something that needs to be implemented in the C extension? -
Operations between multiple columns from multiple tables
I am working on a project with Django and I faced an issue on database level when sometimes I need to apply mathematical operations across multiple fields of multiple tables. I did some research and could not find anything exactly suitable to do on Django Model level, so for now I wrote custom raw SQL for my problems. An example would be this: SELECT (s.a_s * tc.value) AS hours FROM {s} as s, {t_c} as tc WHERE s.id=%s and tc.key='s_per_tc' My question is: is it possible to sort this kind of issue with Django Model module, or should I keep writing custom queries for such operations? The operations might become more complex involving 3+ tables, etc. -
How do I create and save an unknown amount of variables to Django Model?
I am working with the twitter api via tweepy and I am unsure how to save an unknown quantity of media urls to a model object. The media section is where I am stuck. Some tweets will have media urls and some wont, while some may have numerous media urls. How do I create an unknown amount of media url variables and then how do I add that to the update_or_create? I appreciate all your help... been trying to figure this out for awhile now. user = api.get_user(screen_name=team) timeline = tweepy.Cursor( api.user_timeline, id=team, exclude_replies=True, include_rts=False).items(20) handle = user['screen_name'] location = user['location'] description = user['description'] for tweet in timeline: tweet_id = tweet['id'] date = tweet['created_at'] content = tweet['text'] `This is where I am stuck` if 'media' in tweet.entities: for media in tweet.extended_entities.media: url = media['media_url'] Tweets.objects.update_or_create( tweet_id=tweet_id, defaults={ 'handle': handle, 'tweet_id': tweet_id, 'location': location, 'description': description, 'date': date, 'content': content, 'url': url} ) -
django model user create index for first_name, last_name
I use settings.AUTH_USER_MODEL as default user model And I want to create index on public.auth_user.first_name public.auth_user.last_name Are there any elegant way to create this indexes ? -
Circular references in REST API
I'm developing a REST API (using Django Rest Framework) and am struggling with the problem of potential circular references in the data that is returned from each endpoint. I have decided to keep the API flat, rather than nested, as I think it makes a lot of other things (permissions, for example) more straight-forward. So say, for instance, that I am doing the classic blog + posts + comments structure... class Post(models.Model): title = models.CharField() content = models.TextField() author = models.ForeignKey(User) class Comment(models.Model): post = models.ForeignKey(Post) content = models.TextField() If my API has endpoints like:- /api/posts/1/ and:- /api/comments/1/ then they could easily end up serializing to:- { 'title': 'My Title', 'content': 'The content', 'author': { // user name, email etc. } } and:- { 'post': { 'title': 'My Title', 'content': 'The content', 'author': { // user name, email etc. } }, 'content': 'The comment' } Which is fine. But it means that I have to "know" to do select_related on Users when I'm fetching comments, simply because by doing that, I'm fetching the post that the comment is attached to and that has an author which is a User. I can see this getting messy and I'm foreseeing circular references … -
Error running WSGI application in Pythonanywhere
I have researched a lot and found this is a very common question. But the fact is I believe somehow pythonanywhere can not detect my settings.py file. Moreover, I have checked with the settings file directory and it is the same path as I have input in the WSGI file. I have also installed the required pip files but still getting the same errors. Error running WSGI application ModuleNotFoundError: No module named 'widget_tweaks' File "/var/www/ewallet_pythonanywhere_com_wsgi.py", line 33, in <module> application = get_wsgi_application() File "/home/ewallet/.virtualenvs/myenv/lib/python3.7/site-packages/django/core/wsgi.py", line 12, in get_wsgi_application django.setup(set_prefix=False) File "/home/ewallet/.virtualenvs/myenv/lib/python3.7/site-packages/django/__init__.py", line 24, in setup apps.populate(settings.INSTALLED_APPS) File "/home/ewallet/.virtualenvs/myenv/lib/python3.7/site-packages/django/apps/registry.py", line 91, in populate app_config = AppConfig.create(entry) File "/home/ewallet/.virtualenvs/myenv/lib/python3.7/site-packages/django/apps/config.py", line 90, in create module = import_module(entry) Here is the wsgi.py import os import sys path = '/home/ewallet/E-wallet/ewallet/ewallet/' if path not in sys.path: sys.path.append(path) from django.core.wsgi import get_wsgi_application os.environ['DJANGO_SETTINGS_MODULE'] = 'ewallet.settings' application = get_wsgi_application() Here is the directory image Kindly help me to find the bug here. Thank you -
Using the same form multiple times over a single column in a template Django
I gotta a school management web app. In my app teachers can create exams and then add grades to that. I've created a separate model for grades. This is my models right now: class Grade(models.Model): student = models.ForeignKey( Student, on_delete=models.CASCADE, related_name="grade_user", ) subject = models.ForeignKey( Subject, on_delete=models.CASCADE, related_name="grade_subject", ) grade = models.DecimalField(max_digits=6, decimal_places=2) class Exam(models.Model): ... grades = models.ManyToManyField( Grade, related_name="exam_grades", blank=True, ) Now I've created a form like following: Teachers fill the fields and then using a single button this should be submitted. But the problem is that I don't know how to implement such implementation. I read somethings about formsets but I want the fields to be in a single column. Is there any way to get this done? -
Mongodb django settings
I have a django project which in local it works fine. I deploy on a remote server but mongodb it seems doesn’t work because I have this partial traceback: djongo.exceptions.SQLDecodeError: Keyword: FAILED SQL: SELECT "station"."station_name", "station"."id_station" FROM "station" Params: () Pymongo error: OrderedDict([('ok', 0.0), ('errmsg', 'command find requires authentication'), ('code', 13), ('codeName', 'Unauthorized')]) Version: 1.3.6 Sub SQL: None FAILED SQL: None Params: None Version: None The above exception was the direct cause of the following exception: Traceback (most recent call last): File "/home/kafka/anaconda3/envs/djangocrops/lib/python3.9/site-packages/django/db/utils.py", line 97, in inner return func(*args, **kwargs) File "/home/kafka/anaconda3/envs/djangocrops/lib/python3.9/site-packages/djongo/cursor.py", line 70, in fetchmany raise db_exe from e djongo.database.DatabaseError The above exception was the direct cause of the following exception: Traceback (most recent call last): File "/home/kafka/anaconda3/envs/djangocrops/lib/python3.9/threading.py", line 973, in _bootstrap_inner self.run() File "/home/kafka/anaconda3/envs/djangocrops/lib/python3.9/threading.py", line 910, in run I set my mongodb (on the server it runs locally) in settings and in a utils.py file: DB django settings: DATABASES = { 'default': { 'ENGINE' : 'djongo', 'NAME' : 'meteodata', 'HOST': '127.0.0.1', #localhost', 'PORT': 27017, 'USERNAME': 'admin', 'PASSWORD': 'mypwd', 'MONGO_URI': "mongodb://admin:mypwd@127.0.0.127017/meteodata" } } utils.py from pymongo import MongoClient import pymongo def get_db_handle(db_name, host, port, username, password): #, username, password): client = MongoClient(host=host, port=int(port), username=username, password=password, authSource="admin", )# localhost 27017 … -
how to solve cors policy
I have installed django-cors-headers and in settings.py : MIDDLEWARE = [ 'django.middleware.security.SecurityMiddleware', 'django.contrib.sessions.middleware.SessionMiddleware', 'corsheaders.middleware.CorsMiddleware', ] ALLOWED_HOSTS = os.environ.get("ALLOWED_HOSTS","").split() CORS_ALLOW_ALL_ORIGINS = True but i get cors policy error and cant connect to api : Access to XMLHttpRequest at 'https://event-alpha.mizbans.com/api/meetings/?memory=0' from origin 'https://alpha.mizbans.com' has been blocked by CORS policy: Response to preflight request doesn't pass access control check: No 'Access-Control-Allow-Origin' header is present on the requested resource. xhr.js:177 GET https://event-alpha.mizbans.com/api/meetings/?memory=0 net::ERR_FAILED what should i do?(ps: i got this error on the deployed version) -
Is there a way to resign variable in Django template?
I'm working on a Django Project. I'll want to resign a variable in the Django template. Here is the code of views.py (index function): def index(request): global title return render(request, "encyclopedia/index.html", { "title": title }) Here is the code of index.html: {% extends "encyclopedia/layout.html" %} {% block title %} Encyclopedia {% endblock %} {% block body %} <h1>All Pages</h1> <!-- I want to resign the title variable here --> {% endblock %} Is there any way we can resign the variable? -
after moving project to another dir it show this error ImportError: cannot import name 'python_2_unicode_compatible' from 'django.utils.encoding'
my project was running correctly before I moved my project to another directory and it started to show this error I did not change anything but I moved it in my d drive $ python manage.py runserver Watching for file changes with StatReloader Exception in thread django-main-thread: Traceback (most recent call last): File "C:\Users\waqar\AppData\Local\Programs\Python\Python39\lib\threading.py", line 973, in _bootstrap_inner self.run() File "C:\Users\waqar\AppData\Local\Programs\Python\Python39\lib\threading.py", line 910, in run self._target(*self._args, **self._kwargs) File "D:\my project\My All Project\school\venv\lib\site-packages\django\utils\autoreload.py", line 64, in wrapper fn(*args, **kwargs) File "D:\my project\My All Project\school\venv\lib\site-packages\django\core\management\commands\runserver.py", line 110, in inner_run autoreload.raise_last_exception() File "D:\my project\My All Project\school\venv\lib\site-packages\django\utils\autoreload.py", line 87, in raise_last_exception raise _exception[1] File "D:\my project\My All Project\school\venv\lib\site-packages\django\core\management\__init__.py", line 375, in execute autoreload.check_errors(django.setup)() File "D:\my project\My All Project\school\venv\lib\site-packages\django\utils\autoreload.py", line 64, in wrapper fn(*args, **kwargs) File "D:\my project\My All Project\school\venv\lib\site-packages\django\__init__.py", line 24, in setup apps.populate(settings.INSTALLED_APPS) File "D:\my project\My All Project\school\venv\lib\site-packages\django\apps\registry.py", line 114, in populate app_config.import_models() File "D:\my project\My All Project\school\venv\lib\site-packages\django\apps\config.py", line 301, in import_models self.models_module = import_module(models_module_name) File "C:\Users\waqar\AppData\Local\Programs\Python\Python39\lib\importlib\__init__.py", line 127, in import_module return _bootstrap._gcd_import(name[level:], package, level) File "<frozen importlib._bootstrap>", line 1030, in _gcd_import File "<frozen importlib._bootstrap>", line 1007, in _find_and_load File "<frozen importlib._bootstrap>", line 986, in _find_and_load_unlocked File "<frozen importlib._bootstrap>", line 680, in _load_unlocked File "<frozen importlib._bootstrap_external>", line 850, in exec_module File "<frozen importlib._bootstrap>", … -
About Django Test
Assumption I'm developing an application with Django. The authentication is implemented using "django-allauth". Problem I'm try to write unit tests, but I don't know if I should write tests for the authentication process, because tests are already written like this. Can anyone teach me if I should write tests for the authentication process? -
AttributeError: 'MetaDict' object has no attribute 'get_field' django_elasticsearch
I want to use elasticsearch within django app and send some data from model object to it but there is a problem with I am already using django-elasticsearch-dsl library. here`s my django_elasticsearch configuration: from django_elasticsearch_dsl import Document, fields from django_elasticsearch_dsl.registries import registry from core.models.src.errorLog import errorLog @registry.register_document class ErrorLogDocument(Document): class Index: name = 'errors' settings = { 'number_of_shards': 1, 'number_of_replicas': 0 } class Django: model = errorLog fields = [ 'time', 'date', 'error', 'place', ] but when I run my app I get this error and don`t know how to handle this: django_field = django_attr.model._meta.get_field(field_name) AttributeError: 'MetaDict' object has no attribute 'get_field' Can anyone help this???? Blockquote enter code here -
Navbar custom breakpoint not working - dropdown not displaying
I have a website made using Django and Django CMS, and am trying to implement a custom breakpoint for the navbar, as currently resizing the browser window makes the elements stack on top of each other before the navbar collapses. I've been able to implement a custom breakpoint of 1400px, but when using it, the menu dropdown glitches and doesn't display when the hamburger button is pressed. The line of code that both makes the breakpoint work, and the dropdown not display, is .navbar-collapse.collapse { display: none!important; }. I'm suspecting my nav tags might be in the wrong order. Here's my HTML and CSS: {% load cms_tags menu_tags sekizai_tags staticfiles snippet_tags %} {% render_block "css" %} <style> @media (max-width: 1400px) { .navbar-header { float: none; } .navbar-toggle { display: block !important; } .navbar-collapse { border-top: 1px solid transparent; box-shadow: inset 0 1px 0 rgba(255, 255, 255, 0.1); } .navbar-collapse.collapse { display: none !important; } .navbar-nav { float: none !important; margin: 7.5px -15px; } .navbar-nav > li { float: none; } .navbar-nav > li > a { padding-top: 10px; padding-bottom: 10px; } } </style> <nav class="navbar fixed-top navbar-expand-xl navbar-dark bg-dark fixed-top"> <div class="container-fluid" style="margin-left:-20px;"> <button type="button" class="navbar-toggle" data-toggle="collapse" data-target=".navbar-collapse"> <i class="fa … -
__in filter only returning one value, show query through intermediate table
Noob at coding and need help. I am trying to render the view article by filtering through the model Spots. I have an intermediate table ArticleSpots to link the 2 tables Spots and Articles. In the views article I want to show only the spots that are linked to that specific article. My problem is that Spots.objects.filter(id__in=articleSpots) only shows the first one value and not all of the spots that are linked. What am I doing wrong here? views.py def article(request, slug): articles = get_object_or_404(Articles, slug=slug) article_id = articles.id articleSpots = ArticleSpots.objects.filter(article__id=article_id) spots = Spots.objects.filter(id__in=articleSpots) context = {"spots": spots, "articles": articles} template_name = "articletemplate.html" return render(request, template_name, context) models.py class ArticleSpots(models.Model): article = models.ForeignKey('Articles', models.DO_NOTHING) spot = models.ForeignKey('Spots', models.DO_NOTHING) class Meta: managed = True db_table = 'article_spots' verbose_name_plural = 'ArticleSpots' def __str__(self): return str(self.article) + ": " + str(self.spot) class Articles(models.Model): title = models.CharField(max_length=155) metatitle = models.CharField(max_length=155) slug = models.SlugField(unique=True, max_length=155) summary = models.TextField(blank=True, null=True) field_created = models.DateTimeField(db_column='_created', blank=True, null=True) field_updated = models.DateTimeField(db_column='_updated', blank=True, null=True) cover = models.ImageField(upload_to="cover", blank=True, default='logo-00-06.png') class Meta: managed = True db_table = 'articles' verbose_name_plural = 'Articles' def __str__(self): return str(self.id) + ": " + str(self.title) class Spots(models.Model): title = models.CharField(max_length=155) metatitle = models.CharField(max_length=155) slug = … -
Filter queryset accouring to related objects in django
I used django-guardian library, I want to create Manager to filter objects according to user permission. So for-example: from guardian.shortcuts import get_objects_for_user class WithUser(models.Manager): user_obj = None def assign_user(self,user_obj): self.user_obj = user_obj qs = super().get_queryset() ######################### # how I know if the current qs have related field and how to get related field managers. #??????????????? def get_queryset(self): qs = super().get_queryset() if self.user_obj: qs = get_objects_for_user(self.user_obj,"view_%s"%self.model.__name__.lower(),qs,accept_global_perms=False) return qs class A(models.Model): # the model fields objects = WithUser() class B(models.Model): # the model fields a = models.ForeignKey(A,on_delete=Model.CASCADE) objects = WithUser() class C(models.Model): # the model fields b = models.ForeignKey(B,on_delete=Model.CASCADE) objects = WithUser() How to filter C objects according to it's permission and permission of A,B. I want general rule to filter any model objects according to its permission and permission of its related objects. -
Download Sqlite database for backup in django
I have a site for deploying this site I will use image so I don't have access to the project file so I wanna know is there any way to download sqlite database for backup in django -
Run django application on Background with PM2
Hello i have a django application which runs smoothly with python3 manage.py runserver. But to run it all time i need to use any process manager or manually create a service. I want to run it with pm2. But problem occurs when i try to run the app with pm2 as a process. Below is my pm2 config file. { apps: [{ name: "lab", script: "/home/ubuntu/sample-django-app/manage.py", args: ["runserver", "0.0.0.0:8080"], exec_mode: "fork", instances: "1", wait_ready: true, autorestart: true, max_restarts: 5, interpreter : "/home/ubuntu/venv/bin/python3" }] } But the following error occurs raise ImportError( ImportError: Couldn't import Django. Are you sure it's installed and available on your PYTHONPATH environment variable? Did you forget to activate a virtual environment? Traceback (most recent call last): File "/home/ubuntu/sample-django-app/manage.py", line 11, in main from django.core.management import execute_from_command_line ModuleNotFoundError: No module named 'django' The above exception was the direct cause of the following exception: Traceback (most recent call last): File "/home/ubuntu/sample-django-app/manage.py", line 22, in <module> main() File "/home/ubuntu/sample-django-app/manage.py", line 13, in main raise ImportError( ImportError: Couldn't import Django. Are you sure it's installed and available on your PYTHONPATH environment variable? Did you forget to activate a virtual environment? here I have installed Django and the app runs smoothly … -
how to register a user with a specific email address Django?
How do I register a user with a specific email address? def register(request): if request.method == "POST": username = request.POST["username"] email = request.POST.include["mail"] # Ensure password matches confirmation password = request.POST["password"] confirmation = request.POST["confirmation"] if password != confirmation: return render(request, "auctions/register.html", { "message": "Passwords must match." }) -
how to delete previous uploaded file when a new one gets uploaded using id
I have simple cv upload class for users to upload their resume. it works just fine but when they upload a newer one, the previous wont get deleted. this is my code: class ResumeDocument(models.Model): id = models.AutoField(primary_key=True) user = models.ForeignKey(User, on_delete=models.CASCADE) cvfile = models.FileField(upload_to="documents", null=True, validators= [validate_file_extension]) def save(self, *args, **kwargs): try: this = ResumeDocument.objects.get(id=self.id) if this.cvfile != self.cvfile: this.cvfile.delete(save=False) except: pass super().save(*args, **kwargs) how can I reach the previous id? id = self.id - 1. something like that. this is my views: @login_required def pdf_resume(request): if request.method == 'POST': form = DocumentForm(request.POST,request.FILES) if form.is_valid(): form.instance.user = request.user form.save() return redirect('pdf_resume') if 'delete' in request.GET: return delete_item(ResumeDocument, request.GET['id']) else: form = DocumentForm() documents = ResumeDocument.objects.filter(user=request.user) context = { 'form':form, 'documents':documents, } return render(request, 'reg/pdf_resume.html', context) and this is also my HTML code: {% if documents %} {% for doc in documents %} {% if forloop.last %} <div class="existing-item antd-pro-pages-applicant-profile-partials-style-reviewList"> <div class="ant-divider ant-divider-horizontal ant-divider-with-text-center" role="separator"><span class="ant-divider-inner-text"> </span></div> <div class="btn-delete" data-id="{{doc.id}}" style="position: relative;"> <div style="position: absolute; padding: 0.5rem; top: -1.5rem; left: -0.5rem; display: flex; justify-content: center; align-items: center;"><a style="color: red;"></a></div> </div> <a href="{{ doc.cvfile.url }}">cv</a> </div> {% endif %} {% endfor %} {%endif%} -
what is scheme is better for react and django project
I'm going to do my first full-stack project, a website with react and django. Actually I saw a lot of schemes that you can use these two technologies together but I want to choose the best. So I brought these three schemes and I want to know your opinions about theme. Creating react apps inside every django apps and design and transfer and modify data using djangorestframework. Separating frontend and backend in the root and make one react app in frontend and one django project in backend and using djangorestframework for fetching data. There is one django project and there's one app in there named frontend that handles react app and also there's a django app named api to handle serializing and fetching data using djangorestframework. If you prefer another method, please tell your opinion. -
how to use modelformset_factory with ajax request - django
im trying submit a form with a modelformset which upload multiple images with ajax , but it only saves the parent form not model formset_factory ! here is what i tried .. const form = document.getElementById('post-form-add-booking') form.addEventListener("submit",submitHanler); function submitHanler(e){ e.preventDefault(); $.ajax({ type:'POST', url:"{% url 'booking:add_booking', data:$("#post-form-add-booking").serialize(), dataType:'json', mimeType:'multipart/form-data', success:successFunction, error:errorFunction, }) } $('#addImgButton').click(function(e) { var form_dex1 = $('#id_form-TOTAL_FORMS').val(); $('#images').append($('#imgformset').html().replace(/__prefix__/g,form_dex1)); $('#id_form-TOTAL_FORMS').val(parseInt(form_dex1) + 1); e.preventDefault(); }); <form method="POST" enctype="multipart/form-data"id="post-form-add-booking" class="mt-2 ">{% csrf_token %} <div id="form"> <div class="border border-gray-900 p-2 rounded-xl bg-gray-900 bg-opacity-25 pb-2 relative"> <div class="grid md:grid-cols-2 md:gap-5"> <div class="groupinput relative bglightpurple rounded-xl"> <label class="text-white absolute top-1 mt-1 mr-2 text-xs">{% trans "room number" %}</label> <p class="w-full pr-2 pb-1 pt-6 bg-transparent focus:outline-none text-white">{{room_number.room_no}}</p> </div> <div class="groupinput relative bglightpurple rounded-xl"> <label class="text-white absolute top-1 mt-1 mr-2 text-xs">{% trans "address" %}</label> {{form.address | add_class:'w-full pr-2 pt-6 pb-1 bg-transparent focus:outline-none text-white'}} {% if form.address.errors %} <p class="text-white pb-2 pr-2 rounded-xl w-full">{{form.address.errors}}</p> {% endif %} </div> </div> <div class="grid md:grid-cols-2 md:gap-5"> <div class="groupinput relative bglightpurple mt-2 rounded-xl"> <label class="text-white absolute top-1 mt-1 mr-2 text-xs">{% trans "takes by" %}</label> {{form.taker | add_class:'w-full pr-2 pt-6 pb-1 bg-transparent focus:outline-none text-white'}} {% if form.taker.errors %} <p class="text-white pb-2 pr-2 rounded-xl w-full">{{form.taker.errors}}</p> {% endif %} {% if form.errors %} <p class="text-white pb-2 …