In django, tried to create a dynamic web page with ajax. But it doesn't takes the automatic reload. The requesting to the server is only done when reloading the page. Here my codes.
How i make into dynamic reloading.
Views.py
from django.shortcuts import render
from django.http import HttpResponse
from random import randrange
def main(request):
return render(request, 'index.html')
def random_generator(request):
return HttpResponse(randrange(0, 100))
urls.py
from django.conf.urls import patterns, include, url
from django.conf import settings
from django.conf.urls.static import static
urlpatterns = patterns('',
url('^main/$', 'Signup.views.main'),
url('^random/$', 'Signup.views.random_generator')
)
random.html
<!DOCTYPE html>
<html>
<head>
<script type="text/javascript">
function refreshRandom() {
$.ajax({
url: '/random/',
dataType: 'html',
success: function(data) {
$('#random').html(data);
},
complete: function() {
window.setTimeout(refreshRandom, 1000);
}
});
}
window.setTimeout(refreshRandom, 1000);
</script>
</head>
<body>
<div id='random'></div>
</body>
</html>
You can use Jquery like this
$(document).ready(function() {
// JQuery code to be added in here.
});
in your template use
<script src="{% static "/js/jquery.js" %}"></script>
<script src="{% static "/js/rango-ajax.js" %}"></script>
Related
I'm trying to integrate vue-components into django-templates. The basic setup did work, but I'm stacked with a component which needs an import itself.
Here is the component (vue/dropdown.html):
<div id="app">
<template>
...
</template>
</div>
<script setup>
import { computed, ref } from 'vue'
import {CheckIcon, ChevronUpDownIcon} from '#heroicons/vue/20/solid'
const query =ref('')
const selectedPerson = ref(null)
...
var app = new Vue({
delimiters: ['[[', ']]'],
el: '#app',
data: {
message: 'Hello Vue!',
},
});
</script>
So, the 2 imports:
import {computed, ref} from Vue
import {CheckIcon, ChevronUpDownIcon} from '#heroicons/vue/20/solid'
are triggering the error in the browser's console:
Cannot use import statement outside a module
What is the proper way to use the imports?
I'm calling the dropdown.html from base.html:
<html lang="{{ LANGUAGE_CODE }}">
<head>...</head>
<body>
<script src="https://cdn.jsdelivr.net/npm/vue/dist/vue.js"></script>
{% include 'vue/dropdown.html' %}
</body>
</html>
I think this happens because vue cdn should be imported into dropdown.html.Please try this fix and let me know if it works.
Thank you
I'm building a basic Django site.
Currently, I'm trying figure out a way to make an API call and retrieve the results on page load.
Is it possible to use the js .onload function to call a Django view function?
Any suggestions/tips would be appreciated!
you can use "requests" library and making a request on the django view for this page.
import requests
def my_view(request):
r = requests.get('https://api.github.com/user', auth=('user', 'pass'))
context = {
'data': r.json()
}
return render(request, 'my_html.html', context)
You can simply use JavaScript fetch API like following:
page.html
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>My Title</title>
</head>
<body>
<h1 id="msg"></h1>
<script>
var url = 'http://127.0.0.1:8080/message';
fetch(url).then(
response => response.json()
).then(function(data) {
document.getElementById("msg").textContent = data['message'];
});
</script>
</body>
</html>
views.html
from django.shortcuts import render
from django.http import JsonResponse
def index(request):
return render(request, "index.html")
def message(request):
return JsonResponse({"message": "Hello World!"})
I am trying to document my Django REST API with built-in methods. Here is the urls.py:
from django.contrib import admin
from django.urls import path, include
from django.conf import settings
from django.conf.urls.static import static
from django.conf.urls import url
from django.views.generic.base import TemplateView
from rest_framework.documentation import include_docs_urls
urlpatterns = [
path('api/', include('api.urls')),
path('admin/', admin.site.urls),
path('', include('main.urls')),
path('swagger-ui/', TemplateView.as_view(
template_name='swagger-ui.html',
extra_context={'schema_url': 'openapi-schema'}
), name='swagger-ui'),
url(r'^.*', TemplateView.as_view(template_name="home.html")),
] + static(settings.STATIC_URL, document_root=settings.STATIC_ROOT)
static/templates/swagger-ui.html:
<html>
<head>
<title>Swagger</title>
<meta charset="utf-8"/>
<meta name="viewport" content="width=device-width, initial-scale=1">
<link rel="stylesheet" type="text/css" href="//unpkg.com/swagger-ui-dist#3/swagger-ui.css" />
</head>
<body>
<div id="swagger-ui"></div>
<script src="//unpkg.com/swagger-ui-dist#3/swagger-ui-bundle.js"></script>
<script>
const ui = SwaggerUIBundle({
url: "{% url schema_url %}",
dom_id: '#swagger-ui',
presets: [
SwaggerUIBundle.presets.apis,
SwaggerUIBundle.SwaggerUIStandalonePreset
],
layout: "BaseLayout"
})
</script>
</body>
</html>
However, I don't understand where should we allocate the openapi-schema file? Is it a .yml file or .js? And is there a way to generate it automatically?
The schema_url should point to a valid OpenAPI spec. Swagger UI can handle both JSON and YAML files.
The easiest way to point Swagger UI to a valid schema is by using a dynamic schema view, which I think you've skimmed over.
From the docs:
from rest_framework.schemas import get_schema_view
urlpatterns = [
# ...
# Use the `get_schema_view()` helper to add a `SchemaView` to project URLs.
# * `title` and `description` parameters are passed to `SchemaGenerator`.
# * Provide view name for use with `reverse()`.
path('openapi', get_schema_view(
title="Your Project",
description="API for all things …",
version="1.0.0"
), name='openapi-schema'),
# ...
]
If you add this URLpattern url: "{% url schema_url %}", in your template, it will be able to find the dynamically generated schema.
I introduced vuejs using webpack in django, but I can not use vue instances from django templates.
Looking at the chrome devtool, the transpiled js is loaded correctly, but shows {{message}}.
The following message is output on the console of chrome devtool.
TypeError: undefined is not an object (evaluating 'hasOwnProperty.call (it, key)')
ReferenceError: Can't find variable: Vue
This is my code.
main.js
import Vue from 'vue'
import App from './App.vue'
import vuetify from '#/plugins/vuetify' // path to vuetify export
window.Vue = require('vue');
Vue.config.productionTip = false
new Vue({
render: h => h(App),
vuetify,
}).$mount('#app')
html
{% load render_bundle from webpack_loader %}
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Example</title>
</head>
<body>
{% verbatim %}
<div id="app">
{{ message }}
</div>
{% endverbatim %}
{% render_bundle 'main' %}
<script>
var app = new Vue({
el: '#app',
data: {
message: 'Hello Vue!'
}
})
</script>
</body>
</html>
log(django)
django | [09/Jan/2020 11:22:58] "GET /vue/ HTTP/1.1" 200 374
django | [09/Jan/2020 11:22:58] "GET /static/webpack_bundles/main-ccb1054f18bba9ee992d.js HTTP/1.1" 304 0
urls.py
from django.urls import path
from .views import signupfunc, loginfunc, listfunc, logoutfunc, vuefunc
urlpatterns = [
path('signup/', signupfunc, name='signup'),
path('login/', loginfunc, name='login'),
path('list/', listfunc, name='list'),
path('logout/', logoutfunc, name='logout'),
path('vue/', vuefunc, name='vue'),
]
vies.py
<snip>
def vuefunc(request):
return render(request, 'vue.html')
This might be a dumb question, but are you importing your main.js file from your template? It would look something like this:
<script src="{% static 'js/main.js' %}"></script>
Also, just as an aside, I use Vue with django and always list my own delimiter in the Vue code so I don't have to put {% verbatim %} tags around every variable. It looks something like this:
var app = new Vue({
el: '#app',
delimiters: ['${', '}'],
data: {
message: 'Hello Vue!'
}
})
and you can obviously pick whichever delimiters you want.
I'm having some trouble getting the CSRF integration between Django and Angular to work. I made an earlier broader post about that here.. The problem is that logged in users can't make post-requests from the front-end, but they can make the exact same requests from Django's browsable API through forms.
I'm setting a {% csrf_token %} at the index template that Django serves and I am using Angular's built it XSRFS strategy to set attack a header to http requests, but I think the problem is that I'm not catching the value provided by Django's generated csrf token and can't figure out how to implement gathering that data and attaching it to my Angular http-request cookies. Here's the code for the module that provides the strategy:
import { BrowserModule } from '#angular/platform-browser';
import { FormsModule, ReactiveFormsModule } from '#angular/forms';
import { NgModule } from '#angular/core';
import { HttpClientModule } from '#angular/common/http';
import { HttpModule, XSRFStrategy, CookieXSRFStrategy } from '#angular/http'
import { AppComponent } from './app.component';
import { AppRoutingModule } from './app-routing.module';
import { RegisterComponent } from './register/register.component';
import { LoginComponent } from './login/login.component';
import { AlertComponent } from './_directives/alert.component';
import { ProfileComponent } from './profile/profile.component';
import { AuthGuardService } from './_guards/auth-guard.service';
import { AlertService } from './_services/alert.service';
import { AuthService } from './_services/auth.service';
import { UserService } from './_services/User.service';
#NgModule({
declarations: [
AppComponent,
RegisterComponent,
LoginComponent,
AlertComponent,
ProfileComponent,
],
imports: [
BrowserModule,
FormsModule,
ReactiveFormsModule,
AppRoutingModule,
HttpClientModule,
HttpModule
],
providers: [
{
provide: XSRFStrategy,
useValue: new CookieXSRFStrategy('csrftoken', 'X-CSRFToken')
}
],
bootstrap: [AppComponent]
})
export class AppModule { }
And here is the output from the browser with the csrf-value that I think I need to attach somehow:
<input type='hidden' name='csrfmiddlewaretoken' value='9FKUKSXHbJfLClZniDXIHrMu2AEUtPQr4mGDfNSOZURHYVyKGBYvREIuucN0UsEM' />
<!doctype html>
<html lang="en">
<head>
<meta charset="utf-8">
<title>AngularWebapp</title>
<base href="/">
<meta name="viewport" content="width=device-width, initial-scale=1">
<link rel="icon" type="image/x-icon" href="favicon.ico">
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css" integrity="sha384-BVYiiSIFeK1dGmJRAkycuHAHRg32OmUcww7on3RYdg4Va+PmSTsz/K68vbdEjh4u" crossorigin="anonymous">
</head>
<body>
<app-root></app-root>
<script type="text/javascript" src="/static/runtime.js"></script><script type="text/javascript" src="/static/polyfills.js"></script><script type="text/javascript" src="/static/styles.js"></script><script type="text/javascript" src="/static/vendor.js"></script><script type="text/javascript" src="/static/main.js"></script>
<script src="https://code.jquery.com/jquery-2.2.4.min.js" integrity="sha256-BbhdlvQf/xTY9gja0Dq3HiwQF8LaCRTXxZKRutelT44=" crossorigin="anonymous"></script>
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js" integrity="sha384-Tc5IQib027qvyjSMfHjOMaLkfuWVxZxUPnCJA7l2mCWNIpG9mGCD8wGNIcPD7Txa" crossorigin="anonymous"></script>
</body>
</html>
Make sure that "csrfmidlewaretoken": {{csrf_token}} is submitted with the form.
Make sure {% csrf_token %} is inside <form></form> tags. If you are posting the data with ajax, add "csrfmidlewaretoken": {{csrf_token}} to your form data that is submitted.