I am trying to refresh the table data in my Django HTML page, without refreshing the whole page after every 10 seconds ... for which I am using AJAX in Django
This is the HTML Page I want to render -
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>temp1</title>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js"></script>
</head>
<body>
<h1>Hello there</h1>
<h1>{{info_data}}</h1>
<table id="_appendHere" class="table table-striped table-condensed">
<tr>
<th>Username</th>
<th>Email</th>
<th>Gender</th>
</tr>
{% for item in info_data %}
<tr><td>{{item.username}} - {{item.email}} - {{item.gender}}</td></tr>
{% endfor %}
</table>
</body>
<script>
var append_increment = 0;
setInterval(function() {
$.ajax({
type: "GET",
url: {% url 'App1:temp' %}, // URL to your view that serves new info
})
}, 10000)
</script>
</html>
I have created a model inside an app called "App1" whose data I am passing to this table using this code -
from django.shortcuts import render
from App1.models import Info
# Create your views here.
def tempPage(request):
info_data=Info.objects.all()
context={"info_data":info_data}
return render(request,"App1/temp1.html",context)
This is the urls.py for App1 -
from django.contrib import admin
from django.urls import path,include
from App1 import views
app_name = 'App1'
urlpatterns = [
path('temp/', views.tempPage,name="tempPage"),
]
But I get this error on the URL http://localhost:8000/temp/ -
NoReverseMatch at /temp/
Reverse for 'temp' not found. 'temp' is not a valid view function or pattern name.
I am not sure where I'm going wrong
I even added a namespace for the App and included that in the url part of the AJAX request "App1:temp"
But that gives the same error
Project Structure -
Any help would be highly appreciable!! Thanks!!
You have typo error in your url change temp to tempPage
<script>
var append_increment = 0;
setInterval(function() {
$.ajax({
type: "GET",
url: {% url 'App1:tempPage' %}, // URL to your view that serves new info
})
}, 10000)
</script>
Related
I'm trying to practice ajax in django but I got this error 'QuerySet' object has no attribute 'META'. But it's showing the data in the traceback but not in the template because of the error.How to fix this?
models.py
from django.db import models
# Create your models here.
class Profile(models.Model):
name = models.CharField(max_length=100)
email = models.CharField(max_length=100)
bio = models.CharField(max_length=100)
def __str__(self):
return self.name
I think it has something to do with the views but I cant figure it out.
views.py
from django.shortcuts import render
from .models import Profile
from django.http import JsonResponse
# Create your views here.
def list(request):
return render(request, 'livedata/list.html')
def getProfiles(request):
profiles = Profile.objects.all()
# print(JsonResponse({"profiles": list(profiles.values())}))
return JsonResponse({"profiles": list(profiles.values())})
urls.py
from django.urls import path
from . import views
urlpatterns = [
path('', views.list, name='list'),
path('getProfiles', views.getProfiles, name='getProfiles')
]
index.html
{% load static %}
<!doctype html>
<html lang="en">
<head>
<!-- Required meta tags -->
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no">
<!-- Bootstrap CSS -->
<link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.1.3/css/bootstrap.min.css" integrity="sha384-MCw98/SFnGE8fJT3GXwEOngsV7Zt27NXFoaoApmYm81iuXoPkFOJwJ8ERdknLPMO" crossorigin="anonymous">
{% comment %} <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js"></script> {% endcomment %}
<script src="https://code.jquery.com/jquery-3.5.1.js" integrity="sha256-QWo7LDvxbWT2tbbQ97B53yJnYU3WhH/C8ycbRAkjPDc=" crossorigin="anonymous"></script>
<script src="{% static 'js/main.js' %}" defer></script>
<title>Hello, world!</title>
</head>
<body>
{% block contents %}{% endblock contents %}
{% block scripts %}{% endblock scripts %}
<!-- Optional JavaScript -->
<!-- jQuery first, then Popper.js, then Bootstrap JS -->
{% comment %} <script src="https://code.jquery.com/jquery-3.3.1.slim.min.js" integrity="sha384-q8i/X+965DzO0rT7abK41JStQIAqVgRVzpbzo5smXKp4YfRvH+8abtTE1Pi6jizo" crossorigin="anonymous"></script> {% endcomment %}
{% comment %} <script src="https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.14.3/umd/popper.min.js" integrity="sha384-ZMP7rVo3mIykV+2+9J3UJ46jBk0WLaUAdn689aCwoqbBJiSnjAK/l8WvCWPIPm49" crossorigin="anonymous"></script> {% endcomment %}
<script src="https://stackpath.bootstrapcdn.com/bootstrap/4.1.3/js/bootstrap.min.js" integrity="sha384-ChfqqxuZUCnJSK3+MXmPNIyE6ZbWh2IMqE241rYiqJxyMiZ6OW/JmZQ5stwEULTy" crossorigin="anonymous"></script>
</body>
</html>
list.html
{% extends 'livedata/index.html' %}
{% block contents %}
<h1>List of live data</h1>
<ul id="display">
</ul>
{% endblock contents %}
{% block scripts %}
<script>
$(document).ready(function () {
setInterval(function () {
$.ajax({
type: 'GET',
url: "{% url 'getProfiles' %}",
success: function (response) {
// console.log(response);
$("#display").empty();
for (var key in response.profiles) {
var temp = "<li>" + response.profiles[key].name + "</li>";
$("#display").append(temp);
}
},
error: function (response) {
alert("Error occured");
}
});
}, 1000);
});
</script>
{% endblock scripts %}
You should not name a view list, list is a builtin function that you use in other views. By defining a view named list, the list(profiles.values()) will call the view with profile.values() as the request.
Rename list to view_list for example and update the url patterns to direct to view_list instead:
def view_list(request):
return render(request, 'livedata/list.html')
def getProfiles(request):
profiles = Profile.objects.all()
# does not refer to the view ↓ but to the list builtin
return JsonResponse({"profiles": list(profiles.values())})
The urls.py thus looks like:
from django.urls import path
from . import views
urlpatterns = [
path('', views.view_list, name='list'),
path('getProfiles', views.getProfiles, name='getProfiles')
]
I wanted Pass URL parameter in iframe issue as mentioned Passing URL parameter in iframe issue
I tried using following https://glitch.com/edit/#!/tf-embed-with-params?path=README.md:1:0
Traceback:
Exception Type: AttributeError
Exception Value:
'RequestContext' object has no attribute 'META'
views.py
from django.shortcuts import render
from django.template import RequestContext
def survey(request):
return render(RequestContext(request),'wfhApp/survey.html')
And my html page is as follow:
<!DOCTYPE html>
{% load django_typeform %}
{% load sekizai_tags %}
<html>
<head>
<title>Hello!</title>
<meta charset="utf-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1">
<link rel="stylesheet" href="/styles.css">
</head>
<body>
<h1>Hi there!</h1>
<div class="target-dom-node" style="width: 100%; height: 500px;"></div>
<script src="https://embed.typeform.com/embed.js"></script>
<script src="/survey/script.js"></script>
{% typeforms_embed 'https://theother2thirds.typeform.com/to/hNZW30' 'New typeform' '{"hideHeaders": true, "hideFooter": true}' %}
</body>
</html>
urls.py
from django.conf.urls import url
from wfhApp import views
app_name = 'wfhApp'
urlpatterns = [
url(r'^survey/$',views.survey, name='survey'),
]
The issue is that you're wrapping the request inside of a RequestContext object, which is incorrect for the render() function.
The render() function will build the RequestContext object for you, so it expects the request and any extra context variables as arguments.
Instead, just pass the request directly to the render() function:
def survey(request):
return render(request, 'wfhApp/survey.html')
I am trying to implement an autocomplete search by following this tutorial
https://medium.com/#ninajlu/django-ajax-jquery-search-autocomplete-d4b4bf6494dd
And i am failing to implement it, and i think it has something to do with my urls or the way i am putting scripts in my .html file.
My search bar is in my index view
index.html
<!DOCTYPE html>
<html>
<head>
<link rel="stylesheet" href="http://code.jquery.com/ui/1.8.18/themes/base/jquery-ui.css" type="text/css" media="all" /> <script src="http://ajax.googleapis.com/ajax/libs/jquery/1.7.1/jquery.min.js" type="text/javascript"> </script> <script src="https://ajax.googleapis.com/ajax/libs/jqueryui/1.8.16/jquery-ui.min.js" type="text/javascript"></script>
</head>
<body>
{% load static %}
<link rel="stylesheet" type="text/css" href="{% static 'KPI/style.css' %}">
<script>
$(document).ready(function(){
$("#txtSearch").autocomplete({
source: "/login/index",
minLength: 2,
open: function(){
setTimeout(function () {
$('.ui-autocomplete').css('z-index', 99);
}, 0);
}
});
});
</script>
<form id="search" method="POST" action="{% url 'kpi:search' %}">
{% csrf_token %}
<input type="text" class="form-control" id="txtSearch" name="txtSearch">
<button type="submit" class="btn btn-default btn-submit">Submit</button>
</form>
</body>
</html>
urls.py
app_name = 'kpi'
urlpatterns = [
path('login/', views.LoginView.as_view(), name='login'),
path('login/index/', views.IndexView.as_view()),
]
now in the tutorial it says to put this path url(r'^ajax_calls/search/', autocompleteModel), but it doesn't seem like the path has to be this way, so i changed the path to login/index/ and called the class view IndexView which holds the autocompleteModel like so
views.py
class IndexView(LoginRequiredMixin,TemplateView):
template_name = 'KPI/index.html'
def autocompleteModel(self,request):
if request.is_ajax():
q = request.GET.get('term', '').capitalize()
search_qs = Epic.objects.filter(name__icontains=q)
results = []
print(q)
for r in search_qs:
results.append(r.name)
data = json.dumps(results)
else:
data = 'fail'
mimetype = 'application/json'
return JsonResponse(data, mimetype)
Epic is the model i am searching on with the value name.
with the code i have above it doesn't do anything, and i'm hoping someone can see a flaw in it.
I am trying to create a user form and then post the input to the database model.However I keep getting this error message
Page not found (404)
Request Method: GET
Request URL: http://127.0.0.1:8000/hiresite/Recruiter
Using the URLconf defined in recruitment.urls, Django tried these URL patterns, in this order:
^hiresite ^$ [name='index']
^hiresite ^Recruiter$ [name='Recruiter']
^admin/
The current URL, hiresite/Recruiter, didn't match any of these.
I am a bit confused because I can see the url Recruiter above and yet I get the error message.Your help would be much appreciated .
1.Here is my Urls.py for the app
from django .conf.urls import url
from. import views
urlpatterns = [
url(r'^$', views.index, name='index'),
url(r'^Recruiter$', views.Recruiter, name='Recruiter')
]
2.Here is my Urls.py for the Project
from django.conf.urls import include, url
from django.contrib import admin
urlpatterns = [
url(r'^hiresite', include('hiresite.urls')),
url(r'^admin/', admin.site.urls),
]
3.Here is the view for the Url Recruiter
def Recruiter(request):
if request.method == 'POST':
form = register_job(request.POST)
if form.is_valid():
title = request.POST.get('title', ' ')
description = request.POST.get('description', ' ')
salary = request.POST.get('salary', ' ')
reference = request.POST.get('reference', ' ')
user_obj = jobsearch(title=title, description=description, salary=salary, reference=reference)
user_obj.save()
return render(request, 'hiresite/Recruiter.html', {'user_obj ': user_obj, 'is_registered': True})
else:
form = register_job()
return render(request, 'hiresite/Recruiter.html', {'form': form})
4.Here is the Html template file used in the views.py file for the Url Recruiter
!DOCTYPE html>
<html lang="en">
<head>
<title>Learning Html the Hard way</title>
<meta charset="utf-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1">
<meta name="description" content="">
<meta name="author" content="">
<link rel="icon" href="../../favicon.ico">
{% load staticfiles %}
<link rel='stylesheet' href= " {% static 'css/bootstrap.min.css' %}" type = 'text/css'/>
</head>
<body>
<form action="{% url 'hiresite:Recruiter' %}" method="post">
{% csrf_token %}
{{ form }}
<input type="submit" value="Submit">
</form>
</body>
</html>
convert this line :
url(r'^hiresite', include('hiresite.urls')),
To this line :
url(r'^hiresite/', include('hiresite.urls')),
I sent a information by Post method until one views in Django and returned to the site. However, I'm not getting submit this information on the site.
File post3.html
<!DOCTYPE html>
<html ng-app>
<head>
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/angularjs/1.2.27/angular.min.js"></script>
<script>
function ListDropdown($scope, $http){
$scope.ccvms={lista01:['1','3','5','7','9'],lista02:['2','4','6','8','10']}
$scope.send=function(x,y){
$http({
method:'POST',
url:'/escalar',
data:x+y,
headers:{'Content-Type': 'application/x-www-form-urlencoded'},
}).success(function(c){
console.log(c)
})
}
}
</script>
</head>
<body>
<div ng-controller="ListDropdown">
<select ng-model="ccvm" ng-options="ccvm as ccvm for (ccvm, nums) in ccvms"></select>
<select ng-model="num" ng-disabled="!ccvm" ng-options="num for num in ccvms[ccvm]" ng-change="send(num, ccvm)"></select>
<h1 ng-model=c>
</div>
</body>
</html>
File views.py
from django.views.decorators.csrf import csrf_exempt, csrf_protect
from django.http import HttpResponse
from django.shortcuts import render_to_response
def post3(request):
return render_to_response("post3.html")
#csrf_exempt
def escalando(z):
x=list(z.POST)
c=str(x[0])+"_retornou"
return HttpResponse(c)
File urls.py
from django.conf.urls import patterns, include, url
urlpatterns = patterns('',
url(r'^post3/','bvmfconsulta.views.post3'),
url(r'^escalar','bvmfconsulta.views.escalando'),
)
Appears in the console.log(c) the information, for example "4lista02_retornou", however, I am not getting insert it on the site.
I resolved as follows:
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/angularjs/1.2.27/angular.min.js"></script>
<script>
function ListDropdown($scope, $http){
$scope.ccvms={lista01:['1','3','5','7','9'],lista02:['2','4','6','8','10']}
$scope.resposta=""
$scope.send=function(x,y){
$http({
method:'POST',
url:'/escalar',
data:x+y,
headers:{'Content-Type': 'application/x-www-form-urlencoded'},
}).success(function(c){
$scope.resposta=c
})
}
}
</script>
<h1 ng-bind="resposta"></h1>