Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Django: Create view in admin panel for multi file upload
I have a model (MediaModel) with an imagefield, a description (charfield) and tags (manytomany with Tag model). The goal is to be able to upload an image with a description, some tags etc, in the admin panel. This part works fine. But I would like to be able to upload multiple file at a time. So, how can I have an admin page with an upload field (which allow multiple file upload), and with a tag list to select, which will create a MediaModel for each uploaded file. I don't want to create another model: I want to create a MediaModel with an empty description and the selected tags for each uploaded file. Any help is appreciated! -
Stop infinite loop in self-referencing models
I am writing a little utility which allows me to populate data models with a number of records. I used python faker to set the values for each field based on their field-type. What I do next, is that I use model._meta.get_fields to extract all the fields, remove all Rel types, and then populate non-relational fields with the correct values. For relational fields (where .re_relation = True) I follow the relation to the related model, then do the same for that model as well until I reach a model where there is no more relations to other models. Then create instances for each model. Basically a recursive process. My problem is with self-referencing models which cause an infinite loop. I thought of setting these instances to null but what about instances where null is set to False? Is there any clean way to handle situations like this? I couldn't find anything on the net or stackoverflow. ps: the code is pretty long so I didn't post anything. But I can if it's necessary. -
Django SIgnals Cannot assign... 'Mensagem.Chat' must be a "Chat" instance
I'm finishing a college project and I'm stuck on generating notifications whenever a user sends a message to another, I have a notification model, but I'm not able to send the message to the notification in django admin I can already insert the notification and display the screen, but only manually, when the user sends the message, it is not sent to the notification model :'( I'm not able to create a chat instance to put here stream = Mensagem(texto=message, chat=chat) stream.save() from users.models import MyUser from Chat.models import Mensagem from products.models import Product class Notification(models.Model): title = models.ForeignKey(Product, null=True, blank=True,on_delete=models.CASCADE) message = models.ForeignKey(Mensagem, null=True, blank=True,on_delete=models.CASCADE) viewed = models.BooleanField(default=False) sender = models.ForeignKey(MyUser, null=True, blank=True, on_delete=models.CASCADE,related_name="noti_from_user") user = models.ForeignKey(MyUser, null=True, blank=True, on_delete=models.CASCADE, related_name="noti_to_user") from django.db import models from django.db.models.signals import post_save, post_delete class Chat(models.Model): codigoSala = models.CharField(max_length=20, unique=True) locador = models.CharField(max_length=50, blank=False, null=False) locatario = models.CharField(max_length=50, blank=False, null=False) nomeSala = models.CharField(max_length=200, blank=True, null=True) def __str__(self): super().__init__() return self.codigoSala def add_chat(self): sender_message = Chat( self.codigoSala, self.locador, self.locatario, self.nomeSala) sender_message.save() class Mensagem(models.Model): texto = models.CharField(max_length=80) chat = models.ForeignKey(Chat, on_delete=models.CASCADE) def __str__(self): return self.texto def add_message(sender, instance, created, **kwargs): message = instance chat = Chat.objects.create() stream = Mensagem(texto=message, chat=chat) stream.save() post_save.connect(Mensagem.add_message, sender=Mensagem) error: Cannot … -
KeyError at /api/login 'user'
This user keyword error is showing in my login api. I am not sure why. I am guessing user instance is not available in the login view. I am new and I dont know the reason. This is my login view: class LoginUserView(GenericAPIView): permission_classes = [AllowAny] serializer_class = UserLoginSerializer def post(self, request, *args, **kwargs): data = request.data serializer = UserLoginSerializer(data=data) serializer.is_valid(raise_exception=True) user = serializer.validated_data["user"] token, created = Token.objects.get_or_create(user=user) return response.Response({"token": token.key}, status=status.HTTP_200_OK) This is my serializers: class UserLoginSerializer(serializers.ModelSerializer): email = serializers.EmailField(label='Email Address') class Meta: model = User fields = [ 'email', 'password', ] extra_kwargs = {"password": {"write_only": True}} def validate(self, data): # user = None email = data.get("email", None) password = data.get("password") if not email: raise serializers.ValidationError("Email is required for login") if not password: raise serializers.ValidationError("Password is required for login") user = authenticate(email=email, password=password) if not user: raise serializers.ValidationError("This email is not valid/already exists") return data -
django: pass formset data into another view
My issue kind of build on this one post How to pass data between django views. I am trying to do a similar thing which is to use the data inputed in view 1 into view2. However, the challenge is that with a formset, I need to be accessing multiple rows of data input and not just values. I don't know how to achieve this here is what I have so far: view 1: def New_Sales(request): #context = {} form = modelformset_factory(historical_recent_data, fields=('Id', 'Date','Quantity', 'NetAmount', 'customer_name')) if request.method == 'GET': formset = form(queryset= historical_recent_data.objects.none()) #blank_form = formset.empty_form elif request.method == 'POST': formset = form(request.POST) #blank_form = formset.empty_form if formset.is_valid(): request.session['sale'] = request.POST['sale'] for check_form in formset: check_form.save() quantity = check_form.cleaned_data.get('Quantity') id = check_form.cleaned_data.get('Id') update = replenishment.objects.filter(Id = id).update(StockOnHand = F('StockOnHand') - quantity) update2 = Item2.objects.filter(reference = id).update(stock_reel = F('stock_reel') - quantity) return redirect('/dash22.html') return render(request, 'new_sale.html', {'formset':formset}) and view 2: def invoice_view(request): request = request.session.get('sale')) #... i need to get each row of the formset from the above view #and I am stuck!! I am hoping that someone would have a solution, I cannot find anything about this in django doc. -
Django: latest record for each value of another field
Let us say we have a TemperatureForecast model (see below for a Django definition). A forecaster will produce many forecasts of the same target period (say 2021-01-01 6AM UTC), because it will forecast the temperature for that period again and again (at 2020-12-31 8PM UTC, at 2020-12-31 9PM UTC and so on). Now say we would like to know the "latest" (to be defined after the model definition) temperature forecast, by a given forecaster, for each hour from 2021-01-01 1AM to 2021-01-31 10AM. That is, I need to retrieve the "latest" record for each target datetime. In this example, we would have (at most) 10 records. The Django model (with Postgres backend) would look as follows: from django.db import models from .forecaster import Forecaster class TemperatureForecast(models.Model): forecaster = models.ForeignKey(Forecaster, on_delete=models.PROTECT) temperature_in_c = models.FloatField() forecast_datetime = models.DateTimeField() forecast_time_delta_in_s = models.IntegerField() # the time of creation of the record # not the time of the forecast was actually made created_at = models.DateTimeField(auto_now_add=True) forecast_datetime is the field we would like to group by and forecast_time_delta_in_s is the field we would to minimize by ("latest" means min(forecast_time_delta_in_s)). (Assuming created_at was reliable, forecast_time_delta_in_s can be thought of as forecast_datetime - created_at. But created_at cannot be … -
fillter and get all the values greater than current date
I want to filter and get all the values greater than current date. I researched about it, but couldn't able to figure out what is wrong in my code. below is models.py class TrainingDetails(models.Model): code = models.CharField(max_length=60) name = models.CharField(max_length=60) description = models.TextField(default='') trainer_name = models.ManyToManyField(TrainerDetails, blank=True, related_name='trainer',default='') tutorial_image = models.ImageField(upload_to='media') agenda = models.FileField(upload_to='media') from_time = models.ManyToManyField(TrainingDate,blank=True, related_name='from_times', default='') trainingdate = models.ManyToManyField(TrainingDate,blank=True, related_name='dates', default='') to_time = models.ManyToManyField(TrainingDate,blank=True, related_name='to_times', default='') url = models.ManyToManyField(TrainingData, blank=True, related_name='links', default='') document = models.ManyToManyField(TrainingData, blank=True, related_name='files' ,default='') tutorial_name = models.ManyToManyField(TrainingData, blank=True, related_name='tut_name' ,default='') department = models.CharField(max_length=60) is_active = models.BooleanField() def __str__(self): return self.name class Meta: verbose_name_plural = "TrainingDetails" views.py class TrainingDetailsViewSet(viewsets.ModelViewSet): queryset = TrainingDetails.objects.all().order_by('code') serializer_class = TrainingDetailsSerializer def get_queryset(self): queryset = self.queryset today = datetime.date.today() trainingdate = TrainingDate.objects.values('trainingdate') query_set = queryset.filter(trainingdate__gte = today) return query_set -
how to fix import error in django project?
i have a django project, i want to import views from my app called projects from django.urls import path from . import views urlpatterns = [ path("", views.project_index, name="project_index"), path("<int:pk>/", views.project_detail, name="project_detail"), ] i got this error Traceback (most recent call last): File "d:/firstwebapp/mysite/projects/urls.py", line 2, in <module> from . import views ImportError: attempted relative import with no known parent package -
Method Not Allowed (POST): /
I'm new to Django. I am trying to use Django Tutorial , but when i click on the button to vote I've got this error: Method Not Allowed (POST): /hewramanapp/2/results/ Method Not Allowed: /hewramanapp/2/results/ [29/Oct/2020 10:56:33] "POST /hewramanapp/2/results/ HTTP/1.1" 405 0 everything was good til i change some views from function to generic view i don't know where i did a mistake, thanks for help. views: from django.shortcuts import render, get_object_or_404 from django.http import HttpResponseRedirect from .models import Proverb, Choice from django.urls import reverse from django.views import generic # Create your views here. class IndexView(generic.ListView): template_name = 'hewramanapp/index.html' context_object_name = 'latest_proverb_list' def get_queryset(self): return Proverb.objects.order_by('-pub_date')[:5] class DetailView(generic.DetailView): model = Proverb template_name = 'hewramanapp/detail.html' class ResultsView(generic.DetailView): model = Proverb template_name = 'hewramanapp/results.html' def vote(request, proverb_id): proverb = get_object_or_404(Proverb, pk=proverb_id) try: selected_choice = proverb.choice_set.get(pk=request.POST['choice']) except (KeyError, Choice.DoesNotExist): # Redisplay the question voting form. return render(request, 'hewramanapp/detail.html', { 'proverb': proverb, 'error_message': "You didn't select a choice.", }) else: selected_choice.votes += 1 selected_choice.save() # Always return an HttpResponseRedirect after successfully dealing # with POST data. This prevents data from being posted twice if a # user hits the Back button. return HttpResponseRedirect(reverse('hewramanapp:results', args=(proverb.id,))) urls: from django.urls import path from . import views app_name = … -
Why Django project deployment does not work on Apache server?
I have a problem deploying the Django project. This project works well locally. But when deploying on the server, it has a problem. The project folder structure is as follows: project ├── api │ ├── __init__.py │ ├── requests.py │ └── urls.py ├── Services │ ├── __init__.py │ └── RequestService.py ├── DataAccess │ ├── __init__.py │ ├── sqlBase.py │ ├── sqlHelper.py │ └── sqlHelperBids.py ├── Model │ ├── __init__.py │ ├── GetActiveRequestsChangeByDestinationCountry_Result.py │ └── ..and so on.py ├── requirements.txt └── manage.py With repeated checks, I realize that this line has a problem: in requests.py : from Services.RequestService import RequestService and all calls are as follows: from django.http import HttpResponse from rest_framework.decorators import api_view from rest_framework.utils import json from DataAccess.sqlHelper import SqlHelper from Model.ApiResponse import ApiResponse from Services.RequestService import RequestService from Utility.Assistant import Assistant The project runs well when I clear this line The permissions of the folders were also checked, but there was no problem. -
502 Bad Gateway in google cloud using Django and postgresql
I deployed my Django app with postgresql db to google app. When I ran the app local it worked fine. After deploying the app everytime I tries to log-in to the site or retrieve data from the data base I get this error. 502 Bad Gateway nginx Django's data base settings If you need more information to solve this issue please let me know. Thanks! logs: 2020-10-29 10:43:25 default[20201029t122844] "GET / HTTP/1.1" 200 2020-10-29 10:43:26 default[20201029t122844] "GET /static/css/master.css HTTP/1.1" 304 2020-10-29 10:43:26 default[20201029t122844] "GET /static/css/home.css HTTP/1.1" 304 2020-10-29 10:43:26 default[20201029t122844] "GET /static/images/logo.png HTTP/1.1" 304 2020-10-29 10:43:26 default[20201029t122844] "GET /static/images/Yosemite.jpg HTTP/1.1" 304 2020-10-29 10:43:27 default[20201029t122844] "GET /accounts/login/ HTTP/1.1" 200 2020-10-29 10:44:09 default[20201029t122844] [2020-10-29 10:44:09 +0000] [10] [CRITICAL] WORKER TIMEOUT (pid:124) 2020-10-29 10:44:10 default[20201029t122844] [2020-10-29 10:44:10 +0000] [145] [INFO] Booting worker with pid: 145 -
How exactly do I use crispy_addon to prepend a form field?
I'm using Django crispy forms and modelform_factory to generate my form. It looks something like this: ModelForm = modelform_factory(Street) form = ModelForm(request.POST or None, instance=my_record) Then in the template I run this: {% crispy form %} And it generates my bootstrap4 form exactly as intended. However, I'd like to have a single field in my very long form to have a prepended text (@ for a Twitter handle). In the documentation it reads: templatetags.crispy_forms_field.crispy_addon(field, append='', prepend='', form_show_labels=True)[source] Renders a form field using bootstrap’s prepended or appended text: {% crispy_addon form.my_field prepend="$" append=".00" %} You can also just prepend or append like so {% crispy_addon form.my_field prepend=”$” %} {% crispy_addon form.my_field append=”.00” %} I've tried using this as follows in my template: {% crispy form %} {% crispy_addon form.url prepend=”@” %} But this returns the following error: Invalid block tag on line 12: 'crispy_addon', expected 'endblock'. Did you forget to register or load this tag? What am I doing wrong here? -
Copying text of <td> elements of table by clicking on text with javascript
I have a table with some of its columns containing text that is gonna be copied quite often. Despite knowing no javascript, I adventured myself into the challenge of making the content copyable on click and managed to get this working: function copy(event) { console.log("Triggered") var target = event.target || event.srcElement; console.log("Targeted") var copyText = target.innerText || target.textContent; navigator.clipboard.writeText(copyText) } var plist = document.querySelectorAll("p"); for (var i=0; i < plist.length; i++) { plist[i].addEventListener("click", copy) } <!DOCTYPE html> <html> <body> <h1>Copy selector Test</h1> <p>Hi There.</p> <p>I want to copy</p> <p>each of these p's</p> <p>by clicking them.</p> </body> </html> Well, considering my javascript knowledge, I'm pretty sure that isn't the most efficient or correct way of doing it (looping each element and adding an eventlistener to each one seems a bit of unnecesary work to me). Any correction is welcome. Now let's say I want each of the cells of the "Last" column to be copied in the same way that the p's were copied in my snippet. How could I get it done? It would be also cool to highlight the text that's been copied (I tried with .select() but apparently that only works with input elements). The table is gonna … -
django.db.utils.OperationalError: could not connect to server: Connection refused DJANOG gitlab CI
I am trying to run django test on CI gitlab but getting this error : django.db.utils.OperationalError: could not connect to server: Connection refused Is the server running on host "127.0.0.1" and accepting TCP/IP connections on port 5432? whilt my yml file is like stages: - test variables: POSTGRES_DB: asdproject POSTGRES_USER: runner POSTGRES_PASSWORD: asdpassword test: type: test script: - whoami - export DATABASE_URL=postgres://runner:asdpassword@postgres:5432/asdproject - apt-get update -qy - apt-get install -y python3-dev python3-pip - pip3 install -r requirements/base.txt - python3 manage.py test how I can connect postgresql here ? -
Python Django 3.0 URL problem, the browser adds an / at the end
I am new to programming and try to build a website with django 3.0 and Python 3.8.0 (64 bit) My question is why is it that the in the browsers (chrome and edge) wenn I enter http://127.0.0.1:8000/about it automatically adds an / at the end so it becomes http://127.0.0.1:8000/about/ Wenn I enter http://127.0.0.1:8000/services it works fine and shows the page. This is a problem because the extra / results in an error Page not found (404) Please help I am stuck in my learning -
gunicorn + nginx suddenly started to show 502 Bad Gateway
My set up worked stable and nicely for about 1 and a half month. I installed https://pypi.org/project/django-ipware/ with the following commands: pip install django-ipware - it installed for python 2.7 pip3 install django-ipware - I need django-ipware for python 3.6 I stopped and started gunicorn and nginx... My app still didn't see django-ipware... I forgot to switch off both gunicorn and nginx and restarted the server with the reboot command. After reboot, the site gives me 502 Bad Gateway... I deleted django-ipware app, it didn't help and I think my fault was at the hard reboot... What I noticed so far: My sc.sock file is not created on the start of gunicorn and nginx in the right location, which is: /home/evgeny/sc_project/sc.sock it is just not there... Despite I have right permission for the right person and right group: drwxrwxr-x 5 evgeny nginx 85 Oct 28 18:37 sc_project Instead gunicorn.sock always sits (even if gunicorn and nginx not activated) at the /run location. Like so: /run/gunicorn.sock As I understand it is default location, for some tutorials for gunicorn and nginx set up... Also, when I stop both engines, I have: [root@ [~]]# systemctl stop gunicorn Warning: Stopping gunicorn.service, but it can … -
How to import a variable from django into vue.js
I want to import a variable from a django generated html page into my App.vue component. My goal is to pass a String, which represent the user AuthGroup, eg. 'milkman', 'hairdresser' or 'supplier' The error Message looks like this: Module parse failed: Unexpected token (1:1) You may need an appropriate loader to handle this file type, currently no loaders are configured to > process this file. See https://webpack.js.org/concepts#loaders {% extends 'base.html' %} | {% load render_bundle from webpack_loader %} | {% load navtag %} frontend.html {% extends 'base.html' %} {% load render_bundle from webpack_loader %} {% load navtag %} {% block head %} <title>title</title> <script> const test = "{{ auth_group }}" // variable/string needed in App.vue </script> {% endblock %} [...] {% block content_vue %} <div id="app"> <app></app> </div> {% render_bundle 'app' %} {% endblock %} I can't figure out how to modify webpack or find a way to import the variable from django into the vue project. FYI: The vue project is a small part of a large Django environment. -
How to secure my files from my clients in django? [closed]
i created an app in django and using it on local server for right now. In this app client can upload the files. But the problem is that i don't want anyone to access the directory where my files are stored. I want my files to be stored in such a way that no body can delete, copy and edit that.How can i do it? -
Django migrations foreign key mismatch with legacy database
Hej all, I am trying to integrate a SQLite legacy database with Django v3.1.2, and so far it's pretty painful (new to django, so apologies if it's sth obvious). I assume something is wrong with my database schema or with the migration process. So here is what I did and my problem: I have run inspectdb on my legacy database and cleaned up the models, leaving me with the following two models (there are more models in my application, but these are the ones apparently causing a problem): class Integrons(models.Model): arg = models.ForeignKey('Args', on_delete=models.CASCADE) int_id = models.IntegerField(primary_key=True) int_start = models.IntegerField() int_stop = models.IntegerField() int_complete = models.CharField(max_length=500) class Meta: managed = False db_table = 'integrons' class IntElements(models.Model): int = models.ForeignKey('Integrons', on_delete=models.CASCADE) el_id = models.IntegerField() el_start = models.IntegerField() el_stop = models.IntegerField() el_name = models.CharField(blank=True, null=True, max_length=500) el_strand = models.CharField(blank=True, null=True, max_length=500) class Meta: managed = False db_table = 'int_elements' The respective fields in my legacy database are: Integrons: arg_id, int_id, int_start, int_stop, int_complete IntElements: int_id, el_id, el_start, el-stop, el_name, el_strand As seen in the models, IntElements.int_id should refer to Integrons.int_id. Now I am trying to migrate everything - running python manage.py makemigrations works fine. However, when running python manage.py migrate , I … -
How can i solve The QuerySet value for an exact lookup must be limited to one result using slicing. Django
I want to catagorize my posts. def katagori_girisim(request): cg = IlanKatagoriGirdi.objects.filter(katagoriler='Girisimci Mentorlugu') katagiri = IlanSayfa.objects.filter(ilan_katagori=cg) return render(request, 'pages/katagori_girisim.html', {'katagiri':katagiri}) I wrote this code in view. And I wrote this in template: {% for girisimilan in katagiri %} <div class="card"> <img src="/media/{{ girisimilan.ilan_foto }}" class="card-img-top img-fluid" style="width: 25rem; height: 15rem;" alt="ilan_foto"> <div class="card-body"> <h5 class="card-title text-center">{{ girisimilan.ilan_baslik }}</h5> <p class="card-text text-center">{{ girisimilan.ilan_aciklama }}</p> </div> </div> {% endfor %} But I am getting the error in the title. How can i solve this problem? -
add user_id attribute in AuthenticationMiddleware | Django
I have a following question regarding Django authentication middleware: class AuthenticationMiddleware(MiddlewareMixin): def process_request(self, request): assert hasattr(request, 'session'), ( "The Django authentication middleware requires session middleware " "to be installed. Edit your MIDDLEWARE setting to insert " "'django.contrib.sessions.middleware.SessionMiddleware' before " "'django.contrib.auth.middleware.AuthenticationMiddleware'." ) request.user = SimpleLazyObject(lambda: get_user(request)) As you can see here middleware calls method get_user from backend (in my case simple_jwt) and puts this method in a SimpleLazyObject in order to evaluate later. def get_user(self, validated_token): """ Attempts to find and return a user using the given validated token. """ try: user_id = validated_token[api_settings.USER_ID_CLAIM] except KeyError: raise InvalidToken(_('Token contained no recognizable user identification')) try: user = User.objects.get(**{api_settings.USER_ID_FIELD: user_id}) except User.DoesNotExist: raise AuthenticationFailed(_('User not found'), code='user_not_found') if not user.is_active: raise AuthenticationFailed(_('User is inactive'), code='user_inactive') return user What I want to do is to keep request.user = SimpleLazyObject(lambda: get_user(request)) in order to provide user instance for apps that uses it but for my custom apps I want to add something like pseudocode request.user_id = user_id from user (user_id = validated_token[api_settings.USER_ID_CLAIM]) in order to not query database each and every request for user object in case I need only user_id which I already have directly in get_user method in backend. Question – how to … -
Django CSV and data output
Have been trying to put something together which takes an uploaded csv file of all employees data from the previous day, this includes quite a few different columns such as name, rate , up and downtime. This will be added to each day, to build the database, I have looked into a few different ways to then output that data in a user friendly way where you can see each employee data over the past week month year etc could someone please recommend the best way to implement this? I have so far looked into Charts.JS and read through some documentation. Not even sure if python or django are the best route for this application. -
I am getting an error in django project while submitting the form can any one please tell the correction of my error
Error Page not found (404) Request Method: POST Request URL: http://localhost:8000/contact/contact Using the URLconf defined in portfolio.urls admin/ [name='home'] about/ [name='about'] projects/ [name='projects'] contact/ [name='contact'] The current path, contact/contact, didn't match any of these. **code for the form ** <form action="contact" method="POST"> {% csrf_token %} <div class="form-group"> <label for="name">Name</label> <input type="text" class="form-control" id="name" name="name" placeholder="Your Name"> </div> <div class="form-group"> <label for="email">Email address</label> <input type="email" class="form-control" id="email" name="email" placeholder="name@example.com"> </div> <div class="form-group"> <label for="phone">Phone Number</label> <input type="phone" class="form-control" id="phone" name="phone" placeholder="Your Number"> </div> <div class="form-group"> <label for="exampleFormControlTextarea1">Explain your concern</label> <textarea class="form-control" id="desc" rows="3"></textarea> </div> <button type="submit" class="btn btn-success">Submit</button> </form> views.py def contact(request): return render(request,"contact.html") urls.py this url is from my app urlpatterns=[ path("",views.home,name="home"), path("about/",views.about,name="about"), path("projects/",views.projects,name="projects"), path("contact/",views.contact,name="contact"), ] urls.py this url is from my project urlpatterns = [ path('admin/', admin.site.urls), path("",include("home.urls")), ] -
Admin user specified python code to be executed as API later
Working on a webapp for a client. They want to be able to specify a function in Python that will calculate an end result based on end user inputted parameters. Is it possible to store their code (saved from a text field in an admin panel) and execute it later as an API (django or flask), with the relevant parameters (provided by the end user, ie not admin) at runtime? Or any better way to handle that? -
Still recognize my null input field as same exist error
Cannot change the Django field from mandatory to optional input I have a sign up form that requires the users to fill in their phone number. Now ,I want to change it from mandatory to optional .But it fails and still recognizes my phone number null input as '#phone_exist_error' .How to fix? view.py def signup(request): username=request.POST.get('username') email=request.POST.get('email') password=request.POST.get('password') phone_no=request.POST.get('phone_no') .... if Signup.objects.filter(username=username).exists(): return HttpResponse("user_name_exists") elif Signup.objects.filter(email=email).exists(): return HttpResponse("email exists") # I have commented these code already! # elif Signup.objects.filter(phoneno=phone_no).exists(): # return HttpResponse("phone exists") else: if dob: user_obj=Signup(username=username,email=email,password=password,phoneno=phone_no,dob=dob,gender=gender,profile_image=profile_img,email_status=email_all,pwd_status=phone_all,bio=bio) user_obj.save() else: user_obj=Signup(username=username,email=email,password=password,phoneno=phone_no,gender=gender,profile_image=profile_img,email_status=email_all,pwd_status=phone_all,bio=bio) user_obj.save() ... return HttpResponse("success") Register.html var form = $("#form_data")[0]; var data_item = new FormData(form); data_item.append("profile_img",document.getElementById("imgInp").files[0]) data_item.append("username",username) data_item.append("password",password) data_item.append("cnf_password",cnf_password) data_item.append("email",email) data_item.append("phone_no",phone_no) ... $("#loading").show() $.ajax({ method : "POST", url : "/signup/", enctype : "mutipart/form_data", processData : false, contentType : false, cache : false, data : data_item, success : function(response){ console.log(response) $("#loading").hide() if (response == "success") swal("Registration Saved Successfully", { icon: "success", button: "Ok", closeOnClickOutside: false, }).then(function() { location.href = "/signin/"; }); else if (response == "email exists"){ $('#error_email_exists').show(); $('#email').focus(); } <!-- null input but activate this --> else if (response == "phone exists"){ $('#phone_exist_error').show(); $('#phone_no').focus(); } else if (response == "user_name_exists"){ $('#error_name_exists').show(); $('#username').focus(); } } });... $('#phone_no').keyup(function(){ $('#phone_no_error').hide(); $('#phone_exist_error').hide(); })