Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
When does the SQL execute in Django ORM
to begin with ,I give a example. # Student is a model class, and it has attributes: name, age, gender and so on. temp_students = Student.objects.filter(age=18) students = temp_students.filter(gender='girl') if i debug those code, i can get a SQL which may be "SELECT * FROM student WHERE age = 18"(called SQL-A).Then, when I reach the second line, I may get another SQL which is "SELECT * FROM student WHERE gender = 'girl' IN (SELECT * FROM student WHERE age = 18)"(called SQL-B). So, my QUESTION is when does the SQL-A and SQL-B execute? DOES it connect to database twice, and get two result set? In this case, is there any unnecessary spending for database? If not this, Why can I get the SQL looks like in DEBUG MODE? It will be great if there is any doc or article related Django ORM in the end of your answer. THANKS! -
Jquery/ajax and django
I'm trying to send data from my form and a jstree plugin to my view, the problem is if I print request.POST it shows 2 querydict and I tried to get the dict that I send with jquery with areas = request.POST.get('area') and it is ok but when I try to use the variable inside the form.is_valid it shows me None, this is making me tear my hair off I don't know what to do to make it work. any advice to help me this is my view def projectcreate(request): researcher = Researcher.objects.get(user_id=request.user.id) if request.method == 'POST': form = ProjectForm(researcher, request.POST or None, request.FILES or None) if 'area' in request.POST: areas = request.POST.get('area') if form.is_valid(): project = Project() project.with_ict = form.cleaned_data['with_ict'] project.with_company = form.cleaned_data['with_company'] project.for_company = form.cleaned_data['for_company'] project.predominant_area = form.cleaned_data[''] project.title = form.cleaned_data['title'] project.ubc = form.cleaned_data['ubc'] project.conclusion_date = form.cleaned_data['conclusion_date'] project.category = form.cleaned_data['category'] project.has_patent = form.cleaned_data['has_patent'] project.tech_transf = form.cleaned_data['tech_transf'] project.tech_transf_date = form.cleaned_data['tech_transf_date'] project.stage = form.cleaned_data['stage'] project.result = form.cleaned_data['result'] project.save() project.researcher.add(researcher) project.application_area.add(areas) company_form = CompanyForm(request.POST or None, prefix='company') if company_form.is_valid(): company = Company() company.name = company_form.cleaned_data['name'] company.cnpj = company_form.cleaned_data['cnpj'] company.email = company_form.cleaned_data['email'] company.save() return HttpResponseRedirect(reverse('project_list')) else: form = ProjectForm(researcher) company_form = CompanyForm(prefix='company') context = { 'form':form, 'company_form':company_form } return render(request, 'researcher/project/project_form.html', context) … -
BOOTSTRAP Sign in template not working on FORM
My login page isn't looking like the way I want it to which is like this bootstrap signin page right here https://getbootstrap.com/docs/4.0/examples/sign-in/. This is what it looks like right now If you can help me out with this, it would mean the world to me. Also if you think it's because I didn't link to a CSS page here's what my base template looks like and my structure: {% load staticfiles %} <!DOCTYPE html> <html> <head> <meta charset="utf-8"> <meta http-equiv="X-UA-Compatible" content="IE=edge"> <meta name="viewport" content="width=device-width, initial-scale=1"> <title>Accounts</title> <script src="https://code.jquery.com/jquery-3.3.1.min.js"></script> <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css"> <script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js"></script> <link rel="stylesheet" type="text/css" href="{% static 'accounts/signin.css' %}" /> </head> <body> <div class="jumbotron"> <div class="container"> {% block main_content %} {% endblock %} </div> </div> </body> </html> views.py from django.contrib.auth import ( authenticate, get_user_model, login, logout, ) from django.shortcuts import render from django.http import HttpResponse,HttpResponseRedirect from .forms import UserLoginForm # Create your views here. def login_view(request): title = "Login" form = UserLoginForm(request.POST or None) if form.is_valid(): username = form.cleaned_data.get("username") password = form.cleaned_data.get('password') user = authenticate(request, username=username, password=password) if user is not None: login(request, user) # or any other success page # return HttpResponse("Logged in") return HttpResponseRedirect('accounts/home') return render(request, "accounts/form.html", {"form":form, "title": title}) forms.py from django import forms from django.contrib.auth … -
Airbrake notifications disabled in Django tests?
I've configured a Django app called lucy_web to log errors to Airbrake using pybrake. In a module in the lucy_web hierarchy, lucy_web.lib.session_recommendations, I've defined a testing function: import logging logger = logging.getLogger(__name__) def log_something(): logger.error("Logging something...") If I call this function from the Django shell, like so: (venv) Kurts-MacBook-Pro-2:lucy-web kurtpeek$ python manage.py shell Python 3.6.4 (v3.6.4:d48ecebad5, Dec 18 2017, 21:07:28) Type 'copyright', 'credits' or 'license' for more information IPython 6.3.1 -- An enhanced Interactive Python. Type '?' for help. In [1]: from lucy_web.lib.session_recommendation import * In [2]: log_something() I see an error email appear: However, if I define a test, and try to call it from there, I don't see any new instances of the error appear: from django.test import TestCase from django.core import mail class SessionRecommendationTestCase(TestCase): def test_airbrake_notification_if_session_type_does_not_exist(self): from lucy_web.lib.session_recommendation import log_something log_something() import ipdb; ipdb.set_trace() Running this did not cause any new instances of the error appear in the Airbrake dashboard. Also, mail.outbox is empty: (venv) Kurts-MacBook-Pro-2:lucy-web kurtpeek$ python manage.py test lucy_web.tests.test_session_recommendation.SessionRecommendationTestCase.test_airbrake_notification_if_session_type_does_not_exist Creating test database for alias 'default'... System check identified no issues (0 silenced). --Return-- None > /Users/kurtpeek/Documents/Dev/lucy2/lucy-web/lucy_web/tests/test_session_recommendation.py(377)test_airbrake_notification_if_session_type_does_not_exist() 375 from lucy_web.lib.session_recommendation import log_something 376 log_something() --> 377 import ipdb; ipdb.set_trace() ipdb> mail.outbox [] As I understand from … -
where is the working directory for django rest framework myapp.api.views?
I'm using a package called Telethon, a Telegram client wrapper. It creates and stores session data in session_name.session files after an initial login with client.start() and entering a phone number and confirmation code so I won't have to login with my phone and a confirmation code everytime I need to use the client. My api (djando rest framework) uses Telethon. Usually, when I fire up python console in the directory that contains session_name.session and do client = TelegramClient('session_name',api_id,api_hash) client.start() It recognizes the session_name.session file and I don't need to log in. In my case, api.views.my_func does the function above but it does not recognize the session_name.session file in the directory api as it is supposed to I'm basically asking: where am I supposed to put the session_name.session file for my myapp/api/views.py function to recognize it and use it so I won't have to log in (I can't from myapp.api.views; it requires input) -
What is a good practice to distribute a Django app to different customers
I've developed a Django v11.1 application (it uses a MariaDB database). Now, there are different customers interested on installing this application on their own sites. I'm looking for information on how to properly deploy the application to the different sites. My main concern is that I built the models and the database on my own site (logically), but not sure what's the proper way of recreating the database on the customer sites. Do I give each customer a custom copy of settings.py? Do the customers have to run manage.py migrations on their site, in order to create the database? I'd like to share some initial data so that customers don't have to enter data manually. Does Django have a tool that creates a fixtures file from my existing database? In future releases, if I made changes to my database, how would they get propagates to the customer sites? Is it just matter of sharing the migrations files, and having them playing the same on their sites? Thanks! -
NoReverseMatch: Reverse for 'INSERT URL NAME' not found
I am learning about Django forms and am struggling to render a basic 'results' page for the form. I would be greatly appreciative if somebody could point out what I'm doing wrong! Thanks in advance :) ERROR NoReverseMatch at /search_query/ Reverse for 'results' not found. 'results' is not a valid view function or pattern name. Request Method: POST Request URL: http://ozxlitwi.apps.lair.io/search_query/ Django Version: 2.0 Exception Type: NoReverseMatch Exception Value: Reverse for 'results' not found. 'results' is not a valid view function or pattern name. Exception Location: /mnt/data/.python-3.6/lib/python3.6/site-packages/django/urls/resolvers.py in _reverse_with_prefix, line 632 Python Executable: /mnt/data/.python-3.6/bin/python Python Version: 3.6.5 Python Path: ['/mnt/project', '/mnt/data/.python-3.6/lib/python36.zip', '/mnt/data/.python-3.6/lib/python3.6', '/mnt/data/.python-3.6/lib/python3.6/lib-dynload', '/usr/local/lib/python3.6', '/mnt/data/.python-3.6/lib/python3.6/site-packages'] Server time: Fri, 1 Jun 2018 10:00:20 +0900 views.py def search_query(request): # If POST request, process the Form data: if request.method == 'POST': # Create a form instance and populate it with the data from the request (binding): form = SearchQueryForm(request.POST) # Check if the form is valid: if form.is_valid(): form.save() return HttpResponseRedirect(reverse('results')) else: form = SearchQueryForm() context = {'form':form} return render (request, 'mapping_twitter/search_query.html', context) def results(request): context = {'form':form} return render(request, 'mapping_twitter/results.html', context) mapping_twitter/urls.py from django.urls import path from . import views app_name = 'mapping_twitter' urlpatterns = [ path('', views.search_query, name='search-query'), path('results/', views.results, name='results'), … -
Django + MySQL 'datetime.datetime' object has no attribute 'split'
I tried to login admin page, but this error was showed... Connect MySQL and Django Using Engine mysql.connector.django. (Othere Engine can not connect mysql :( i tried..) Migrate was success. AttributeError at /admin/login/ 'datetime.datetime' object has no attribute 'split' Request Method: POST Request URL: http://localhost:8000/admin/login/?next=/admin/ Django Version: 2.0.5 Exception Type: AttributeError Exception Value: 'datetime.datetime' object has no attribute 'split' My pip freeze is here. certifi==2018.4.16 Django==2.0.5 mysql-connector-python==8.0.11 mysqlclient==1.3.12 pipenv==2018.5.18 psycopg2-binary==2.7.4 PyMySQL==0.8.1 pytz==2018.4 virtualenv==16.0.0 virtualenv-clone==0.3.0 whitenoise==3.3.1 I guess that MySQL is not support the latest django version, is it? All traceback is here!! Environment: Request Method: POST Request URL: http://localhost:8000/admin/login/?next=/admin/ Django Version: 2.0.5 Python Version: 3.6.5 Installed Applications: ['django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'picker_main'] Installed 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.messages.middleware.MessageMiddleware', 'django.middleware.clickjacking.XFrameOptionsMiddleware'] Traceback: File "C:\Users\XSHA\AppData\Local\Programs\Python\Python36\lib\site-packages\django\core\handlers\exception.py" in inner 35. response = get_response(request) File "C:\Users\XSHA\AppData\Local\Programs\Python\Python36\lib\site-packages\django\core\handlers\base.py" in _get_response 128. response = self.process_exception_by_middleware(e, request) File "C:\Users\XSHA\AppData\Local\Programs\Python\Python36\lib\site-packages\django\core\handlers\base.py" in _get_response 126. response = wrapped_callback(request, *callback_args, **callback_kwargs) File "C:\Users\XSHA\AppData\Local\Programs\Python\Python36\lib\site-packages\django\views\decorators\cache.py" in _wrapped_view_func 44. response = view_func(request, *args, **kwargs) File "C:\Users\XSHA\AppData\Local\Programs\Python\Python36\lib\site-packages\django\contrib\admin\sites.py" in login 398. return LoginView.as_view(**defaults)(request) File "C:\Users\XSHA\AppData\Local\Programs\Python\Python36\lib\site-packages\django\views\generic\base.py" in view 69. return self.dispatch(request, *args, **kwargs) File "C:\Users\XSHA\AppData\Local\Programs\Python\Python36\lib\site-packages\django\utils\decorators.py" in _wrapper 62. return bound_func(*args, **kwargs) File "C:\Users\XSHA\AppData\Local\Programs\Python\Python36\lib\site-packages\django\views\decorators\debug.py" in sensitive_post_parameters_wrapper 76. return view(request, *args, **kwargs) File "C:\Users\XSHA\AppData\Local\Programs\Python\Python36\lib\site-packages\django\utils\decorators.py" in bound_func 58. return … -
Django Message format error on Reverse Redirect
I am getting a formatting error with messages when I use a redirect like the one below. msg = 'Guest Users are not Authorized.' messages.warning ( request, msg ) return redirect ( reverse ( 'page:index', kwargs = { 'slug': slug } ) ) Messages are fine with the below example when I just do a return render(). msg = '{} has been Updated.'.format ( a.abrev ) messages.success ( request, msg ) return render ( request, template, context ) Is there something about redirects and messages? I am using Django 2.0, Cookiecutter and Foundation. Thank you. -
How to serving a django with Apache and Cherrypy
I have a problem and would like a help! I have a django application, which is on an apache server. It was running normally until you upgraded to django 2.0.5. The application is served with cherrypy and apache. Where apache does the reverse proxy role. When I type the address, it removes the targeting created by apache. For example: The domain is "www.example.com" and the application is located at "www.example.com/app". When entering the address of the application in the browser, it redirects to the login page, but removing "/app/", thus making "www.example.com/security/enter", when it should be "www.example.com/app/security/enter". If I manually put the "/app/" system works normally, server the static files and everything else, but when requesting a new page, it always removes the "/app/", forcing it to manually put to work. Below is the template I used to get the application up and running: File app.conf in /etc/httpd/conf.d/: <VirtualHost *:*> ServerName example.com ProxyPreserveHost On ProxyPass /app/ http://example.com:8000/ ProxyPassReverse /app/ http://example.com:8000/ </VirtualHost> File cps.py (cherrypy script): #!/opt/app/env/bin python # -*- coding: utf-8 -*- import os os.environ["DJANGO_SETTINGS_MODULE"] = "app.settings" import cherrypy import django django.setup() from django.conf import settings from django.core.handlers.wsgi import WSGIHandler class DjangoApplication(object): HOST = "0.0.0.0" PORT = 8000 def mount_static(self, … -
Is custom Django user model with only one field possible?
I need a custom user model in Django with only one field to authenticate. Because the users of my website will not have an email or password. They will be logged in with only one string (like token generated immediately). If the string matches with the another string/token defined by my system, the user should be logged in. How could it be possible? Thanks -
Any hosting site relevant to host Django App?
I am currently using PythonAnywhere to host a Django app, however, the PythonAnywhere server is too slow that it takes quite more time compared to other sites sending responses. It also takes lot of time uploading images. (It's slow though I am paying for the account.) Is there any other sites that Django apps can be hosted? It is better if I can set static files' path easily, download files (including script files) on the server, and so on. It's better if the functions and UI are similar to PythonAnywhere, since I'm used to it. -
DSL class does not exist in query
I am using elasticsearch_dsl library in my Django project. And I run into the following error while using the Q object: DSL class `(AND: term, ('org', 'abc'))` does not exist in query. I tried several approaches but everything seems to fail. Is it a bug, or there is something wrong with my code? CODE: client = Elasticsearch() s = Search(using=client) my_query = Q("term", org='abc') s = s.query(my_query) MAPPING: enter code here { "device" : { "mappings" : { "doc" : { "properties" : { "created_by" : { "type" : "text" }, "created_on" : { "type" : "date" }, "label" : { "type" : "text" }, "org" : { "type" : "keyword" } } } } } -
What's the SIMPLEST way to make a DJANGO Registration page?
I'm relatively new to Django but have spent countless hours this past week learning how to make webapps. I've bounced around from numerous tutorials promising to make a user registration, but they have all led my pages to crash and turn completely blank and white. I'm now starting over once again, but this time I made an app COMPELETY devoted to user login/logout/registration. I have finally got my login to work, but that doesn't serve me any good since I don't have any user accounts. I'm now just asking for a really simple way for me to make a user registration page to which it allows users to make an account in order to view the homepage and be able to edit stuff on it. I have seen multiple tutorials and documentations, and really am hoping that someone can give me a straight answer to this. However if it's necessary I'm willing to look at a youtube tutorial (even though it lead me to have trust issues) and if it's really necessary I can look at a documentation. Thanks in advance. If it helps, this is what my code looks like so far: (it's also worth mentioning that I'm using … -
how to return the object number of a model?
please I would like to know the instruction that allows me to return the object number of a model for the deviser after, for example: devise the time attribute of the model exam on the attribute number of teacher supervising, if you have instructions or documentation, I'm all ears -
Fetch and display Data from Django Rest Api
after followed many tutorials about how to integrate Django rest in React i successed to fetch data from my api like this , but the header of my table repeat himself by the numbers of objects i fetch from my data , i have 3 products in my data so that is make the table 3 times . When i try to move the {this.state.todos.map(item => ( just before my i get an error because that "break" my tag , so i can put {this.state.todos.map(item => ( just before my or just after , someone can help me plz ? i just want to repeat the for each item but not all the table , thanks you for help Render of my table in the local server import React, { Component } from 'react'; class Products extends Component { state = { todos: [] }; async componentDidMount() { try { const res = await fetch('http://127.0.0.1:8000/api/'); const todos = await res.json(); this.setState({ todos }); } catch (e) { console.log(e); } } render() { return ( <div> {this.state.todos.map(item => ( <table class="table table-bordered table-hover table-striped"> <thead> <tr class="bg-gray text-white"> <th>Id</th> <th>Category</th> <th>Name</th> <th>Short Description</th> <th>Price</th> <th class="text-center">Image</th> <th>Delete</th> </tr> </thead> <tbody> <tr> … -
Proper declaration of an empty Django PostgreSQL JSONField default value in migration file
I'm a little lost interpreting Django's explanation of applying a default value to a PostgreSQL JSONField: If you give the field a default, ensure it’s a callable such as dict (for an empty default) or a callable that returns a dict (such as a function). Incorrectly using default={} creates a mutable default that is shared between all instances of JSONField. So in my model file I've declared the default as such foo = JSONField(default=dict()) however when I generate the migration operation for the new field this is the result migrations.AddField( model_name='bar', name='foo', field=django.contrib.postgres.fields.jsonb.JSONField(default={})) I'm just not sure whether or not this result is in accordance with the documentation's suggestion. Is this valid, or should I modify the generated default to call dict()? -
Google App Engine logs a mess of New connection for ... and Client closed local connection on
Checking out my logs on my App Engine. I get A LOT of New connection for "<project_id>-central1:<project_name>" Client closed local connection on /cloudsql/<project_id>-central1:<project_name>/.s.PGSQL.5432 Like happening multiple times a second and just floods my logs. I was unable to find any information relating to this and maybe this is just a non-issue. Is there any way to prevent this? (excluding filtering) Is this inadvertently driving up the cost of operation of opening and closing? I am using Django on the app engine. -
display paragraph django form widget
I am new to django I have a Author admin form which contains Inlines of several related forms While Editing any author form i want to display a readonly element of associated books with it in a inline like way. I cant find a way to fetch all the related objects and show a markup object. (Book have a many to many relation ship with author) Instead i have used a Multi model choice field class AuthorForm(FormCleanMixin): assoc_books = forms.ModelMultipleChoiceField(queryset=Books.objects.none(),required=False) class AuthorAdmin(): def get_form(self, request, obj=None, **kwargs): if obj is not None: form.base_fields['assoc_books'].queryset = Books.objects.filter(authors=obj.id) else: form.base_fields.pop('assoc_books') i am getting the output in a select box. Is there a way to convert it into a paragraph where i can also insert some HTML to it.I want to list each book to its own url. /admin/book//change I have tried this but the anchor tag doesnt display class listRelatedItemsField(forms.ModelMultipleChoiceField): def label_from_instance(self, obj): html = '''<a target='_blank' href='admin/book/%(id)s/change'>%(name)s</a>''' % {'id':obj.id,'name':obj.name} return mark_safe(html) Can i create a custom widget for this. Please help -
Heroku's Django is not loading lity.css and lity.js
I am trying to use this simple lightbox for embedding a video on my Django project. Locally with: python3 manage.py runserver it runs fine. However, once deployed to Heroku the app struggles to find the css and the js of lity, though it is located in the correct folder. Has anyone run into a similar problem? The project is live here: https://dry-depths-69493.herokuapp.com/ And the git-repo is here: https://github.com/Datenrausch/heroku -
how to list all the files of a custom directory
i want to let the user choose a courseName from a list and render all the files under this directory, how can i achieve that using here is what i've done so far: views.py def showDocuments(request): # how can i get the directory from the html page and break down the link # in order to get all the files of the certain directory documents = Document.objects.all() context = { "documents" : documents , } return render(request , 'dashboard.html' , context ) models.py class Document(models.Model): #to do : enum class ! DB = "data structure" SF = "software enginering" DS = "discrete structure " WD = "web dev" OPTIONS = "options" courseChoices = ( (DB , "data structure"), (SF , "software enginering "), (DS , "discrete structure"), (WD , "web dev"), (OPTIONS , "options"), ) courses = models.CharField(max_length=50, choices=courseChoices, default=OPTIONS) def content_file_name(self, courses): file_path = "documents/{courses}/{filename}".format(courses = self.courses ,filename = courses ) return file_path description = models.TextField(help_text="A little description can be very helpful for others!") document = models.FileField(upload_to=content_file_name) uploaded_at = models.DateTimeField(auto_now_add=True) def __str__(self): return "{}".format(self.document) thanks in advanced -
Can't drop into Python debugger in a function called asynchronously?
In order to debug an Airbrake issue described in Airbrake throwing error "pybrake - ERROR - strconv.ParseInt: parsing "None": invalid syntax", I'm trying to inspect requests prior to sending them to Airbrake by dropping into the iPython debugger using import ipdb; ipdb.set_trace(). To inspect the request, I've set a trace in the send_notic_sync() method of the Notifier (see https://github.com/airbrake/pybrake/blob/master/pybrake/notifier.py): def send_notice_sync(self, notice): """Sends notice to Airbrake. It returns notice with 2 possible new keys: - {'id' => str} - notice id on success. - {'error' => str|Exception} - error on failure. """ for fn in self._filters: r = fn(notice) if r is None: notice['error'] = 'notice is filtered out' return notice notice = r if time.time() < self._rate_limit_reset: notice['error'] = _ERR_IP_RATE_LIMITED return notice data = jsonify_notice(notice) req = urllib.request.Request(self._airbrake_url, data=data, headers=self._airbrake_headers) try: import ipdb; ipdb.set_trace() resp = urllib.request.urlopen(req, timeout=5) except urllib.error.HTTPError as err: resp = err except Exception as err: # pylint: disable=broad-except notice['error'] = err logger.error(notice['error']) return notice This method gets submitted to a ThreadPoolExecutor in pybrake's source code. The problem is, when I try to import a script which calls this function, I am unable to drop into the debugger. Here is what I see when I try: … -
Have dropdown menu on admin page in Django
I am new to Django. In models.py I have 2 tables Project and Employee with ManyToMany relationship In admin.py I register Project and Employee tables, when adding new project record to Project table (which has employees belong to that specific project) I want to have dropdown list on admin page to let user choose existing projects from database. Thanks for all the helps!! -
How can I show error messages in change_password in Django
I'm struggling to show error message in change_password in Django. I tried all the ways I know to show errors in the template file, but nothing shows up when I put some wrong information on purpose. I thought it's because of redirecting when the form is not valid. But, the changing password feature doesn't work without the redirecting. Can anyone suggest a way to do that? views.py def change_password(request): if request.method == 'POST': form = PasswordChangeForm(data=request.POST, user=request.user) if form.is_valid(): form.save() update_session_auth_hash(request, form.user) return redirect('/accounts/profile') else: return redirect('/accounts/change-password') else: form = PasswordChangeForm(user=request.user) args = {'form': form} return render(request, 'accounts/change_password.html', args) HTML template <form method="POST"> {% csrf_token %} <p class="error-message"> {{ form.errors.old_password }} {{ form.errors.new_password1 }} {{ form.errors.new_password2 }} {{ form.non_field_errors }} {% if form.non_field_errors %} {% for error in form.non_field_errors %} {{ error }} {% endfor %} {% endif %} </p> <div class="form-group row"> <label for="inputPassword" class="col-sm-3 col-form-label">Old Password</label> <div class="col-sm-9"> <input type="password" class="form-control" name="old_password" placeholder="Old Password" required autofocus> </div> </div> <div class="form-group row"> <label for="inputPassword" class="col-sm-3 col-form-label">New Password</label> <div class="col-sm-9"> <input type="password" class="form-control" name="new_password1" placeholder="New Password" required> </div> </div> <div class="form-group row"> <label for="inputPassword" class="col-sm-3 col-form-label">Confirm New Password</label> <div class="col-sm-9"> <input type="password" class="form-control" name="new_password2" id="inputPassword" placeholder="Confirm New Password" required> </div> … -
How to pass data through an AJAX request in django?
I want to retrieve data from the database when the bottom of the page is hit. Now, what I have so far: urls.py urlpatterns = [ url(r'^$', feedViews.index, name='index'), url(r'^load/$', feedViews.load, name='load'), ] views.py def index(request): if request.method == 'GET': context = { 'entry_list': Entry.objects.filter()[:5], } return render(request,'index.html',context) else: return HttpResponse("Request method is not a GET") def load(request): if request.method == 'GET': context = { 'entry_list': Entry.objects.filter()[:1], } return render(request,'index.html',context) else: return HttpResponse("Request method is not a GET") index.html ... <script> $(window).on("scroll", function() { if ((window.innerHeight + window.scrollY) >= document.body.offsetHeight) { console.log( "TEST" ); $.ajax( { type:"GET", url: "/load", data:{ }, }) } }); </script> ... Basicaly it loads 5 items at the beginning and what I try to achieve is that it loads 1 more as soon as I hit the bottom of the page. So jQuery works beacuase the console.log('Test') works and in my terminal it says "GET /load/ HTTP/1.1" 200 484 which is fine as well. I think I messed up the ajax somehow. I am not sure though. As you can probably tell I am a nooby but any help is highly appreciated.