Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Error while entering the login form details based on signup form
I am trying to enter the details in login form.But it is not authenticating the username and password with the existing usernames and passwords present in form data. Here is my code views.py from django.shortcuts import render from django.http import HttpResponseRedirect, HttpResponse from django.urls import reverse from django.contrib.auth import authenticate, login, logout from . forms import signup_form,loginform,profileform from . models import registration_form def index(request): return render(request,'loginapp/index.html') def display_form(request): rform = signup_form(request.POST) if rform.is_valid(): rform.save() return HttpResponseRedirect('/profile/') else: return render(request,'loginapp/first.html',{'rform': rform}) def login_form(request): if request.method == 'POST': Username = request.POST.get('Username') Password = request.POST.get('Password') registration_form= authenticate(Username=Username,Password=Password) print("Username") if registration_form is None: if registration_form.is_active: login(request,registration_form) return HttpResponseRedirect(reverse('index')) else: return HttpResponse("Your account was inactive.") else: print("Someone tried to login and failed.") print("They used Username: {} and Password: {}".format(Username,Password)) return HttpResponse("Invalid login details given") return HttpResponseRedirect('/profile/') else: return render(request, 'loginapp/login.html', {}) def profile_form(request): return render(request,'loginapp/profile.html') -
How do I use BeautifulSoup to search for elements that occur before another element?
I'm using BeautifulSoup 4 with Python 3.7. I have the following HTML ... <tr> <td class="info"><div class="title">...</div></td> </tr> <tr class="ls"> <td colspan="3">Less similar results</td> </tr> <tr> <td class="info"><div class="title">...</div></td> </tr> I would like to extract the DIVs with class="title", however, I only want to find the ones that occur before the element in the table whose TD text = "Less similar results". Right now I have this elts = soup.find("td", class_="info").find_all("div", class_="title") But this returns all DIVs with that class, even ones that have occurred after the element I want to screen for. How do I refine my search to only include results before that particualr TD? -
Static file collections - Logo navbar does not show up
I am trying to have an image (logo) on the navbar. My project is called "mysite-project" (where manage-pyis), it contains the app "mysite". In order to upload my static file I did the following: 1) mysite-project/mysite/settings.py I added: STATIC_ROOT = os.path.join(BASE_DIR,"static") STATIC_URL = '/static/' STATICFILES_DIRS = [ os.path.join(BASE_DIR, '/static/') ] 2) Created folders static and added my logo.png in: mysite-project/static/mysite-project/logo.png 3) mysite-project/templates/base.html {% load staticfiles %} <nav class="navbar navbar-expand-lg navbar-light bg-light"> <a class="navbar-brand" href="{% url 'home' %}"> <img src="{% static 'mysite/logo.png' %}" height=30 width=30 class="d-inline-block alighn-top" /> Code of Conduct </a> </nav> HOWEVER the image does not show up. I think I have some issues in the settings.py for the folders but I cannot find where -
What is different between django foreigin key in string and without string?
I am not getting why people write foreign key in two way and what is the purpose of this? are they both same or any different? I notice some people write like: author = models.ForeignKey(Author, on_delete=models.CASCADE) and some people write it like: author = models.ForeignKey('Author', on_delete=models.CASCADE) What is different between these? is there any special purpose of writing like this or they both are same? -
Creating a React-Django full stack web app. How to proceed?
I am building a webpage which uses django-rest-framework and react as a frontend. The main aim is to get some data from the frontend or react component, using rest api, then working on that data with python code to make a csv file of the data that i want to display on my next component of react. How should i proceed? I am a beginner in both django and react. Very confused how to take data from react form and then use it in django python code. Very confused how to use csv file in django and manipulate it. Please help. Suggest me some tutorials or something to go forward. -
Unable to use double braces to resolve variables
I am unable to use double braces to resolve variables. Here's my js code. var app = angular.module('toDo',[]); app.controller('toDoController', function($scope, $http) { $http.get('/todo/api/').then(function(response) { $scope.todoList = response.data; }); }); HTML code: <!DOCTYPE html> <html> <head> <meta charset="utf-8"> <title>To Do List</title> {% load static %} <link rel="stylesheet" href="{% static 'css/todo.css' %}"> </head> <body ng-app="toDo" ng-controller="toDoController"> <h1>Todo List</h1> <form ng-submit="add()"> <input type="text" ng-model="todoInput" placeholder="Add a new todo task..."> <button type="submit">Add Task</button> </form> <br> <div ng-repeat="todo in todoList"> <input type="checkbox" ng-model="todo.done"><a ng-href="/todo/api/{{todo.id}}" ng-bind="todo.task"></a> </div> <p> <button class="delete" ng-click="delete()">Delete</button> <button class="update" ng-click="update()">Update</button> </p> <script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.7.8/angular.js"></script> <script src="{% static 'js/todo.js' %}"></script> </body> </html> tasks which displayed in screen should redirect me to the url "/todo/api/". But values given in the braces not resolving it's ID. Currently the hyperlink redirecting always to the url "/todo/api/". Kindly let me know if I am doing anything wrong or help me to fix this issue. -
Google Re-captcha with Django 2 built-in LoginView
I'm working with a project using Python(3.7) and Django(2) in which I have to implement Google's Recaptcha. For authentication I'm using the built LoginView from Django,contrib.auth.views, How can I validate the captcha by utilising this auth view? Here's what I have tried so far: From urls.py: path('login/', LoginView.as_view(extra_context={'key': settings.RECAPTCHA_PUBLIC_KEY}), name='login'), From login.html: <form action="{% url 'login' %}" method="post" class="p-3"> {% csrf_token %} <div class="form-group"> <label for="recipient-name" class="col-form-label">Username</label> <input type="text" class="form-control" placeholder=" " name="username" id="recipient-name" required=""> </div> <div class="form-group"> <label for="password" class="col-form-label">Password</label> <input type="password" class="form-control" placeholder=" " name="password" id="password" required=""> </div> <div class="form-group"> <script src='https://www.google.com/recaptcha/api.js'></script> <div class="g-recaptcha" data-sitekey="{{ key }}"> {{ key }}</div> </div> <div class="right-w3l"> <input type="submit" class="form-control" value="Login"> </div> </form> -
Integrating Vue.js with Django
Vue.js has some modules that can help me to build my web app using Django. Is there any way to to integrate Vue.js with Django (Python)? -
how to print the context added template returned by the view
Just in curiosity to know , i want to get the printed html along with context that is returned by my view .(I want get it printed on server side only). eg def my_view(request): template='product/compare-in-box.html' context={"data": instance,} # print(render(request , template ,context)) the thing i was trying to print but not working as i expect. render(request , template,context) how this can be achieved? -
Django: Get page title from middleware
I have a small middleware I wrote to keep track of user activity: class AccessLogs(object): def __init__(self, get_response): self.get_response = get_response def __call__(self, request): response = self.get_response(request) if "/media/" not in request.path: # Add the user and page info into DB try: ActivityLog(user=request.user, pageURL=request.path).save() except Exception as e: print(e) return response Is there any way I can get the title of the page using this method of middleware? I have looked up a LOT of stuff here like templateview, custom response but nothing seems to be working. Is there any class or function that retrieves the visited page's title? Any help would be really appreciated. -
in django app even if migration folders files are deleted this error exists 'relation "blog_no_of_views" does not exist'
i was using sqlite in the beginning but now i tried switching to postgresql and tried executing makemigrations command, now i am getting below error (youngmindsenv) E:\young_minds\heroku\youngminds>python manage.py makemigrations Traceback (most recent call last): File "E:\young_minds\heroku\youngmindsenv\lib\site-packages\django\db\backends \utils.py", line 85, in _execute return self.cursor.execute(sql, params) psycopg2.errors.UndefinedTable: relation "blog_no_of_views" does not exist LINE 1: ..."views_count", "blog_no_of_views"."username" FROM "blog_no_o... ^ The above exception was the direct cause of the following exception: Traceback (most recent call last): File "manage.py", line 15, in <module> execute_from_command_line(sys.argv) File "E:\young_minds\heroku\youngmindsenv\lib\site-packages\django\core\manage ment\__init__.py", line 371, in execute_from_command_line utility.execute() File "E:\young_minds\heroku\youngmindsenv\lib\site-packages\django\core\manage ment\__init__.py", line 365, in execute self.fetch_command(subcommand).run_from_argv(self.argv) File "E:\young_minds\heroku\youngmindsenv\lib\site-packages\django\core as suggested in answers by others as i don't worry about losing the data, so i deleted the tables and database as well,i have deleted the migration folder files and created init.py inside it and tried makemigrations command but still i am getting the above error, i am so confused from where is it getting that error since there is no files in apps migrations folder it gives error in all of below commands as well ./manage.py clear_cache ./manage.py clean_pyc ./manage.py reset_schema ./manage.py reset_db please help me i am so troubled by this. Thanks in advance! -
Django Rest Framework, Registering viewset with router breaks everything - circular import, "Module" object is not iterable
Currently trying to configure my project to work with a router as I plan on using multiple viewsets, all the components seem to work individually, specifying the path manually produces no errors and works as intended. However once i attempt to register my viewset with the router it all explodes Have compared what I've done to the tutorial on the Django Rest Framework site and everything seems to be done correctly. Have broken it down to the smallest components I am able to comprehend and still not sure. My code: urls.py # endpoint templateResponder = TemplateViewSet.as_view({ 'get': 'gotget', 'post': 'gotpost', }) # define router and add viewsets router = DefaultRouter() router.register(r'template', views.TemplateViewSet) # THIS LINE IS BREAKING EVERYTHING urlpatterns = [ # path('template/', templateResponder, name='templateResponder'), # If i add the viewset manually it works path('', include(router.urls)), path('response', views.request_maker), path('json', views.response_maker), ] my viewset class TemplateViewSet(viewsets.ViewSet): """ The Template ViewSet """ # serializer = TestSerializer # currently not used # need to specify a queryset maybe? @action(detail=False, methods=['GET']) def gotget(self, request): return Response("A GET request has been received!!!", status=status.HTTP_200_OK) @action(detail=True, methods=['POST']) def gotpost(self, request): return Response("A POST request has been received!!!", status=status.HTTP_201_CREATED) I get these errors upon attempting to run. If … -
Django ORM - How to delete items with identical field if the datefield is bigger than in others dublicates?
So I have a Comments model and by querying comments = Comments.objects.values('students_id', 'created_at') I get this output <QuerySet [ {'students_id': 4, 'created_at': datetime.date(2019, 6, 19)}, {'students_id': 2, 'created_at': datetime.date(2019, 6, 3)}, {'students_id': 1, 'created_at': datetime.date(2019, 6, 24)}, {'students_id': 6, 'created_at': datetime.date(2019, 6, 4)}, {'students_id': 6, 'created_at': datetime.date(2019, 6, 19)}, {'students_id': 5, 'created_at': datetime.date(2019, 6, 5)}, {'students_id': 4, 'created_at': datetime.date(2019, 7, 28)}, {'students_id': 6, 'created_at': datetime.date(2019, 6, 11)}]> It's three comments by student with id=6 and two comments by student with id=4. What I need to get is only one latest comment from every student. In this example it'll look like this: <QuerySet [ {'students_id': 2, 'created_at': datetime.date(2019, 6, 3)}, {'students_id': 1, 'created_at': datetime.date(2019, 6, 24)}, {'students_id': 6, 'created_at': datetime.date(2019, 6, 19)}, {'students_id': 5, 'created_at': datetime.date(2019, 6, 5)}, {'students_id': 4, 'created_at': datetime.date(2019, 7, 28)},]> Thanks in advance for the answer! -
What pattern to use for invoking web service (SOAP) with complex parameters
I have to call a SOAP web service method with rather complex data (~40 attributes with some of them being of complex types). The transformation Django Model Data -> SOAP WS Data is not trivial. Currently, I use suds.client.Client for invoking the WS, and I'm already able to instantiate all WS data types using the Client.factory.create method. The question is about: what pattern to use? I would like to validate the data before handling it over to the WS, something like DTO (which some people classify as anti-pattern). I wouldn't like to put all the transformation logic into the view. I already have a little WS wrapper to be able to do any transformations / validations before invoking the WS method. Here are some alternatives: Direct: Make a the WS wrapper accept any required data, validate and transform it to suds WS data instances. Plain Old Python Object: Create a simple Python object, instance and populate it in the view and pass it to WS wrapper which should validate and transform it to WS data before sending it over. (Now we have a clear separation between any django form / instance data and the WS data, the passed object serves … -
How should I create a filter form while having Models with relationships and I want to include fields from other models
I am developing the backend of my web application. First I show the models: class School(Model): name = ... rank = ... class Program(Model): id = ... length = ... campus = ForeignKey(Campus) class Campus(Model): name = ... school = ForeignKey(School) city = ForeignKey(City) class City(Model): population = ... city = ... province = ForeignKey(Province) class Province(Model): province = ... country = ForeignKey(Country) class Country(Model) country = ... population = .... I have so many questions and problems here. What I want to do is to create a filter form to filter programs based on their country, city, province, campus, and school. My first question: There is a package named django-filters . Do you recommend using this? is it trustable? Is it better to use this package or build a form and send the form and get them and build the query-set, with which I will show the filtered programs in a template? My second Question: If I want to have a form using built-in Django ModelForm and I want to include city, province, country, campus name, and even city population in my form, how should I do this? Suppose I want to show programs that are in a country … -
Django: Count of ManyToMany field in PositiveIntegerField during save() in a models.py
I want to alter the count of a ManyToMany Field during save of my model. For which I modified the save(). If I run save(), count will not be updated. If I run save second time without updating the field it will update the count. class UserProfile(models.Model): follower = models.ManyToManyField('self', related_name='Followers', blank=True, symmetrical=False) following = models.ManyToManyField('self', related_name='Followings', blank=True, symmetrical=False) follower_count = models.PositiveIntegerField(null=True, blank=True, editable=False) following_count = models.PositiveIntegerField(null=True, blank=True, editable=False) class Meta: verbose_name = 'User Profile' verbose_name_plural = 'User Profiles' def __str__(self): return self.follower_count def save(self, *args, **kwargs): super(UserProfile, self).save(*args, **kwargs) self.following_count = self.following.all().count() self.follower_count = self.follower.all().count() super(UserProfile, self).save(*args, **kwargs) I want to update count with single save(). -
Django edit view does not show
I am new to Django. My app allows a user to create a project by providing a title and a body content, delete it and update it. Now, I am creating and edit/update view for my app but it is not showing up in my html page. urls.py from django.urls import path, include from . import views urlpatterns = [ path('allprojects', views.allprojects, name='allprojects'), path('createproject', views.createproject, name='createproject'), path('<int:project_id>', views.projectdetail, name='projectdetail'), path('<int:project_id>/editproject', views.editproject, name='editproject'), ] projects/views.py @login_required def editproject(request, project_id): if request.method == 'POST': if request.POST['title'] and request.POST['content']: project = get_object_or_404(Project, pk=project_id) project.title = request.POST['title'] project.content = request.POST['content'] project.developer = request.user project.save() return redirect('/projects/' + str(project.id)) else: return render(request, 'projects/' + str(project.id) + 'editproject.html', {'error':'All fields are required.'}) else: return render(request, 'projects/allprojects.html') projects/templates/projects/editproject.html {% extends 'base.html' %} {% block title %}Edit Project{% endblock %} {% block content %} <div class="container"> <div class="row"> <div class="mt-4 offset-md-3 col-md-6"> <h2>Create a new project</h2> <form method="put"> {% csrf_token %} <div class="form-group"> <label for="exampleFormControlTextarea1">Title of the project</label> <textarea class="form-control" id="exampleFormControlTextarea1" rows="1" name="title"></textarea> </div> <div class="form-group"> <label for="exampleFormControlTextarea1">Brief description of this project</label> <textarea class="form-control" id="exampleFormControlTextarea1" rows="5" name="content"></textarea> </div> <button type="submit" class="btn btn-primary">Submit</button> </form> </div> </div> </div> {% endblock %} PROBLEM When I go to a urls such as … -
Can I dynamically set field names in Django orm query?
Can I dynamically set field names in Django view? I want this code CategoryNick.objects.get(author=self.request.user).get(field=slug) but error is occured AttributeError: 'CategoryNick' object has no attribute 'get' Is there a good way to solve this problem? if you know solution thank you for let me know total code def get_context_data(self, *, object_list=None, **kwargs): context = super(type(self), self).get_context_data(**kwargs) context['posts_without_category'] = MyShortCut.objects.filter(category=None,author=self.request.user).count() context['category_list'] = Category.objects.all() slug = self.kwargs['slug'] if slug == '_none': context['category'] = 'no_category' else: category = Category.objects.get(slug=slug) context['category'] = category context['category_nick'] = CategoryNick.objects.get(author=self.request.user).get(field=slug) return context -
Django apache2 authentication with remote_user and local db
i' ve a Django application with the following parameters: Debian: 9.9 Apache2: 2.4.25-3+deb9u7 Django: 2.2.1 Mysql: mariadb-server-10.1 . For the authentication i' d like to use remote authentication but through the local database. Is there any authentication class for it? My goal is to have the apache2 pop- up for authentication, but the authentication data should not come - for instance - from ldap, but from the local database, and the REMOTE_USER variable should be also set. My current apache conf file looks like this now: <VirtualHost *:80> ServerName 127.0.0.25 ServerAlias infokom.localhost prj.256.hu prj.128.hu DocumentRoot /usr/share/prj <Directory /usr/share/prj> Order allow,deny Allow from all </Directory> WSGIDaemonProcess prj.djangoserver user=prj processes=10 threads=20 display-name=%{GROUP} python-path=/usr/share/prj:/home/prj/.virtualenvs/prj/lib/python3.5/site-packages WSGIProcessGroup prj.djangoserver WSGIScriptAlias / /usr/share/prj/prj/wsgi.py CustomLog ${APACHE_LOG_DIR}/prj-access.log combined ErrorLog ${APACHE_LOG_DIR}/prj-error.log LogLevel debug </VirtualHost> . The wsgi.py file is simply: import os from django.core.wsgi import get_wsgi_application os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'cworld.settings') application = get_wsgi_application() . The related settings.py parts: MIDDLEWARE = [ 'django.middleware.security.SecurityMiddleware', 'django.contrib.sessions.middleware.SessionMiddleware', 'django.middleware.common.CommonMiddleware', 'django.middleware.csrf.CsrfViewMiddleware', 'django.contrib.auth.middleware.AuthenticationMiddleware', 'django.contrib.auth.middleware.RemoteUserMiddleware', 'django.contrib.messages.middleware.MessageMiddleware', 'django.middleware.clickjacking.XFrameOptionsMiddleware', ] ... AUTHENTICATION_BACKENDS = ['django.contrib.auth.backends.RemoteUserBackend'] . With this current setup when log is required, it redirects me to the login page (e. g.: /accounts/login/?next=...), but i rather would like to have here the apache2 popup for authentication. -
Specify PORT in Django Dockerfile using Cloudrun
I have a basic Django 2 app (the starterproject) running locally in a Docker container. This works fine and i can access site. I would like to deploy the container using Google Cloudrun service and I see in their documentation it's required to specify the PORT environment variable. I have tried many differnet configurations but I just cannot make it work. I always get the error: Cloud Run error: Container failed to start. Failed to start and then listen on the port defined by the PORT environment variable. Logs for this revision might contain more information. The logs have no information. My base Docker file is: FROM python:3.7-alpine ENV PYTHONBUFFERED 1 COPY ./requirements.txt ./requirements.txt RUN pip install -r ./requirements.txt RUN mkdir /app WORKDIR /app COPY ./app /app RUN adduser -D user RUN chown -R user:user /app RUN chmod 755 /app USER user and my docker-compose file is: version: "3" services: app: build: context: . ports: - "$PORT:8000" volumes: - ./app:/app command: sh -c "python manage.py runserver 0.0.0.0:8000" The troubleshooting is here: https://cloud.google.com/run/docs/troubleshooting Where and how do i use the PORT environment variable correctly? All help appreciated, Jon -
How to redirect any url to "404.html" in Django
I have such problem that, I can't redirect my application to "404.html" when user enters wrong url. I know, it is required to set DEBUG=False and ALLOWED_HOSTS=['*'], but still I am getting "Server Error 500", or css is missing. -
Django: Filter Queryset dynamically on template action
I want to filter a queryset dynamically on some template action. e.g. a Dropdown for the School Year so i only display the results for the chosen year. Where do i need to define this behaviour, directly in the view or filter it in the template? I already tried to filter in the view but im struggling to get the correct entries from my Course Mode. I dont know how I am able to get the Year Information from my Course from my already filtered CourseGrade Queryset. A simple course_info = Course.objects.filter(id=student_grades.course.pk) is not possible as i would do it in the template. class Course(models.Model): import datetime YEAR_CHOICES = [] for r in range(2000, (datetime.datetime.now().year+2)): YEAR_CHOICES.append((r,r)) name = models.CharField(choices=course_names, max_length=32) teacher = models.ForeignKey(Teacher, on_delete=models.SET_NULL, null=True, blank=True) school_year = models.IntegerField(choices=YEAR_CHOICES, default=datetime.datetime.now().year) half_year = models.IntegerField(choices=course_halfyear, default=1) g def __str__(self): return self.name class CourseGrade(models.Model): student = models.ForeignKey(Student, on_delete=models.CASCADE) course = models.ForeignKey(Course, on_delete=models.CASCADE) grade = models.DecimalField(validators=[MinValueValidator(1), MaxValueValidator(6)], null=True, blank=True, decimal_places=1, max_digits=2) course_type = models.CharField(choices=course_types, max_length=1, null=True, blank=True) class Meta: unique_together = ["student", "course"] def __str__(self): return '{0}: {1}'.format(self.student, self.course.name) def student_grade(request): current_student = get_object_or_404(Student, user=request.user) student_class = School_Class.objects.filter(student=current_student) student_grades = CourseGrade.objects.filter(student=current_student).order_by('course') context={'current_student': current_student, 'student_grades': student_grades, 'student_class': student_class} return render( request, 'bgrade/student/student_grade.html', context) The expected … -
how to fix django.db.utils.ProgrammingError: relation "blog_no_of_views" does not exist
i am new to django , i was using sqlite for development and now when i switched to postgresql, i am getting below error i have tried to see all the answers on stackoverflow and every other sites but it didn't help for me. i have already tried to delete migration folder and run makemigrations and migrate it is still giving me the error on makemigrations itself.try to run python manage.py migrate --run-syncdb it gives error on this command as well (youngmindsenv) E:\young_minds\heroku\youngminds>python manage.py makemigrations Traceback (most recent call last): File "E:\young_minds\heroku\youngmindsenv\lib\site-packages\django\db\backends \utils.py", line 85, in _execute return self.cursor.execute(sql, params) psycopg2.errors.UndefinedTable: relation "blog_no_of_views" does not exist LINE 1: ..."views_count", "blog_no_of_views"."username" FROM "blog_no_o... ^ The above exception was the direct cause of the following exception: Traceback (most recent call last): File "manage.py", line 15, in <module> execute_from_command_line(sys.argv) File "E:\young_minds\heroku\youngmindsenv\lib\site-packages\django\core\manage ment\__init__.py", line 371, in execute_from_command_line utility.execute() File "E:\young_minds\heroku\youngmindsenv\lib\site-packages\django\core\manage ment\__init__.py", line 365, in execute self.fetch_command(subcommand).run_from_argv(self.argv) File "E:\young_minds\heroku\youngmindsenv\lib\site-packages\django\core\manage ment\base.py", line 288, in run_from_argv settings.py import os BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__))) SECRET_KEY = 'e-mc3z=m#6_w#lzy$eb%qik9fcdlqmzsfsdf9=5s(we74^)25q_ge5' DEBUG = True ALLOWED_HOSTS = ['youngminds.herokuapp.com',"localhost"] # Application definition INSTALLED_APPS = [ 'users.apps.UsersConfig', 'blog.apps.BlogConfig', 'crispy_forms', 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'storages', 'django.contrib.humanize', 'ckeditor', 'ckeditor_uploader', 'social_django', #'sslserver' ] CKEDITOR_UPLOAD_PATH = 'uploads/' CKEDITOR_CONFIGS … -
Two URLs in django form tag using java script or ajax to process
would it be possible to include two data-url links in django form tag and proccess it either by java script or ajax to populate two different dependent drop down boxs? if it is possible what is the best way to implement it! thanks $("#province").change(function () { var url = $("#MyForm").attr("data-cities-url"); // get the url of the load_cities view var provinceId = $(this).val(); // get the selected country ID from the HTML input $.ajax({ // initialize an AJAX request url: url, // set the url of the request (= localhost:8000/includes/load-cities/) data: { 'province': provinceId // add the country id to the GET parameters }, success: function(data) { // `data` is the return of the `load_cities` view function $("#city").html(data); // replace the contents of the city input with the data that came from the server } }); }); the result would be by loading the form user can choose a province and based on that the city fileds load the relevent cities and also user can choose a category and based on that subcategory field will populate relevent subcategories related to choosen category. -
Recommendations to build location based search in django
I am working on a project of house selling webapp in django. Now what I want is that user searches using address or city he wants house in and my search results should show houses nearby that location present in my database. What should I use to implement this ? I am using postgres database.