Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Django REST framework - filtering against query param with date Outside Views.py file
I created my "API" using REST framework, now trying to do filtering for it. That's how my models.py look for BookingStatement model. class BookingStatement(BaseModel): ticket_number = models.PositiveIntegerField(unique=True) booking = models.OneToOneField(Booking, on_delete=models.PROTECT) user_rate = AmountField() agent_rate = AmountField() total_amount = AmountField() class Meta: default_permissions = () def __str__(self): return str(self.id) Booking is One to One Key so the booking model has following Attributes. class Booking(BaseModel): bus_seat = models.ManyToManyField(Seat) schedule = models.ForeignKey(Schedule, on_delete=models.PROTECT) boarding_point = models.ForeignKey( BoardingPoint, on_delete=models.PROTECT, null=True ) remarks = models.JSONField(null=True, blank=True) contact = PhoneNumberField(null=True) booking_date_time = models.DateTimeField(auto_now_add=True) class Meta: default_permissions = () verbose_name = 'Booking' verbose_name_plural = 'Bookings' def __str__(self): return '{}-{}'.format(self.user, self.customer_name) I used generic ListAPIView in my views.py as following. class BusCompanyTicketDetailView(generics.ListAPIView, BusCompanyMixin): serializer_class = serializers.TicketDetailResponseSerializer def get_queryset(self): travel_date = (int(self.request.query_params.get('booking_date'))) print(booking_date) return usecases.ListBusCompanyTicketUseCase(date=#'what should i pass?'#).execute() I use usecases.py to filter booking_date_time with url as following. http://127.0.0.1:8000/api/v1/ticket/list?booking_date=2021-1-29 So my usecase file to filter the Booking time is as following. class ListBusCompanyTicketUseCase(BaseUseCase): def __init__(self, date:datetime): self._date = datetime def execute(self): self._factory() return self._booking_statements def _factory(self): self._booking_statements = BookingStatement.objects.filter(booking__booking_date_time=?? need to get date from views.) Problem is I don't know to how to get query params from url in my usecases to filter with booking date any help … -
How to bite-size a form in Django, with no data persistance: What's the most Djangonic mothod?
Firstly, the scenario in my question: I want to deliver a form in bitesize stages, with the valid completion of one stage leading to the next until all stages are complete. On completion, I'd like to use all data once, and then forget it completely so I'm not holding on to any user data. My options as I see it are: Multiple views each with a unique form all bound to a single model. The final submit button in the chain triggers data in the model to be accessed, used and then that particular row removed. Multiple views each with unbound forms, each adding data to a cookie, which is then read on the final submit, data used and the cookie deleted (either using sessions or plain old js hard coded into each template). A single view and template containing a single unbound form, which progressively un-hides divs containing each stage until all stages are completed and final 'submit' posts data from the form, allows a view to process it and forgets it. I can actualise all three of the above, but which is the most 'Djangonic' method? Is there a more conventional way of 'bite-sizing' my single form? -
Post sensor values to a django app deployed on Heroku
Is it possible to post readings from sensors connected to arduino to postgress database of a django app deployed to heroku...am new to heroku need assistance. -
What is the standart value of category filter in fields? Django-filter
I am using django-filter and I have one question. I am using dictionary value for fields in meta tag of filter class. But on the documentation I didnt found stantart value. class Meta: model = Product fileds = { 'category': <here what?>, } -
getting strict-origin-when-cross-origin although i provided CORS_ORIGIN_ALLOW_ALL = True in settings.py file
I have build my frontend using Angular and backend using django-restframwork. In my settings.py I provided CORS_ORIGIN_ALLOW_ALL = True I run it using python3.8 manage.py runserver 5000 but when my frontend tried to send request to it it generates error. my angular sends request like this. my environment file where I saved my urls export const environment = { production: true, api_url: "https://localhost:5000/op-api", user_login_url: "https://localhost:5000/auth/login/", // all_users :"https://ots.ahg.af:5000/rest-auth/login", user_logout_url: "https://localhost:5000/auth/logout/", user_register_user:"https://localhost:5000/auth/register/" }; and by submitting register form I send my request like this. onCreateAccount(){ this.httpService.register_user(this.registerForm.value).subscribe(resp=>{ ....... }, error=>{ ...... } else{ ........ }); } these are in my http service where I call using the above code. user_register_user = environment.user_register_user; public register_user(data){ if (data != null){ return this.http.post(this.user_register_user ,{ 'username': data.username, 'email' : data.email, 'password' : data.password, }); } } can anyone tell me why I am getting cross-origin error and what is the problem. I tried: export const environment = { production: true, api_url: "https://ots.ahg.af:5000/op-api", user_login_url: "https://ots.ahg.af:5000/auth/login/", // all_users :"https://ots.ahg.af:5000/rest-auth/login", user_logout_url: "https://ots.ahg.af:5000/auth/logout/", user_register_user:"https://ots.ahg.af:5000/auth/register/" }; ots.ahg.af is my domain name export const environment = { production: true, api_url: "http://127.0.0.1:5000/op-api", user_login_url: "http://127.0.0.1:5000/auth/login/", // all_users :"http://127.0.0.1:8000/rest-auth/login", user_logout_url: "http://127.0.0.1:5000/auth/logout/", user_register_user:"http://127.0.0.1:5000/auth/register/" }; none of the above worked for me. -
VScode redis extension show gebberish
VScode redis extension show gibberish of key string, is this an encoding problem? how to fix this in vscode? I am using windows -
Django data from context not showing in template
Im stuck with a template context in Django. In my template I display information about a team and I also want to display players from this team. In context I pass players from team but then in template when I want to display this data it doesn't work. I tried to add also some example data like "test":123 and display it in template like {{test}} but it also doesn't work. views.py* def team_profile(request, name): team = Team.objects.get(name=name) player_list_filtered = [] player_list = User.objects.all() for player in player_list: if player.profile.team.name == team.name: player_list.append(player) context = { 'team': team, 'players': player_list_filtered, 'test': 123 } return render(request, 'blog/team_profile.html', context) team_profile.html* {% block content %} <div class="d-flex align-items-start flex-column content-section"> <img class="rounded-circle account-img" src="{{ team.image.url }}"> <h1>{{team.name}}</h1> <h3>Mecze: {{team.matches}}</h3> <h3>League: {{team.league}}</h3> {% for player in players %} <h3>{{player.first_name}}</h3> {% endfor %} <p>Test: {{test}}</p> </div> {% endblock content %} Here is my result -
Django forms are not reflecting on html tempelate page
Am trying to create forms in django template but the fields are not showing.I have no idea why the fields are not showing, Kindly help out. Below are the codes forms.py from django import forms class ContactForm(forms.Form): from_email = forms.EmailField(required=True) subject = forms.CharField(required=True) message = forms.CharField(widget=forms.Textarea, required=True) views.py from django.shortcuts import render, redirect from django.http import HttpResponse, HttpResponseRedirect from .models import Contacts from django.core.mail import send_mail, BadHeaderError from django.conf import settings from .forms import ContactForm # Create your views here. def Contacts(request): # contact = Contacts.objects return render(request,'Contacts/index.html') def Home(request): return render(request,'Home/index.html') def contact(request): if request.method =='GET': form = ContactForm() else: form = ContactForm(request.POST) if form.is_valid(): subject = form.cleaned_data['subject'] from_email = form.cleaned_data['from_email'] message = form.cleaned_data['message'] try: send_mail(subject, message, from_email, ['henryochieng8@gmail.com']) except BadHeaderError: return HttpResponse('Invalid header found.') return render('success') return render(request, "Contacts/index.html", {'form':form}) def successView(request): return HttpResponse('Success! Thank You for messaging us.') part of html file <h1>Contact Me</h1> <form action="" method="post" role="form"> {% csrf_token %} {{form.as_p}} <div class="form-actions"> <button type="submit">Send</button> </div> </form> -
django-allauth signals user_signed_in signal isn't working
I am relatively new to django, and trying to trigger a function on login. I have tested the function itself, and it works fine. The django-allauth login is also correctly configured. However, i cannot seem to trigger the signal below on login. See code below... Any help would be appreciated... pages/apps.py from django.apps import AppConfig class PagesConfig(AppConfig): name = 'pages' def ready(self): import apps.pages.signals pages/signals.py from allauth.account.signals import user_logged_in from django.dispatch.dispatcher import receiver from django.utils import timezone from datetime import timedelta from .models import Token @receiver(user_logged_in) def user_logged_in_(request, user, **kwargs): is_valid = Token.objects.filter(valid_until__gte=timezone.now() + timezone.timedelta(seconds=10800)).values() if not is_valid: new = Token(token='valid', valid_until=timezone.now()) else: new = Token(token='not valid', valid_until=timezone.now()) new.save() -
Which cloud store should i use for storing documents?
I have developed a Django web app which store user uploaded pdfs, Docx. Site is hosted on pythonanywhere.com. The problem is pythonanywhere provide only 500 MB for a free account. Storage provided by them on the paid account is I feel costly which is 5GB disk space for 12 USD/ Month. I really do not need a lot of space but 500 MB is too low for me. Should I use Google drive/ One drive which provides 15 GB for free and paid service is also quite low than pythonanywhere? Will it affect on drastically on the website? -
Is it possible to reuse annotations from one model in another one in Django?
I'm using Django 2.2.16 and I was trying to get rid of replicated logic across querysets. I didn't manage to find a way (without impacting performance, like subquery in select clause) to reuse annotations from one model in annotations of another one. Here is my current implementation: # models.py from django.contrib.gis.db import models from querysets import PostManager, TagManager class Tag(models.Model): objects = TagManager() name = CICharField(db_index=True, max_length=100) class Post(models.Model): objects = PostManager() STATUS_ACCEPTED = "ACCEPTED" STATUS_DECLINED = "DECLINED" STATUS_CHOICES = ( (STATUS_ACCEPTED, "Accepted"), (STATUS_DECLINED, "Declined"), ) status = models.CharField( default=STATUS_DECLINED, choices=STATUS_CHOICES, max_length=63, verbose_name="Źródło ogłoszenia", ) expiration_date = models.DateField(blank=True, null=True) tags = models.ManyToManyField(Tag, blank=True, db_index=True) # querysets.py from django.db.models import Case, Count, Q, QuerySet, When, Manager class PostQuerySet(QuerySet): def annotate_statuses(self): today = date.today() return self.annotate( live=Case( When( Q(status="ACCEPTED") & (Q(expiration_date__isnull=True) | Q(expiration_date__gte=today)), then=True, ), default=False, output_field=models.BooleanField(), ), expired=Case( When( Q(status="ACCEPTED") & (Q(expiration_date__isnull=False) & Q(expiration_date__lt=today)), then=True, ), default=False, output_field=models.BooleanField(), ), ) PostManager = Manager.from_queryset(PostQuerySet) class TagQuerySet(QuerySet): def annotate_live_listings(): today = date.today() return queryset.annotate( posts_count=Count("post"), listings_count=Sum( Case( When( Q(post__status="ACCEPTED") & (Q(post__expiration_date__isnull=True) | Q(post__expiration_date__gte=today)), then=1, ), output_field=IntegerField(), default=0, ) ), ) TagManager = Manager.from_queryset(TagQuerySet) My question is if it's possible to reimplement method annotate_live_listings in TagQuerySet to reuse somehow already implemented annotate_statuses from PostQuerySet. … -
Receiving data from ESP8266 to Django
I am trying to send data from sensor connected to ESP8266 to Django server using this Arduino code void loop(void){ if (WiFi.status() == WL_CONNECTED) { //Check WiFi connection status HTTPClient http; data = analogRead(A0); const int capacity = JSON_OBJECT_SIZE(2); StaticJsonDocument<capacity> doc; doc["sensor"] = data; serializeJsonPretty(doc, postMessage); serializeJsonPretty(doc, Serial); http.addHeader("Content-Type", "application/json"); http.begin("http://192.168.1.21:8000/sensor"); //Specify destination for HTTP request int httpCode = http.POST(postMessage); String payload = http.getString(); if (httpCode > 0) { Serial.println(); Serial.println(httpCode); if (httpCode == 200) { Serial.println("Hooray!"); } } Serial.println(payload); delay(5000); } } but I cant get the postMessage value to django iam using this code and getting None @csrf_exempt def index(request): data = request.POST.get("postMessage", None) print(data) return HttpResponse("Hello there") -
Retrieve a value from JWT Token in Python
I have passed a boolean field, 'is_valid' in the JWT token payload. Now I need to retrieve the value of 'is_valid' for condition checking. How can I do it in python django? Check this image -
iterating over two tables simultaneously in Django Template For Selection - Python Django
Here, I want to iterate over two tables data and make them available in SELECT tag for selection, and this is a mapping table so I want to iterate two tables simultaneously. This mappings I want to store in Mapping table. Let me show my code so that you can better understand it. models.py class Product(models.Model): prod_ID = models.AutoField("Product ID", primary_key=True) prod_Name = models.CharField("Product Name", max_length=30, null=False) prod_Desc = models.CharField("Product Description", max_length=2000, null=False) prod_Price = models.IntegerField("Product Price/Piece", default=0.00) prod_img = models.ImageField("Product Image", null=True) def __str__(self): return "{}-->{}".format(self.prod_ID, self.prod_Name) class Size(models.Model): size_id = models.AutoField("Size ID", primary_key=True, auto_created=True) prod_size = models.CharField("Product Size", max_length=20, null=False) def __str__(self): return "{size_id}-->{prod_size}".format(size_id=self.size_id, prod_size=self.prod_size) class SizeProductMapping(models.Model): size_p_map_id = models.AutoField("Size & Product Map ID", primary_key=True, auto_created=True) size_id = models.ForeignKey(Size, null=False, on_delete=models.CASCADE, verbose_name="Size ID") prod_id = models.ForeignKey(Product, null=False, on_delete=models.CASCADE, verbose_name="Product Id") def __str__(self): return ".`. {}_____{}".format(self.size_id, self.prod_id) Here in above models i want to store size and product mapping in SizeProductMap table. views.py def sizeProductMap(request): # Here I am fetching products and size ID to give option while add new records productSize_show = Size.objects.all() print(productSize_show) product_show = Product.objects.all() print(product_show) attribute_values = zip(productSize_show, product_show) print(attribute_values) if request.method == 'POST': size_id = request.POST['size_id'] product_id = request.POST['prod_id'] sizeProductMap_update = SizeProductMapping(size_id=size_id, prod_id=product_id) # … -
Uploaded an image got [Error 111] using Cloudinary on Pythonanywhere
Hi, Somebody, please help me, I'm using Pythonanywhere to store my Django code and everything run properly except when I'm trying to upload an image. I got this error: cloudinary.exceptions.Error: Unexpected error - MaxRetryError("HTTPSConnectionPool(host='api.cloudinary.com', port=443): Max retries exceeded with url: /v1_1/MY-CLOUD-NAME/image/upload (Caused by NewConnectionError('<urllib3.connection.HTTPSConnection object at 0x7f5de5f6e6d0>: Failed to establish a new connection: [Errno 111] Connection refused'))") This is my code in model.py: from cloudinary.models import CloudinaryField some class project_image = CloudinaryField("project_img", proxy="http://proxy.server:3128") This is my code in setting.py: CLOUDINARY = { 'cloud_name': 'CLOUD-NAME', 'api_key': 'xx', 'api_secret': 'xx, } CLOUDINARY_URL='cloudinary://xxx@CLOUD-NAME?api_proxy=proxy.server:3128' I also tried to change the proxy.server part to: - https://api.cloudinary.com/v1_1/MY-CLOUD-NAME and add the api_proxy in CLOUDINARY parameter but It didn't work also P.S. I'm using a free Pythonanywhere account and I do some research and the owner said that I have to set the proxy to proxy.server:3128 but I don't know how to do that P.S.2 What I've tried to do so far upgrade urllib but didn't work out try to add a proxy in many different ways on setting.py as you saw above Please help me or at least give me any advice, I'm really new to the Pythonanywhere site -
In Django, how can we stop losing the details filled in the form, if it fails validation?
I am using the UserCreationForm for user registration in my Django web app. When the user fills in the detail (username, password, confirm_password) and submits, then if the form fails validation (maybe because username already exists or password don't match or password is too short) then the user is redirected back to the register page (see the below code, to redirect I've used return HttpResponseRedirect(reverse("register")). Now my problem is that when he is redirected back to the register page, the form is blank again, i.e. he has to start all over again, which is not a good user experience because his form might fail one or more times. I want that if the form fails validation and when he is redirected to the registration form, he should see his previously filled in details so that he can just correct the field which is causing the error and move on. Is there any way the data can be retained? Here is my code of the register function in views.py: def register(request): if request.method == 'POST': form = UserCreationForm(request.POST or None) if form.is_valid(): # some code return redirect('login') else: messages.error(request, form.errors) return HttpResponseRedirect(reverse("register")) If it's not possible to retain details in the … -
Django ERROR: there is no unique constraint matching given keys for referenced table
There are many similar questions on Stackoverflow, but none of the answers has helped me. So, when running migrations, Django throws this error: django.db.utils.ProgrammingError: there is no unique constraint matching given keys for referenced table "catalogues_movieslist" I have this BlackWhiteCartoon model I am trying to create with the migration: class BlackWhiteCartoon(BaseMovie, BaseList): authors = JSONField(default=list, blank=True, null=True) publisher = CharField(max_length=250, blank=True) year = PositiveSmallIntegerField(blank=True, null=True) This model inherits from the BaseList model that has only one field, a foreign key: class BaseList(Model): belongs_to_movies_list = ForeignKey(MoviesList, on_delete=CASCADE, null=True) The referenced MoviesList model is the following: class MoviesList(Model): creation_date = DateTimeField(auto_now_add=True) id = AutoField(primary_key=True) uid = UUIDField(default=uuid.uuid4, editable=False) user = ForeignKey(User, on_delete=CASCADE, null=True, blank=True) Also, the BaseMovie model is the following: class BaseMovie(BaseObject): language = CharField(max_length=2, blank=True) note = CharField(max_length=700, blank=True) And the BaseObject model: class BaseObject(Model): id = BigAutoField(primary_key=True) uid = UUIDField(default=uuid.uuid4, editable=False, db_index=True) date_added = DateTimeField(null=True) So, what I have tried: Migrating everything together: this throws the above error. Migrating BlackWhiteCartoon without inheriting BaseList first. This migration applies, but as soon as I add BaseList, it crashes with the same error. Adding unique=True to the id field of MoviesList (both together with all other migrations and before adding BaseList to … -
Specific Fields for Specific User types in Django
I'm trying to come up with a better structure for handling user data in a django app. Currently, There are two kinds of users in the app, individual and organization. There is data specific to an individual and data specific to an organization. For example, an individual can have a first and last name while a organization only has their organization name. This is how the model currently looks class CustomUser(AbstractUser): first_name = models.CharField(_('first name'), max_length=30, blank=True) # from AbstractUser last_name = models.CharField(_('last name'), max_length=150, blank=True) # from AbstractUser organization_name = models.CharField(_('organization name'), max_length=180, blank=True) is_individual = models.BooleanField(default=False) is_organization = models.BooleanField(default=False) Is there a way specific fields can be set up for specific user types? Something like: Individual -- first_name -- last_name # more data concerning individuals Organization -- organization_name # more data concerning organizations -
IsDoctorPermission is not working in this class?
views Is doctor permissions are not working in this cclass ? class CreateEducationView(generics.ListCreateAPIView): serializer_class = EducationSerializer queryset = Education.objects.all() permission_classes = (permissions.IsAuthenticated,IsDoctorPermission) def perform_create(self, serializer): return serializer.save(doc_clinic=self.request.user) def get_queryset(self): return self.queryset.filter(doc_profile=self.request.user) -
Django templates ; Reverse for '' not found. '' is not a valid view function or pattern name
I have this error with templates, I don't understand what's the problem, pls help NoReverseMatch at /login/ Reverse for '' not found. '' is not a valid view function or pattern name. Request Method: GET Request URL: http://localhost:5000/login/ Django Version: 3.1 Exception Type: NoReverseMatch Exception Value: Reverse for '' not found. '' is not a valid view function or pattern name. Exception Location: /home/daniiar/.local/lib/python3.8/site-packages/django/urls/resolvers.py, line 685, in _reverse_with_prefix Python Executable: /usr/bin/python3 Python Version: 3.8.5 Python Path: ['/home/daniiar/land-gPage', '/usr/lib/python38.zip', '/usr/lib/python3.8', '/usr/lib/python3.8/lib-dynload', '/home/daniiar/.local/lib/python3.8/site-packages', '/usr/local/lib/python3.8/dist-packages', '/usr/lib/python3/dist-packages'] Server time: Sat, 16 Jan 2021 13:39:04 +0600 Error during template rendering In template /home/daniiar/land-gPage/auto/templates/base.html, error at line 14 Reverse for '' not found. '' is not a valid view function or pattern name. 4 <html> 5 <head> 6 <title>{% block title %}{% endblock %}</title> 7 <link href="{% static 'css/base.css' %}" rel="stylesheet"> 8 </head> 9 <body> 10 <div id="header"> 11 <span class="logo">Bookmarks</span> 12 {% if request.user.is_authenticated %} 13 <ul class="menu"> 14 <li {% if section == 'dashboard' %}class="selected"{% endif %}> 15 <a href="{% url 'dashboard' %}">My dashboard</a> 16 </li> 17 <li {% if section == 'images' %}class="selected"{% endif %}> 18 <a href="#">Images</a> 19 </li> 20 <li {% if section == 'people' %}class="selected"{% endif %}> 21 <a href="#">People</a> … -
django return Database.Cursor.execute(self, query, params) django.db.utils.OperationalError: no such table:
I have a simple model class as below class Language(models.Model): name= models.CharField(max_length=20) code= models.CharField(max_length=5) status=models.BooleanField() create_at=models.DateTimeField(auto_now_add=True) update_at=models.DateTimeField(auto_now=True) def __str__(self): return self.name and I want to use it like this llist = Language.objects.filter() list1 = [] for rs in llist: list1.append((rs.code,rs.name)) langlist = (list1) but it keeps throwing this error when I try to use llist : return Database.Cursor.execute(self, query, params) django.db.utils.OperationalError: no such table: home_language I tried to use python manage.py shell to make querries and it's showing the same above error. -
Django: Getting 403(csrf token validation error) If I make POST/PUT request one after other
I have page where I render datatables to display the data with buttons like edit and delete per row,I have also one global button to create new entry. The create button opens a modal form which is standard bootstrap model. I am using this same form to create & update records.So if refresh my page & create one new entry it works but without refresh when click on the edit button then submit the modal form it gives me this error, CSRF verification failed. Request aborted. All this operations are performed using the AJAX request so I am not reloading the page after each request.How can I resolve this? Here is my server side code you want to take a look, class CategoryView(AdminLoginRequiredMixin,View): def post(self, request): form = DownloadableCategoryForm(request.POST) if not form.is_valid(): return JsonResponseBuilder.validation_error(form.errors) form.save() return JsonResponseBuilder.success('Category created succesfully...') # to update category def put(self, request): try: category = DownloadableCategory.objects.get(pk=request.POST.get('id')) except DownloadableCategory.DoesNotExist: return JsonResponseBuilder.error('Category not found!', HTTPStatus.NOT_FOUND.value) form = DownloadableCategoryForm(request.POST,instance=category) if not form.is_valid(): return JsonResponseBuilder.validation_error(form.errors) form.save() return JsonResponseBuilder.success('Category updated succesfully...') -
render_form() missing 1 required positional argument: 'form'
I am getting this error for my code given below. Can someone help me out class CreatePost(LoginRequiredMixin,SelectRelatedMixin,generic.CreateView): fields = ('message','group') model = models.Post def form_valid(self,form): self.object = form.save(commit=False) self.object.user = self.request.user self.object.save() return super().form_valid(form) -
how to dynamically add text input field in model on the basis on no of choice selected in drop down(using easy_select2) in django python
I have created a model in Django which contains a easy-select2 drop down field Vendor : class Offer(models.Model): Offer_Name=models.CharField(max_length=200,blank=False) StartBid=models.CharField(max_length=100,blank=False) JumpBid=models.CharField(max_length=100,blank=False) Vendor=models.ManyToManyField(User,limit_choices_to={'is_vendor': True},help_text = "Please select vendor valid for this offer") LastBid=models.CharField(max_length=100) In this i want to modify LastBid field such that if 3 options are selected in Vendor than 3 Last bid input fields are created dynamically for each option.I'm new to django and tried using dynamic-django-forms 0.1.5 but was unable to implement the same. Please help. -
My code is not working - Form is not getting submitted
<!-- The form markup --> <div class="modal fade" id="exampleModal" tabindex="-1" aria-labelledby="exampleModalLabel" aria-hidden="true"> <div class="modal-dialog modal-dialog-centered"> <div class="modal-content"> <button type="button" class="btn-close" data-bs-dismiss="modal" aria-label="Close"></button> <div> <h1 class="text-primary fw-bold text-center log-in-title">Log In</h1> </div> <div class="mt-3 text-center"> <!-- The form --> <form class="mod-auth"> <div class="mb-3"> <input id="mod-auth-username" type="text" placeholder="Username" name="username" class="form-control" required> </div> <div class="mb-3"> <input id="mod-auth-password" type="password" placeholder="Password" name="password" class="form-control" required> </div> <div class="d-grid gap-2 mx-auto"> <button class="btn btn-primary" type="button">Log in</button> </div> </form> <hr> <h6>Don't have an account? <a href="/sign-up/?next={{request.path}}">Sign up</a></h6> </div> </div> </div> </div> // AJAX Post request $(document).on('submit', '.mod-auth', (e) => { e.preventDefault(); console.log('hi'); $.ajax({ url: '/log-in/', type: 'POST', data: { csrfmiddlewaretoken: $('input[name=csrfmiddlewaretoken]').val(), username: $('#mod-auth-username').val(), password: $('#mod-auth-password').val(), }, success: function() {}, }); }); My code is not working, I have added a jQuery form submit event, which is not working. I am unable to figure out what is the problem. The form is a part of a Modal (Bootstrap), which is fired when a user tries to click a Like button without logging in, the modal contains a form, which has to be filled and submitted, then an AJAX Post request gets executed and the data is sent to the views.py. Thank you. Your help is appreciated.