We are using DJango rest framework to make api. We added swagger page, but its complain about swagger version.
Unable to render this definition
The provided definition does not specify a valid version field.
Please indicate a valid Swagger or OpenAPI version field. Supported version fields are swagger: "2.0" and those that match openapi: 3.0.n (for example, openapi: 3.0.0).
I was following documentation https://www.django-rest-framework.org/topics/documenting-your-api/#a-minimal-example-with-swagger-ui
Below are files.
urls.py
from django.urls import path
urlpatterns = [
...
...
path("openapi", get_schema_view(
title="My api",
description="API for me",
version="1.0.0"
), name="openapi-schema"),
path('swagger-ui/', TemplateView.as_view(
template_name='swagger-ui.html',
extra_context={'schema_url':'openapi-schema'}
), name='swagger-ui')
]
templates/swagger-ui.html
<!DOCTYPE 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",
requestInterceptor: (request) => {
request.headers['X-CSRFToken'] = "{{ csrf_token }}"
return request;
}
})
</script>
</body>
</html>
I think, its complaining about version: 1.0.0 mentioned in openapi schema view. But need to sure, if something else is not causing this issue.
Related
Is it possible to include snippets of shared HTML using Vite (vanilla)? I'm looking for a way to have the HTML prerendered without injecting via JS.
Something like:
<html>
<head>
{ include 'meta-tags' }
</head>
<body>
{ include 'nav' }
<h1>Hello World</h1>
<body>
</html>
vite-plugin-handlebars was the solution I was looking for. Partials were super easy to set up with this package:
Setup:
// vite.config.js
import { resolve } from 'path';
import handlebars from 'vite-plugin-handlebars';
export default {
plugins: [
handlebars({
partialDirectory: resolve(__dirname, 'partials'),
}),
],
};
File where you want to include partial:
<!-- index.html -->
{{> header }}
<h1>The Main Page</h1>
Rendered output:
<header>My Website</header>
<h1>The Main Page</h1>
You could use the vite-plugin-html that enables EJS templates in index.html:
// vite.config.js
import { defineConfig } from 'vite'
import { createHtmlPlugin } from 'vite-plugin-html'
export default defineConfig({
plugins: [
createHtmlPlugin({
entry: 'main.js',
/**
* Data that needs to be injected into the index.html ejs template
*/
inject: {
data: {
metaTags: `<meta charset="UTF-8" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />`,
nav: `<nav>
Google |
Apple
</nav>`,
},
},
}),
],
})
<!-- index.html -->
<html>
<head>
<%- metaTags %>
</head>
<body>
<%- nav %>
<h1>Hello World</h1>
<body>
</html>
demo
I'm working on a small application using Vue.js and Django on Digitalocean, so I have installed Django Webpack loader and the tracker also, now I have executed my Django server and my vue.js also using npm run serve and when I access to my webpage localhost:8000 I see only a blank page since everything is installed correctly, This is my HTML page ( when I inspect on chrome browser )
<html>
<head>
<title>Title of the document</title>
</head>
<body>
<div id="app"></div>
<script type="text/javascript" src="http://0.0.0.0:8080/js/app.js"></script>
</body>
</html>
PS : i think the problem is in app.js ( because i follow the link and i get an error )
This site can’t be reachedThe webpage at http://0.0.0.0:8080/js/app.js might be temporarily down or it may have moved permanently to a new web address.
ERR_ADDRESS_INVALID
you should config your vue application first creating vue.config.js file.
vue.config.js:
const BundleTracker = require("webpack-bundle-tracker");
module.exports = {
// on Windows you might want to set publicPath: "http://127.0.0.1:8080/"
publicPath: "http://0.0.0.0:8080/",
outputDir: "./dist/",
chainWebpack: (config) => {
config
.plugin("BundleTracker")
.use(BundleTracker, [{ filename: "./webpack-stats.json" }]);
config.output.filename("bundle.js");
config.optimization.splitChunks(false);
config.resolve.alias.set("__STATIC__", "static");
config.devServer
// the first 3 lines of the following code have been added to the configuration
.public("http://127.0.0.1:8080")
.host("127.0.0.1")
.port(8080)
.hotOnly(true)
.watchOptions({ poll: 1000 })
.https(false)
.disableHostCheck(true)
.headers({ "Access-Control-Allow-Origin": ["*"] });
}
// uncomment before executing 'npm run build'
// css: {
// extract: {
// filename: 'bundle.css',
// chunkFilename: 'bundle.css',
// },
// }
};
Then load render_bundle from webpack_loader. Your django template will be like:
{% load render_bundle from webpack_loader %}
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<title>Document</title>
</head>
<body>
<!-- This part is in the screenshot at the bottom! -->
<h1>Vue JS</h1>
<div id="app"></div>
{% render_bundle 'app' %}
</body>
</html>
Make Sure you are using webpack-bundle-tracker of version #0.4.3
You can follow this link for step by step tutorial.
I am wanting to host an Angular 6 application in Django, how do I do this?
Integrating Angular 8 and django 2.2
Used Visual Studio for Django 2.2 and Visual Studio Code for Angular 8
I tweaked the above solution and it ultimately worked. devised a simpler solution using some additional references (listed at the end) on top of the above solution.
Assuming:
angular is setup at: example/angular
django is setup at: example/django
Distribute angular files directly to django static folder
This is #1 key, the rest is glue (somewhat ugly) code to stitch the frameworks together as painless as possible.
At the console:
cd example/angular
ng build --prod --output-path ..\django\mysite\mysite\app\static\angular --output-hashing none --watch
Check Angular/CLI for command line switches and their use, the key here that the output of angular compilation goes directly to Django, no need for a middle man.
Maintain independent FE and BE for development and testing
Note: this is optional, you could "ruin" your angular development environment and put all django tags and attributes directly in angular, at the cost of losing FE - BE independence.
The index.html distributed in angular cannot be used "as is" in Django.
Here is such an example call it angular.html:
{% load static %}
<!doctype html>
<html lang="en">
<head>
<meta charset="utf-8">
<title>mysite</title>
<base href="/">
<meta name="viewport" content="width=device-width, initial-scale=1">
<link rel="icon" type="image/x-icon" href="{% static 'angular/favicon.ico' %}">
<link rel="stylesheet" href="{% static 'angular/styles.css' %}">
</head>
<body>
<app-root></app-root>
<script src="{% static 'angular/runtime.js' %}"></script>
<script src="{% static 'angular/polyfills-es5.js' %}"></script>
<script src="{% static 'angular/polyfills.js' %}"></script>
<script src="{% static 'angular/main.js' %}"></script>
</body>
</html>
Note: using only Django native language
Serve it in django like any other html
What else
Two way routing between django and angular
Sharing packages like bootstrap
Strongly recommend django-rest-frame-work as a starting point
BUILDING A WEB APP WITH ANGULAR, DJANGO AND DJANGO REST a more complex example putting it all together, I would keep the above simplified django and angular gluing mechanism.
angular8 django
Assumption: That django site is already running
Things needed to set up Angular 6 locally
Install Node Js.
https://nodejs.org/en/download/
Install Angular cli Globally
npm install -g #angular/cli
Navigate to angular on the repo
dir\angular
Install the npm's [libraries]
npm install
Serve the site
npm serve [-o]
Navigate to the hosted site
http://localhost:4200/
Angular Libraries needed to support Django
npm install #angular-devkit/custom-webpack --save
npm install #angular-builders/custom-webpack --save
npm install webpack-bundle-tracker --save
Django Libraries needed to support Angular
pip install django-webpack-loader
File Architecture - I put my angular project within the djangodir off root
root > djangodir > angular
root > djangodir > static
root > djangodir > templates
root > djangodir > webpack-stats-angular.json
Set Up Angular for Django
1) Alter angular.json to include custom webpack config and change build type to builder
"architect": {
"build": {
"builder": "#angular-builders/custom-webpack:browser",
"options": {
"customWebpackConfig": {
"path": "./extra-webpack.config.js"
},
"outputPath": "../static/angular",
2) extra-webpack.config.js code
const BundleTracker = require('webpack-bundle-tracker');
module.exports = {
plugins:[
new BundleTracker({filename: '../webpack-stats-angular.json'})
],
output: {
path: require('path').resolve('../static/angular'),
filename: "[name]-[hash].js"
}
};
Set Up Django for Angular
1) settings.py - added webpack_loader to installed_apps
INSTALLED_APPS = [
'webpack_loader'
]
2) settings.py - added webpack_loader
WEBPACK_LOADER = {
'DEFAULT': {
'BUNDLE_DIR_NAME': 'angular/',
'STATS_FILE': os.path.join(BASE_DIR, 'webpack-stats-angular.json'),
}
}
3) requirements.txt - We have a script that pulls from a text file to include dependencies - to this we add
django-webpack-loader==0.6.0
4) urls.py - set up the init routing to the hello world angular app
from . import views as djangodir_views
urlpatterns = [
# path('', include(router.urls)),
path('', djangodir_views.serve_angular, name='serve_angular')
]
5) views.py - include url path
def serve_angular(request):
return render(request, 'angular.html')
Angular.html Page:
{% load render_bundle from webpack_loader %}
<!doctype html>
<html lang="en">
<head>
<base href="/">
<title>Angular/TypeScript Hello World Project</title>
<meta charset="utf-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="description" content="Angular Hello World Starter">
<meta name="viewport" content="width=device-width, initial-scale=1">
<link href="//maxcdn.bootstrapcdn.com/bootstrap/3.3.6/css/bootstrap.min.css" rel="stylesheet" />
<!-- <link href="assets/styles/styles.css" rel="stylesheet" /> -->
</head>
<body>
<header class="navbar navbar-inner navbar-fixed-top">
<nav class="container">
<div class="navbar-header">
<span class="app-title"></span>
</div>
</nav>
</header>
<main class="container">
<app-root>
Loading...
</app-root>
<br /><br />
</main>
<footer>
<div class="navbar navbar-fixed-bottom">
<div class="navbar-inner footer">
<div class="container">
<footer>
</footer>
</div>
</div>
</div>
</footer>
{% render_bundle 'runtime' %}
{% render_bundle 'polyfills' %}
{% render_bundle 'styles' %}
{% render_bundle 'vendor' %}
{% render_bundle 'main' %}
</html>
References:
Angular 6|5 Tutorial: Integrating Angular with Django
Customizing Angular CLI 6 build — an alternative to ng eject
Evolving your Django frontend
Angular Hello World Example used
Routing:
In order for angular routing to work, you must
1) app-routing.module.ts - Add the routing to angular
const routes: Routes = [
{ path: '', component: TestComponent, data: { title: 'Home' }},
{ path: 'test', component: Test2Component, data: { title: 'Test' }}
];
2) urls.py - Add the routing to Django - just point it to the same view
urlpatterns = [
path('', djangodir_views.serve_angular, name='serve_angular'),
path('test', djangodir_views.serve_angular, name='serve_angular')
]
So, I've got 3 questions
How to use Django's URLs in react
EXAMPLE:
index.js (in react)
<Router>
<div>
<nav className="navbar navbar-inverse bg-inverse">
<div className="container">
<Link to="/" className="navbar-brand">PetFinder</Link>
<Link to="/storage" className="navbar-brand">Storage </Link>
Sign-Up <== like this
</div>
</nav>
<Route exact path={"/"} component={PetRegistration} />
<Route path={"/storage"} render={() => <Storage ids={checkingName} />} />
</div>
</Router>
urls.py
urlpatterns = [
path('admin/', admin.site.urls),
#path('api-auth/', include('rest_framework.urls', namespace="rest_framework")),
path('api/animals/', include('petsite.urls', namespace='petsite')),
path('api/user_info', core_views.UserInfo.as_view()),
path('signup/', core_views.signup, name='signup'),
path('', csrf_exempt(core_views.index), name='index'),
path(r'^login/$', auth_views.login, name='login'),
]
is_authenticated in react
How I did it:
In index.html
I wrote this ******. I am ashamed of this. Don't judge me, okay just a bit...
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no">
<meta name="theme-color" content="#000000">
<!--
manifest.json provides metadata used when your web app is added to the
homescreen on Android. See https://developers.google.com/web/fundamentals/engage-and-retain/web-app-manifest/
-->
<link rel="manifest" href="%PUBLIC_URL%/manifest.json">
<link rel="shortcut icon" href="%PUBLIC_URL%/favicon.ico">
<!--
Notice the use of %PUBLIC_URL% in the tags above.
It will be replaced with the URL of the `public` folder during the build.
Only files inside the `public` folder can be referenced from the HTML.
Unlike "/favicon.ico" or "favicon.ico", "%PUBLIC_URL%/favicon.ico" will
work correctly both with client-side routing and a non-root public URL.
Learn how to configure a non-root public URL by running `npm run build`.
-->
<title>React App</title>
</head>
<body>
<noscript>
You need to enable JavaScript to run this app.
</noscript>
<div class="signUpBlock">
Sign-Up
</div>
<div id="root">
</div>
<span class="currentUser" style="display: none">{{user.id}}</span>
<span class="currentUserName" style="display: none">{{user.username}}</span>
<span id="DJANGO_USER" style="display: none"></span>
<!--
This HTML file is a template.
If you open it directly in the browser, you will see an empty page.
You can add webfonts, meta tags, or analytics to this file.
The build step will place the bundled scripts into the <body> tag.
To begin the development, run `npm start` or `yarn start`.
To create a production bundle, use `npm run build` or `yarn build`.
-->
<script type="text/javascript">
var WHETHER_DJANGO_USER_IS_AUTH = "{{user.is_authenticated|yesno:"true,false"}}";
document.getElementById("DJANGO_USER").innerHTML = WHETHER_DJANGO_USER_IS_AUTH;
</script>
</body>
</html>
Check the code below:
<script type="text/javascript">
var WHETHER_DJANGO_USER_IS_AUTH = "{{user.is_authenticated|yesno:"true,false"}}";
document.getElementById("DJANGO_USER").innerHTML = WHETHER_DJANGO_USER_IS_AUTH;
</script>
<span id="DJANGO_USER" style="display: none"></span>
AND THEN IN index.js I do this
let boolButString = $('#DJANGO_USER').text()
var StringToBool = (boolButString === 'true');
If StringToBool = true I do smth (means that user is logged in)
else StringToBool != true I do smth (means that user is not logged in)
if (StringToBool) {
do smth
} else {
make some tea for him
}
I don't think I did it in a right way can you suggest me smth?
Is it real to check whether a user is auth. or not?
How to display Django context in react.
You might have seen how I did it in index.html
As usual, I wrote:
def index(request):
return render(request, 'index.html', {
"user" : request.user,
})
end then
<span class="currentUser" style="display: none">{{user.id}}</span>
grab data through jquery and display it in react app.
What can you suggest me?
How to display context properly?
Sry for cups.
I'm trying to mimic template inheritance as found in Django with a Grails app. I want to be able to define a '_header.gsp' which includes all the shared resources across the app:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<title>${title}</title>
<meta name="viewport" content="width=device-width, initial-scale=1.0">
%{--Shared Styles--}%
<link rel="stylesheet" href="${resource(dir: 'app/shared/css/bootstrap', file: 'bootstrap.min.css')}" type="text/css">
%{--Shared Libraries--}%
<script src="${resource(dir: 'lib/jquery', file: 'jquery.js')}"></script>
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.1.5/angular.min.js"></script>
%{--View-specific styles--}%
<g:each var="style" in="${styles}">
<link rel="stylesheet" href="${style}" type="text/css">
</g:each>
%{--View-specific scripts--}%
<g:each var="include" in="${includes}">
<script src="${include}" type="text/javascript"></script>
</g:each>
For each specific view template I will include this _header.gsp with a dictionary to fill in the view-specific requirements:
<g:render template="/header"
model="[
title:'Alerts',
styles:[
'${resource(dir: "app/stuff/css", file: "other.css")}',
'${resource(dir: "app/stuff/css", file: "second.css")}'
],
includes:[
'${resource(dir: "app/stuff/src/main/js/", file: "app.js")}',
'${resource(dir: "app/stuff/src/main/js/", file: "filters.js")}'
]
]" />
This is not working, and I'm sure my syntax is wrong somewhere. Can you define a '$resource(dir)' path inside of a g:each like I have? Perhaps I need to use g:link? Can this be done with Grails?
It sounds like you just need to use the resources tag. Define your 'resources' in ApplicationResources.groovy. Then, in your layout include the r:layoutResources tag, and finally, in the gsp specify the resource modules you want to include on that page.
In ApplicationResources.groovy
modules = {
application {
dependsOn 'jquery'
resource url: 'css/other.css'
resource url: 'css/second.css'
resource url: 'js/bootstrap.js'
}
charting {
//Charting is dependent on the 'application' resource module above,
// so it will include everything from the application and the
// charting css and js.
dependsOn 'application'
resource url: 'css/chart.css'
resource url: 'js/pie-chart.js'
}
reports {
//Completely separate so there is no dependsOn.
// Like 'application' module, it will only include the resources below.
resource url: 'css/pdf.css'
resource url: 'js/interactive-report.js'
}
}
In the /grails-app/layouts/main.gsp
<head>
...
<r:layoutResources />
</head>
<body>
...
<r:layoutResources />
</body>
In the /grails-app/views/someDomain/
list.gsp
<head>
...
<r:require modules="application" />
</head>
<body>
...
</body>
report.gsp
<head>
...
<r:require modules="reports" />
</head>
<body>
...
</body>
charts.gsp
<head>
...
<r:require modules="charting" />
</head>
<body>
...
</body>