Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
my phone can't login to Django admin panel.(but my pc can ???)
i got a problem i deploy my django app with azure and azure PostgreSQL.i can login admin perfectly fine with pc but when i give link to my friend for login to admin and this happened this picture i login by my phone and it says the same of my friend when they login but i login by my pc it fine. and this my setting.py 1 2 3 4 i want to let my friend login to admin for editing database. -
Bootstrap and CSS Styling not working with Django Forms
I have a django form where I have certain fields. Now I want to add some styling to it (bootstrap mostly). But it does not seem to be working. In my forms.py file from django import forms from django.core.validators import FileExtensionValidator file_type_choices = [ ('CSV', 'Comma-Separated Values'), ('TSV', 'Tab-Separated Values') ] valid_extensions = ['.tsv', '.csv'] class FileUploadForm(forms.Form): file = forms.FileField(allow_empty_file=False, \ validators=[FileExtensionValidator(allowed_extensions=valid_extensions)]) file_type = forms.ChoiceField(choices=file_type_choices, widget=forms.Select(attrs={"class": "form-control"})) source_language = forms.CharField(max_length=30,\ widget=forms.TextInput(attrs={"class":"form-control", "placeholder": "English"})) target_language = forms.CharField(max_length=30, \ widget=forms.TextInput(attrs={"class":"form-control"})) I also added bootstrap CDN links in the templates. And just for surety, added the following in settings.py file of the project: python CRISPY_TEMPLATE_PACK = 'bootstrap5' Also, its curious to see that placeholder is also not working. I don't see particular reason behind this. -
Django runserver crashes on chunked encoding
I am writing a Java client that posts a multipart/form-data request to a Django server. But Django logs an error (though the request continues to the view, just without the body). When Django is deployed behing Nginx it is working normally, which is why I suspect Django's runserver setup may not be able to handle it. The error is: code 400, message Bad request syntax ('23'). This 23 is part of the transfer-encoding: chunked that is being sent. I didn't find any reference that Django isn't able to understand chunked encoding so I am lost where this is going wrong. Java client, using Spring's WebClient: public void saveRecording(String token, Integer songId, String fileLocation) { var recording = new FileSystemResource(new File(fileLocation)); var data = new MultipartBodyBuilder(); data.part("songId", songId.toString(), MediaType.TEXT_PLAIN); data.part("recording", recording, MediaType.APPLICATION_OCTET_STREAM); webClient.post() .header("Authorization", token) .body(BodyInserters.fromMultipartData(data.build())) .retrieve() .toBodilessEntity() .block(); } Wireshark capture, notice the 23 after Content-Type which is part of the chunked encoding and which I believe is the reason for the error. POST /recording/save-recording/ HTTP/1.1 accept-encoding: gzip user-agent: ReactorNetty/1.1.5 host: localhost:8000 accept: */* transfer-encoding: chunked Authorization: 123e4567-e89b-12d3-a456-426614174000 Content-Type: multipart/form-data;boundary=GlYowTnlo8QZLczdlpPL6wSEhFBv1DA 23 --GlYowTnlo8QZLczdlpPL6wSEhFBv1DA 5e Content-Type: text/plain Content-Disposition: form-data; name="songId" Content-Length: 1 1 1 2 23 --GlYowTnlo8QZLczdlpPL6wSEhFBv1DA 8f Content-Type: audio/mpeg Content-Disposition: form-data; … -
Unable to render a D3 chart to my web page in a Django project
I have a Django project where a form takes a file from the user (.json), processes this file, populates a post-gres database, and then at the front-end I pull some of that data back out to render a table - this works well so far. However, I also want to draw a D3 bar chart that also pulls data from my db and plots it, this is what I am currently unable to do. I have created the chart in full, and it works correctly when I render it on its own template html. Though when I attempt to draw the chart beneath my main data table (on the page I need it to appear on), I am faced with problems. The issue is, I cannot get the d3 chart to appear on my main web page, anywhere. Here is the error message: Uncaught SyntaxError: Expected property name or '}' in JSON at position 1 at JSON.parse (<anonymous>) at d3bar.js:1:19 It looks like there's an issue with the formatting if the incoming json data, or least the object that emanates from the initial json data. I find this confusing because as I said, I can correctly display the d3 chart … -
QueryDict is empty, after received from the POST request
I used axios to send a POST request, here is my code: register: function (){ console.log("register start"); if (this.password !== this.confirmPassword) { alert("The Password IS DIFFERENT THAN CONFIRM PASSWORD!"); } else { console.log("register start"); const data = { firstname: this.firstname, lastname: this.lastname, username: this.username, email: this.email, password: this.password, confirmPassword: this.confirmPassword } console.log(data) axios.post("/register", data) .then(res => { alert("Register Success!"); console.log(res); }) .catch(error => { console.log(error); }) } } And here is the code for received the POST request: def register(request): try: # receive POST request, queryDict object if request.method == "POST": print("Post Request Received") user_info = request.POST print(request.body) print(user_info) except Exception as e: print("Error", e) return render(request, "error.html", context=e) return render(request, "register.html") However, I keep received an empty QueryDict but I did comform that the return type is Json and it does received something, here is the output: Post Request Received b'' QueryDict} I had found a method, which is replicate the POST request and decode it. Here is the code: if request.method == "POST": print("Post Request Received") request_data = request.body user_info = request_data.decode("utf-8") print(user_info) Here is the output, after the changed: Post Request Received {"firstname":"First Name","lastname":"Last Name","username":"username123","email":"username123@gmail.com","password":"12345678","confirmPassword":"12345678"} [25/Mar/2023 16:07:07] "POST /register HTTP/1.1" 200 5347 Post Request Received ------WebKitFormBoundarycXOVuwbkiaqZTvQy-- [25/Mar/2023 … -
mysql path environment variable not working
I am trying to connect mysql to the back end of my project in Django When I use the command mysql -u root -p I receive this error: 'mysql : The term 'mysql' is not recognized as the name of a cmdlet, function, script file, or operable program. Check the spelling of the name, or if a path was included, verify that the path is correct and try again.' I have installed mysql, configured it and additionally set the PATH in the environment variables windows panel. C:\Program Files\MySQL\MySQL Shell 8.0\bin\ when I search this error I only see to change the PATH but it is already done, I'm not sure why it isn't working. -
How can I retrieve a value from my PostgreSQL database and print it in my html website?
I am trying to take information that is submitted by the user in a form, and make a query to my PostgreSQL database to retrieve the average cost of the selected repair. While I can retrieve the value, I can only do so in the scope of the (if request.method == POST) statement. Is there a way I can retrieve the cleaned_data from my form and filter the database entries outside of the scope? Here is the code in my views.py file that contains the problematic code: from django.http import JsonResponse from django.shortcuts import render, redirect, get_object_or_404 from .forms import ModelCreationForm from .models import Make, Model, Car, Repair, Cost def model_create_view(request): form = ModelCreationForm() if request.method == 'POST': form = ModelCreationForm(request.POST) if form.is_valid(): form.save() cost_data = getFormData(request, form) return redirect('model_add') return render(request, 'models/home.html', {"form": form}) def getFormData(request, form): year = form.cleaned_data['year'] make = form.cleaned_data['make'] model = form.cleaned_data['model'] repair = form.cleaned_data['repair'] form_data = Cost.objects.filter(year = year, make = make, model = model, repair = repair) return render(request, 'models/home.html', {"cost": form_data[0]}) def model_update_view(request, pk): car = get_object_or_404(Car, pk=pk) form = ModelCreationForm(instance=car) if request.method == 'POST': form = ModelCreationForm(request.POST, instance=car) if form.is_valid(): form.save() return redirect('model_change', pk=pk) return render(request, 'models/home.html', {'form': form}) def load_models(request): … -
custom user model Django - AUTH_USER_MODEL refers to model that has not been installed
I created my custom user model which inherits from AbstractBaseUser. My model is located in api/models/userModel.py file. Api is the name of my application which I registered in INSTALLED_APPS in settings.py. I register my custom user model in settings.py with AUTH_USER_MODEL='api.UserAccount'. My problem is whenever I try to py manage.py makemigrations I get error: django.core.exceptions.ImproperlyConfigured: AUTH_USER_MODEL refers to model 'api.UserAccount' that has not been installed I tried to delete all migrations files and reset my DB but it doesn't work. Do you have any idea what is wrong ? -
Django: making user email unique=True is causing a problem
I made email field unique in the user model because I don't want users sharing same email. But now the problem is that when I created the first user without email address and then tried to create a second user without email address, I got error message about user with email already existing whereas there's no user yet with email address. I edited the first user and added an email address before I could successfully create a second user without email address. Please what am I doing wrong? I want to be able to create several users without email address. -
How to count quantity with data in table, depending on status?
I have a table that records printer paper activities. I need to find the amount of paper in the warehouse, for this I need to add the numbers with the value "arrived" and subtract the values "given" from them. How to do it? ID Office Number Status 000001 Stock 50 Arrived 000002 105-1 2 Given 000003 108-3 1 Given 000004 Stock 10 Arrived 000005 104-1 3 Given It should be 54 (+50-2-1+10-3). My code: Views.py class PaperReportView(ListView): model = PaperReport template_name = 'paper_list.html' ordering = ['name'] Models.py class PaperReport(models.Model): name = models.CharField('Office', max_length=255) amount = models.CharField('Amount', max_length=255) status = models.CharField('Status', max_length=255) def get_absolute_url(self): return reverse('paper_list') paper_list.html <h2>Printer paper left: <!-- The result should be here --><h2> <div> {% for case in object_list %} <div> <p>{{ case.amount }} pcs {{ case.status}} for {{ case.name }}</p> </div> {% endfor %} </div> -
How to store unknow number of entries in django sqlite module
I have the following form which the user select a product and quantity. Product_name Quantity product1 3 product2 2 + Add Product And a button to add a extra field in the table, the button can be used any number of times to add extra products. How can i store the users orders in the database? Result: a database with fields of users orders. -
Reverse for 'unassign_emp' with arguments '('',)' not found. 1 pattern(s) tried: ['unassign\\-emp/(?P<eid>[^/]+)/\\Z']
I have two views: one to show the list of assigned users and post method to assign new users. Second view: to delete a user from usecase_assigned table I’m showing everything in one template, and pressing delete button It’s executing another view and redirecting to the same page (UsecaseDetails.html): model: class UsecaseAssign(models.Model): usecase_assign_date = models.DateTimeField(primary_key=True, auto_now_add=True) usecase = models.ForeignKey(Usecase, models.DO_NOTHING) user_email = models.ForeignKey('User', models.DO_NOTHING, db_column='user_email') usecase_role_id = models.CharField(max_length=20) my views: @user_login_required def view_usecase_details(request, ucid): usecase_details = Usecase.objects.filter(usecase_id=ucid).all() usecase_details = usecase_details.prefetch_related("usecaseids") users = User.objects.all() #SELECT user_email FROM usecase_assign WHERE usecase_id LIKE 'NN245'; usecase_assigned = UsecaseAssign.objects.select_related('user_email').values_list('user_email__user_name').filter(usecase_id=ucid) #to show list of users working on uc if request.method=='POST' and 'assignuser' in request.POST: user_email = request.POST['user_email'] userAssignCheck = UsecaseAssign.objects.filter(user_email=user_email, usecase_id=ucid) if userAssignCheck: messages.error(request, "user already added!") return HttpResponseRedirect(reverse('usecase-details', args=[ucid])) else: userAssignObj = UsecaseAssign.objects.create(user_email_id=user_email, usecase_id=ucid) if userAssignObj: messages.success(request, "User was Successfully Assigned with Usecase!") return HttpResponseRedirect(reverse('usecase-details', args=[ucid])) context = {'usecase_details': usecase_details, "users": User.objects.all(), 'usecase_assigned':usecase_assigned, "users": users} return render(request, 'UsecaseDetails.html', context) ##ask in stack overflow with pic of url how to pass only the id clicked @user_login_required def unassign_emp(request, eid): if request.method == 'POST': unassign_emp = UsecaseAssign.objects.get(user_email=eid) unassign_emp.delete() messages.success(request, "User was unassigned with Usecase!") return redirect('myapp:usecase-details') my template: {% for result in usecase_details %} <div class="card card-body … -
Django serializer field with more than one type
I need to create a field that is either a CharField or a list of char fields. Pseudo code: class MySerializer(Serializer): my_field = CharField() | ListField(child=CharField()) ... I also need it to be properly recognised by DRF Spectacular so that the API docs state it can be either of those two field types. How can I achieve this? -
Why does pagination in django half working?
I tried to implement pagination in django using ajax. But for some reason my pagination is half working. That is, the buttons work, but nothing happens when you go to another page. I understand the problem is in the ajax code views.py: class ProjectDetail(DetailView): model = PortfolioStructure template_name = 'WebPortfolioApp/details.html' slug_url_kwarg = 'proj_slug' context_object_name = 'project' def get_context_data(self, **kwargs): context = super().get_context_data(**kwargs) context["other_blog_posts"] = Comment.objects.all().order_by('id') paginator = Paginator(context["other_blog_posts"], 3) page_two = self.request.GET.get("other-page") try: context["other_blog_posts"] = paginator.page(page_two) except PageNotAnInteger: context["other_blog_posts"] = paginator.page(1) except EmptyPage: context["other_blog_posts"] = paginator.page(paginator.num_pages) stuff = get_object_or_404(PortfolioStructure, slug=self.kwargs['proj_slug']) total_likes = stuff.total_likes() liked = False if stuff.likes.filter(id=self.request.user.id).exists(): liked = True context['total_likes'] = total_likes context['liked'] = liked return context pagination-two.html: <div class="container mt-5"> <nav id="pagination-two"> <ul class="pagination justify-content-center"> {% if other_blog_posts.has_previous %} <li class="page-item"> <a class="page-link" href="{{ request.path }}?other-page={{ other_blog_posts.previous_page_number }}"><</a> </li> {% else %} <li class="page-item disabled"> <a class="page-link" href="#" tabindex="1" aria-disabled="true"><</a> </li> {% endif %} {% for i in other_blog_posts.paginator.page_range %} {% if other_blog_posts.number == i %} <li class="page-item active"> <a class="page-link" href="{{ request.path }}?other-page={{ i }}">{{ i }}</a> </li> {% else %} <li class="page-item"> <a class="page-link" href="{{ request.path }}?other-page={{ i }}">{{ i }}</a> </li> {% endif %} {% endfor %} {% if other_blog_posts.has_next %} <li class="page-item"> <a … -
Why is django not detecting this import path of my custom middleware
I tried adding the middleware at the end of the list of middlewares in the settings.py file of the project. I double-checked the inclusion of my app in the list of installed apps in the same file. The directory of the installed app works for other parts of my project. I also tried doing an import of the middleware class that I've made inside of init.py (tried both the project's init file and the app's init file) The error I get is "ModuleNotFoundError: No module named 'front.middleware'" Directory: settings.py: """ Django settings for CloseUp project. Generated by 'django-admin startproject' using Django 4.1.7. For more information on this file, see https://docs.djangoproject.com/en/4.1/topics/settings/ For the full list of settings and their values, see https://docs.djangoproject.com/en/4.1/ref/settings/ """ from pathlib import Path import os # Build paths inside the project like this: BASE_DIR / 'subdir'. BASE_DIR = Path(__file__).resolve().parent.parent # Quick-start development settings - unsuitable for production # See https://docs.djangoproject.com/en/4.1/howto/deployment/checklist/ # SECURITY WARNING: keep the secret key used in production secret! SECRET_KEY = "django-insecure-i$rv^2g_phigb-!655)qp5_btr8+gw8xr_v)d-#5kw)$*u3mnj" # SECURITY WARNING: don't run with debug turned on in production! DEBUG = True ALLOWED_HOSTS = [] # Application definition INSTALLED_APPS = [ "front", "django.contrib.admin", "django.contrib.auth", "django.contrib.contenttypes", "django.contrib.sessions", "django.contrib.messages", "django.contrib.staticfiles", ] MIDDLEWARE = … -
React app creating cart but not getting cart from django backend
Gooday everyone I'm working on an ecommerce project and I'm trying to build the cart for the unauthenticated users. Instead of using user id to identify the cart I decided to use session id to identify users currently accessing the server. It works perfectly in the backend but there is a problem in the frontend. creating the cart works but when I try to get my cart using the react frontend it returns an empty list. models.py #for the cart from django.db import models from books.models import Book from django.contrib.auth import get_user_model from django.dispatch import receiver from django.db.models.signals import post_save User = get_user_model() class TimeStampedModel(models.Model): created = models.DateTimeField(db_index=True, auto_now_add=True) modified = models.DateTimeField(auto_now=True) class Meta: abstract=True class Cart(TimeStampedModel): total = models.DecimalField(max_digits=10, decimal_places=2, default=0, blank=True, null=True) session_id = models.CharField(max_length=100, blank=True) class CartItem(TimeStampedModel): cart = models.ForeignKey(Cart, related_name='cart_items', on_delete=models.CASCADE) product = models.ForeignKey(Book, related_name='cart_products', on_delete=models.CASCADE) quantity = models.IntegerField(default=1) def __str__(self): return self.product.__str__() Now I'll add my views.py file from django.shortcuts import get_object_or_404 from rest_framework.generics import ListCreateAPIView, CreateAPIView, ListAPIView, RetrieveUpdateDestroyAPIView, RetrieveAPIView from .serializers import CartItemSerializers, CartItemUpdateSerializers from rest_framework import permissions, status from rest_framework.response import Response from rest_framework.exceptions import NotAcceptable, ValidationError, PermissionDenied from .models import Cart, CartItem from books.models import Book from rest_framework.views import APIView import uuid … -
ModuleNotFoundError: No module named 'settings' for any django project
I have been studying Django for some time and have been working on a project. Everything was fine until yesterday when I was studying a new topic, saved the project and shut down my PC. There were no errors or anything. Today, when I tried to run my project using the command "py manage.py runserver", I received an error "ModuleNotFoundError: No module named 'settings'". I spent enough time trying to solve this problem and assumed that the error was in my project. I couldn't solve it and decided to create a completely new project in a new virtual environment. To my surprise, the same error occurred in this completely new project as well. I thought that I might be doing something wrong, so I repeated the project creation on my laptop, and everything worked as expected with no errors. I tried reinstalling PyCharm and Python, but it didn't help. I don't think I can continue using Django on this PC anymore... I don't know what data may be needed to solve this problem, so I will provide at least something. These are the data from the project that was just created. Project structure Installed modules Full error: During handling of … -
why django can't see javascript?
Django does not see javascript and css file, I don't know what is wrong and how to fix it This is my code JavaScript in html file: <style> .like-container{ width: 100px; height: auto; margin-bottom: 10px; } .like-container button{ background: none; border: none; } i{ font-size: 22px; cursor: pointer; } </style> <div class="like-container"> <p class="num-of-likes" id ="num">{{post.likes.count}}</p> {% if msg %} <i class="fa-solid fa-heart"></i> {% else %} <i class="fa-regular fa-heart"></i> {% endif %} <small>like</small> </div> </div> <script> function getCookie(name) { let cookieValue = null; if (document.cookie && document.cookie !== '') { const cookies = document.cookie.split(';'); for (let i = 0; i < cookies.length; i++) { const cookie = cookies[i].trim(); // Does this cookie string begin with the name we want? if (cookie.substring(0, name.length + 1) === (name + '=')) { cookieValue = decodeURIComponent(cookie.substring(name.length + 1)); break; } } } return cookieValue; } const csrftoken = getCookie('csrftoken'); let btn = document.querySelector("i") let num_of_likes = document.getElementById("num") let post_id = "{{post.id}}" btn.addEventListener("click", likePost) function likePost(e){ let url = "{% url 'like' %}" const data = {id:post_id} fetch(url, { method: 'POST', headers: {"Content-Type": "application/json", 'X-CSRFToken': csrftoken }, body : JSON.stringify(data) }) .then(res => res.json()) .then(data => { console.log(data) if(data["check"] == 1){ btn.classList.remove("fa-regular") btn.classList.add('fa-solid') } else … -
Can we use sqlite3 for django in production azure
i have developed a django app in my local pc using sqlite3 server and after hosting it on azure app service. Every time i push new version it overwrite database and static files what should be the best and free fix for this. Expecting solution and suggestions -
Getting this error 'QuerySet' object has no attribute 'pk' when passing queryset instance in Serializer with many=True
I have a view that is responsible for bulk updating objects, since DRF doesn't provide any generic view for that I proceed with this approach. In docs they are passing many=True and a queryset of objects in the serializer. this is from docs queryset = Book.objects.all() serializer = BookSerializer(queryset, many=True) serializer.data # [ # {'id': 0, 'title': 'The electric kool-aid acid test', 'author': 'Tom Wolfe'}, # {'id': 1, 'title': 'If this is a man', 'author': 'Primo Levi'}, # {'id': 2, 'title': 'The wind-up bird chronicle', 'author': 'Haruki Murakami'} # ] So decided to do something like that, here is my view.py file class PostListBulkUpdateApiView(GenericAPIView): serializer_class = PostListUpdateSerializer permission_classes = [permissions.IsAuthenticated, HasPostChangePermission, HasPostReadPermission, HasObjectDeletePermission] def get_serializer(self, *args, **kwargs): if isinstance(kwargs.get('data', {}), list): kwargs['many'] = True return super().get_serializer(*args, **kwargs) def get_queryset(self, ids=None): if ids: return Post.objects.filter(id__in=ids) return Post.objects.all() def put(self, request, *args, **kwargs): return self.update(request) def patch(self, request, *args, **kwargs): return self.update(request) def update(self, request, *args, **kwargs): ids = set() for data in request.data: id = data.get('id', None) if id is not None: ids.add(id) instance = self.get_queryset(ids=ids) serializer = PostListUpdateSerializer(instance=instance, data=request.data, partial=True, many=True) if serializer.is_valid(raise_exception=True): return Response(serializer.data, status=status.HTTP_200_OK) return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST) but it give me 'QuerySet' object has no attribute 'pk' error … -
View 'UPDATE' statements in Django Debug Toolbar (SQL panel)
I am using Django Debug Toolbar with my project. I am looking to view all SQL statements that are made by the app. Currently, only SELECT statements are shown. Is there a way to enable UPDATE and other statements? -
How to insert values into a form from another table?
I have two tables. A first table contains a list of offices and a second table contains a list of cartridges. When I create the cartridge, it's required to write the office. But it is necessary that in the form of creating a cartridge in the office selection there should be a list from the Offices. How to do it? For example, there is the list: Offices ID name 1 A11 2 A11-1 3 A12 4 A13 5 A13-2 My code: Models.py class Office(models.Model): name = models.CharField('name', max_length=255) def get_absolute_url(self): return reverse('office_list') class CartridgeList(models.Model): office = models.CharField('office', max_length=255) uniquenumber = models.CharField('unique number', max_length=255) status = models.CharField('status', max_length=255) def get_absolute_url(self): return reverse('cartridge_list') forms.py class CartridgeListForm(forms.ModelForm): class Meta: model = CartridgeList fields = ('office', 'uniquenumber', 'status') widgets = { # Now I write the office here, but it's required to have a ready list from Office Model (A11, A11-1, A12, A13, A13-2) 'office': forms.TextInput(attrs={'class': 'form-control'}), 'uniquenumber': forms.TextInput(attrs={'class': 'form-control'}), 'status': forms.TextInput(attrs={'class': 'form-control'}), } Views.py: class AddCartridgeListView(CreateView): model = CartridgeList form_class = CartridgeListForm template_name = 'add_cartridge.html' -
Populate Django Model with for-loop
I have a model Task which I want to populate with a for loop. In a list I have the tasks that should be passed into the model. My model has actually more than three tasks (Below I have shown only three). The list will also have varying number of entries. The list can also have only one task. tasks = ['first task', 'second task', 'third task'] class Task(models.Model): ad = models.OneToOneField(Ad, on_delete=models.CASCADE, primary_key=True, blank=True, null=False) task1 = models.CharField(max_length=256, blank=True, null=True) task2 = models.CharField(max_length=256, blank=True, null=True) task3 = models.CharField(max_length=256, blank=True, null=True) def __str__(self): return f'Tasks for {self.ad}' My approach looks like this: task_obj = Task.objects.create( ad = ad ) for idx, t in enumerate(tasks): task_obj.f'task{idx+1}' = t Basically this part f'task{idx+1}' should not be a string, but the actual variable of the model. Is this even possible? Or does an other way exist I am not aware of? -
Implement search bar in django
I want to implement two things: User page from URL: If I enter a URL like '.../username', I am taken to that page provided it exists. For that I mapped 'str:username' to user_profile view. Then I will perform a query and display the page dynamically. This part is working fine. Next is implementing a search bar where I will enter a username and submit to call the same function passing the input value as the argument to that view function. I tried various method like {% url 'user_profile' username=username %}. Used various if else conditions but still I am unable to make it. -
jQuery remote validate not working with django url
when i submit form, adno field (number) not validate excluding empty my template.html <input name="adno" id="id_adno" type="number" class="form-control" placeholder="" required> jquery validate remote adno: { remote: { url: "{% url 'is_adno_valid' %}", type: "post", data: { field_value: function () { return $("#my_field").val(); }, csrfmiddlewaretoken: "{{ csrf_token }}" } } }, views.py and urls.py def is_adno_valid(request): adno = int(request.POST.get('adno')) return JsonResponse({'status':adno==1111}) urls.py path('is_adno_valid',views.is_adno_valid, name='is_adno_valid'), when i try to submit form with adno field as empty, red border of error showing. but whe enter any number it not showing error. ie, remote not working