I new to AngularJS and trying to set up Django with AngularJs, however, I have some issues with handling the routing with those two frameworks. so far I've set up like below:
When I run http://localhost:8000/index.html it works and shows me the file, but when I run http://localhost:8000/test as I wrote in app.js it gives me standard Django 404 error.
What am I missing?
urls.py
urlpatterns = [
url(r'^index.html/$',
]
app.js
var app = angular.module("myApp", ["ngRoute"]);
app.config(function($routeProvider) {
$routeProvider
.when("/test", {
templateUrl : "index.html",
controller: "MainCtrl"
})
});
app.controller("MainCtrl", function ($scope) {
$scope.msg = "test";
});
index.html
{% load static %}
<html ng-app="myApp">
<head>
</head>
<body>
<div>
test
</div>
<script src="{% static 'js/general/angular.min.js' %}" type="text/javascript"></script>
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.6.4/angular-route.js"></script>
<script type="text/javascript" src="{% static 'js/app.js' %}"></script>
</body>
</html>
You need to define the URL and it's corresponding views method.
In you urls.py
You need something like:
url(r'^test/$', views.test, name='test')
In views.py
def test(request):
return HttpResponse('You are looking at test')
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 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've decided to integrate an existing Angular 2 app into my Django REST project.
create Django app with static folder for my frontend:
urls.py:
from django.conf.urls import url
from frontend import views
from django.conf import settings
from django.conf.urls.static import static
urlpatterns = [
url(r'^$', views.index, name='index'),
] + static(settings.STATIC_URL, document_root=settings.STATIC_ROOT)
views.py:
from django.shortcuts import render
def index(request):
"""
Renders the Angular2 SPA
"""
return render(request, template_name='index.html')
move my Angular 2 app to frontend static folder
add static settings in my settings:
STATIC_URL = '/static/'
STATICFILES_DIRS = [
os.path.join(BASE_DIR, 'frontend', 'static'),
]
STATIC_ROOT = os.path.join(BASE_DIR, 'static')
make changes in index.html:
<html>
<head>
<base href="/">
<title>PhotoHub</title>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
{% load staticfiles %}
<link rel="stylesheet" href="{% static "node_modules/bootstrap/dist/css/bootstrap.min.css" %}">
<link href="{% static "bower_components/font-awesome/css/font-awesome.min.css" %}" rel="stylesheet" />
<link href="{% static "bower_components/alertify.js/themes/alertify.core.css" %}" rel="stylesheet" />
<link href="{% static "bower_components/alertify.js/themes/alertify.bootstrap.css" %}" rel="stylesheet" />
<link rel="stylesheet" href="{% static "styles.css" %}">
<script src="{% static "bower_components/jquery/dist/jquery.min.js" %}"></script>
<script src="{% static "node_modules/bootstrap/dist/js/bootstrap.min.js" %}"></script>
<script src="{% static "bower_components/alertify.js/lib/alertify.min.js" %}"></script>
<!-- 1. Load libraries -->
<!-- Polyfill(s) for older browsers -->
<script src="{% static "node_modules/core-js/client/shim.min.js" %}"></script>
<script src="{% static "node_modules/zone.js/dist/zone.js" %}"></script>
<script src="{% static "node_modules/reflect-metadata/Reflect.js" %}"></script>
<script src="{% static "node_modules/systemjs/dist/system.src.js" %}"></script>
<!-- 2. Configure SystemJS -->
<script src="{% static "systemjs.config.js" %}"></script>
<script>
System.import('app').catch(function(err){ console.error(err); });
</script>
</head>
<!-- 3. Display the application -->
<body>
<photohub></photohub>
</body>
</html>
make changes in systemjs.config.js:
(function (global) {
System.config({
//static
defaultJSExtensions: true,
paths: {
// paths serve as alias
'npm:': 'static/node_modules/'
},
// map tells the System loader where to look for things
map: {
app: 'static/dist',
// angular bundles
'#angular/core': 'npm:#angular/core/bundles/core.umd.js',
'#angular/common': 'npm:#angular/common/bundles/common.umd.js',
'#angular/compiler': 'npm:#angular/compiler/bundles/compiler.umd.js',
'#angular/platform-browser': 'npm:#angular/platform-browser/bundles/platform-browser.umd.js',
'#angular/platform-browser-dynamic': 'npm:#angular/platform-browser-dynamic/bundles/platform-browser-dynamic.umd.js',
'#angular/http': 'npm:#angular/http/bundles/http.umd.js',
'#angular/router': 'npm:#angular/router/bundles/router.umd.js',
'#angular/forms': 'npm:#angular/forms/bundles/forms.umd.js',
// other libraries
'rxjs': 'npm:rxjs',
'angular-in-memory-web-api': 'npm:angular-in-memory-web-api',
},
// packages tells the System loader how to load when no filename and/or no extension
packages: {
app: {
main: './main.js',
defaultExtension: 'js'
},
rxjs: {
defaultExtension: 'js'
},
'angular-in-memory-web-api': {
main: './index.js',
defaultExtension: 'js'
}
}
});
})(this);
The TypeScript files are compiled in /dist and templates remained in /app. When I used two different servers the path for templateUrl look like this:
templateUrl: './app/app.component.html'
now I'm trying to declare templateUrl this way, but it doesn't work:
templateUrl: '{{ STATIC_URL }}' + '/app/app.component.html'
How to deal with templates urls now?
Response:
"GET /app/components/login/login.component.html HTTP/1.1" 404 2601
Not Found: /app/app.component.html
JavaScript files loaded well:
"GET /app/components/login/login.component.html HTTP/1.1" 404 2601
Not Found: /app/components/register/register.component.html
This solved problem:
templateUrl: 'static/app/app.component.html'
I am not sure what error you're having but you probably should use the static tag to make a URL to a static asset in your template:
{% load static %}
templateUrl: "{% static '/app/app.component.html' %}"
Doc: https://docs.djangoproject.com/en/1.10/ref/templates/builtins/#std:templatetag-static
I am new to Tornado. I am trying to link a CSS file to the html template. I am using jinja2 with Tornado. But due to some unknown reasons the CSS file is not loading up.
EDIT: I have created my custom render_template function which is working fine.
Directory structure:
app.py
static
css
custom.css
templates
index.html
Here is my Request Handler's Class:
class Index(RequestHandler):
def get(self):
path = os.path.join('static/css/', 'custom.css')
return self.write(render_template('index.html', path = path))
and here is my index.html template:
<!Doctype html>
<html>
<head>
<link rel="stylesheet" type="text/css" href="{{path}}"/>
</head>
<body>
<div>
<div class="header">
asdasdasd
</div>
</div><!--wrapper-->
</body>
</html>
but the browser is returning the 404-NotFound error for the css file with the correct url, that is http://localhost/static/css/custom.css
Here is a guide on how to link static files in tornado:
http://tornado.readthedocs.org/en/latest/guide/running.html#static-files-and-aggressive-file-caching
Important is the 'static_path' setting in your settings dictionary:
settings = {
"static_path": os.path.join(os.path.dirname(__file__), "static")
}
Now you should be able to use it.
I'm a beginner in django, I follow the steps showed at GitHub, but I just got a blank page, here my code:
views.py
from django.shortcuts import render
from django_ajax.decorators import ajax
#ajax
def AjaxView(request):
return render(request, 'blogs/ajaxtest.html'`
urls.py
from django.conf.urls import patterns, include, url
urlpatterns = patterns('',
url(r'^ajax/', 'blogs.views.AjaxView', name='Ajax'))
ajaxtest.html
<head>
<script type="text/javascript" src="{% static '/blogs/django_ajax/js/jquery.ajax.min.js' %}"></script>
<script src="https://code.jquery.com/jquery-1.10.2.min.js"></script>
<title>Ajax Test</title>
</head>
<body>
<script type="text/javascript">
ajaxGet('/', function(content){
//onSuccess
alert(content);
})
</script>
</body>
You need to include jQuery before django_ajax or django_ajax won't work, it is a requirement.
Also your AjaxView function seems to be incomplete.