i need get context in react using django
but i cant do it
this is my code
in my jsx
<h1>{{titulo}}</h1>
<h2>{{ejemplo}}</h2>
in my template:
{% load staticfiles %}
<!DOCTYPE html>
<html>
<head>
<title>Index</title>
</head>
<body >
<div id="app"></div>
<script type="text/javascript" src="{% static 'bundle.js' %}"></script>
</body>
</html>
in my view py:
def registro (request,giro):
reg = 'Registro Normal'
if giro==1:
reg='Registro Especial'
context = {
'ejemplo':'tests',
'titulo':reg
}
return render(request,'home/registro.html',context)
but does not render and wild error appeared :(
Uncaught ReferenceError: titulo is not defined
The Django context is only when the template is rendered on the server. React uses Javascript which means it's rendered on the browser. If you want to use Django variables in your React app, you will need to set those variables in Javascript (making sure to do so before bundle.js is imported).
So your template might look something like this:
{% load staticfiles %}
<!DOCTYPE html>
<html>
<head>
<title>Index</title>
</head>
<body >
<div id="app"></div>
<script type="text/javascript">
/* Put your context vars here. I recommend putting them under
a variable to avoid naming conflicts.
*/
var context = {
titulo: '{{titulo}}',
ejemplo: '{{ejemplo}}'
};
</script>
<script type="text/javascript" src="{% static 'bundle.js' %}"></script>
</body>
</html>
Then in React you can reference context.variable to get the value you need.
Related
Problem: As the title says I am building a django project the base.html extended to homepage.html and works fine, static images appear, but home.css does not works anywhere.
Update
I have switched in the base.html
from this <link rel="stylesheet" href="{% static 'css/home.css' %}">
to this <link href="css/home.css" rel="stylesheet" />
than I have also tried this: <link rel="stylesheet" type="text/css" href="{% static 'css/home.css' %}" />
It deletes a formatting on -s that was caused by another previously used .css that has been deleted since but the formatting sticked on.
I have called this css property thickkk{color: red;}
many places in both base.html and home.html and it still not working.
I have also get the following error message if I inspect the site with/F12/consol/ 127.0.0.1/:1 Refused to apply style from 'http://127.0.0.1:8000/css/home.css' because its MIME type ('text/html') is not a supported stylesheet MIME type, and strict MIME checking is enabled.
Update ERROR message
Refused to apply style from 'http://127.0.0.1:8000/stacic/css/home.css' because its MIME type ('text/html') is not a supported stylesheet MIME type, and strict MIME checking is enabled.
Properties: Python 3.7, Bootstrap 4
settings.py
STATICFILES_DIRS = [os.path.join(BASE_DIR, 'baseprojectfolder/static/')]
STATIC_ROOT = os.path.join(BASE_DIR, 'static')
STATIC_URL = '/static/'
base.html
I have created a base.html that hold the navbar and the footer.
This also has the CSS imported from a static css and also from bootstrap
It finds the static files because it imports the images that are appearing both here and in the home page
<!doctype html>
<html lang="en">
{% load static %}
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no">
<meta name="description" content="xz">
<meta name="author" content="xz">
<link rel="shortcut icon" type="image/png" href="{% static 'favicon.ico' %}"/>
<link rel="icon" href="/docs/4.0/assets/img/favicons/favicon.ico">
<title>Click Helps - BE PART OF THE NEW CREATION</title>
<link rel="canonical" href="https://getbootstrap.com/docs/4.3/examples/carousel/">
<!-- Bootstrap core CSS -->
<link href="/docs/4.3/dist/css/bootstrap.min.css" rel="stylesheet" integrity="sha384-ggOyR0iXCbMQv3Xipma34MD+dH/1fQ784/j6cY/iJTQUOhcWr7x9JvoRxT2MZw1T" crossorigin="anonymous">
<link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.4.1/css/bootstrap.min.css" integrity="sha384-Vkoo8x4CGsO3+Hhxv8T/Q5PaXtkKtu6ug5TOeNV6gBiFeWPGFN9MuhOf23Q9Ifjh" crossorigin="anonymous">
<link rel="stylesheet" href="{% static 'css/home.css' %}">
</head>
....
<!-- Bootstrap core JavaScript ================================================== -->
<!-- Placed at the end of the document so the pages load faster -->
<script src="https://code.jquery.com/jquery-3.3.1.slim.min.js" integrity="sha384-q8i/X+965DzO0rT7abK41JStQIAqVgRVzpbzo5smXKp4YfRvH+8abtTE1Pi6jizo" crossorigin="anonymous"></script>
<script>window.jQuery || document.write('<script src="/docs/4.3/assets/js/vendor/jquery-slim.min.js"><\/script>')</script>
<script src="/docs/4.3/dist/js/bootstrap.bundle.min.js" integrity="sha384-xrRywqdh3PHs8keKZN+8zzc5TX0GRTLCcmivcbNJWm2rs5C8PRhcEn3czEjhAO9o" crossorigin="anonymous"></script>
<!-- I have placed in the followring 3 line from bootstrap to make JS work -->
<script src="https://code.jquery.com/jquery-3.4.1.slim.min.js" integrity="sha384-J6qa4849blE2+poT4WnyKhv5vZF5SrPo0iEjwBvKU7imGFAV0wwj1yYfoRSJoZ+n" crossorigin="anonymous"></script>
<script src="https://cdn.jsdelivr.net/npm/popper.js#1.16.0/dist/umd/popper.min.js" integrity="sha384-Q6E9RHvbIyZFJoft+2mJbHaEWldlvI9IOYy5n3zV9zzTtmI3UksdQRVvoxMfooAo" crossorigin="anonymous"></script>
<script src="https://stackpath.bootstrapcdn.com/bootstrap/4.4.1/js/bootstrap.min.js" integrity="sha384-wfSDF2E50Y2D1uUdj0O3uMBJnjuUD4Ih7YwaYd1iqfktj0Uod8GCExl3Og8ifwB6" crossorigin="anonymous"></script>
</body>
</html>
home.html
I have used the center CSS property I have created
{% extends 'applicaonfolderofmine/templates/base.html' %}
{% load static %}
{% block content %}
<main>
<body>
<div class="container">
<h1 id="about" class="center" >About</h1>
...
home.css
it can be found in "django-project/certainapplication/static/css/home.css"
.center {
margin: auto;
width: 60%;
padding: 10px;
}
Error messages in terminal
Not Found: /docs/4.3/dist/css/bootstrap.min.css
[22/Feb/2020 15:55:26] "GET /docs/4.3/dist/css/bootstrap.min.css HTTP/1.1" 404 2494
Not Found: /docs/4.3/dist/js/bootstrap.bundle.min.js
[22/Feb/2020 16:24:29] "GET /docs/4.3/dist/js/bootstrap.bundle.min.js HTTP/1.1" 404 2509
Not Found: /docs/4.3/dist/js/bootstrap.bundle.min.js
[22/Feb/2020 16:24:29] "GET /docs/4.3/dist/js/bootstrap.bundle.min.js HTTP/1.1" 404 2509
I have read the following articles but they haven't answered my question:
css for base template in django
Adding css file after all extensions css files
Django UserProfile extension
Background from CSS not working in Base.html
Django mptt, extends "base.html"
{ % extends parent _ template|default:"base.html" % } vs {% extends "base.html" %} in Django?
Django templates extending and CSS
How does Django's extends work?
As you have STATICFILES_DIRS remove STATIC_ROOT then type python manage.py collectstatic, then yes, then run your server again.
The server should respond with the correct MIME Type for JSONP application/javascript and your request should tell jQuery you are loading JSONP dataType: 'jsonp'
Please see this answer for further details ! You can also have a look a this one as it explains why loading .js file with text/plain won't work.
Disable Chrome strict MIME type checking
I have a simple "hello world" VueJS app I'm trying to get working:
<!doctype html>
<html>
<head>
<meta http-equiv="content-type" content="text/html; charset=utf-8" />
<script type="text/javascript" src="https://unpkg.com/vue"></script>
</head>
<body>
<div id="app">
Message: {{ message }}
</div>
<script>
var vm = new Vue({
el: "#app",
data: {
message: "Hello, world"
}
});
</script>
</body>
</html>
When I load this file in the browser, off my local disk (ie: file:///home/user/vue-project/index.html), it loads and "Hello, world" is displayed.
However, if I try to take the same file and serve it through the python flask development server, or through gunicorn, {{message}} renders blank.
Does anyone know what might be causing that to happen?
flask renders its variables with jinja2 which uses {{ variable }} as its parsing delimiter
render("mytemplate.html",message="Hello") would replace all {{ message }} blocks with "Hello" before any javascript is handled ... since you dont define message it is simply an empty string... you will need to configure vue to use alternative delimiters (I use [[ message ]])
<!doctype html>
<html>
<head>
<meta http-equiv="content-type" content="text/html; charset=utf-8" />
<script type="text/javascript" src="https://unpkg.com/vue"></script>
</head>
<body>
<div id="app">
Message: [[ message ]]
</div>
<script>
var vm = new Vue({
el: "#app",
delimiters : ['[[', ']]'],
data: {
message: "Hello, world"
}
});
</script>
</body>
</html>
I have created documentation for my Django app using apidoc library.
It creates docs using angular. App is running on Heroku.
Docs are working nicely when I open index.html file, but I cannot open them via http://localhost:5000/docs.
Firstly I got this error:
"Variables and attributes may not begin with underscores: '__' "
, which I was able to bypass by putting {% verbatim %} and {% endverbatim %} into the index.html file. (Which I'm not very happy with in the first place and would like to do it some other way).
Then the page is stuck on the loading screen, but when I open it in Chrome I have the following error:
"Uncaught SyntaxError: Unexpected token <" in polyfill.js:1 and
require.min.js:1
And also 3 warnings:
"Resource interpreted as Stylesheet but transferred with MIME type
text/html"
in vendor/bootstrap.min.cs, vendor/prettify.css and css/style.css
We are using apidocs also in other project with Node where it works perfectly, so I think it's an issue with Django. Since the documentation is generated automatically, I would prefer to introduce changes into the app, not docs.
I tried it on Chrome and Safari.
My questions
1. What can I do to make it work?
2. How can I make Django compatible with Angular without putting {%verbatim%} tags into index.html?
Here is my controller:
from django.shortcuts import render
def show_docs(request):
return render(request, 'index.html')
and url_pattern:
from django.conf.urls import include, url
from django.contrib import admin
admin.autodiscover()
import my_app.controller
from django.views.decorators.csrf import csrf_exempt
urlpatterns = [
url(r'^docs/', my_app.controller.show_docs),
]
index.html head:
<head>
<meta http-equiv="X-UA-Compatible" content="IE=edge" />
<title>Loading...</title>
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<link href="vendor/bootstrap.min.css" rel="stylesheet" media="screen">
<link href="vendor/prettify.css" rel="stylesheet" media="screen">
<link href="css/style.css" rel="stylesheet" media="screen, print">
<link href="img/favicon.ico" rel="icon" type="image/x-icon">
<link href="css/apidoccustom.css" rel="stylesheet" media="screen, print">
<script src="vendor/polyfill.js"></script>
</head>
edit:
Thanks to answer from hubert, I was able to find the source of the problem.
It turns out, that Django doesn't work that good with RequireJS, which is used by api docs.
I had to add the following changes to the generated code to make it work:
Points 1-4 are for index.html, point 5, 6 are for main.js:
Add this line above tag:
{% load static %}
Add "{% static" + " %}" tags to all tags so it looks like this:
<link href="{% static "vendor/bootstrap.min.css" %}" rel="stylesheet" media="screen">
Add the same static tags to tags with polyfill.js and require.min.js:
<script src="{% static "vendor/polyfill.js" %}"></script>
<script data-main="{% static "main.js" %}" src="{% static "vendor/require.min.js" %}"></script>
Add {% verbatim %} at the beginning of and {% endverbatim %} at the end of , BUT BEFORE with require.min.js!
In main.js add following lines to paths at the beginning of the file:
apiProject: './api_project.js',
apiData: './api_data.js',
Change lines:
'./api_project.js',
'./api_data.js',
to:
'api_project',
'api_data',
From this two errors:
"Uncaught SyntaxError: Unexpected token <" in polyfill.js:1 and require.min.js:1
"Resource interpreted as Stylesheet but transferred with MIME type text/html"
I would assume that there is something wrong with loading your static files. Probably you have 404 or 500 on them and django loads then default route.
Check if you have correct routing for static files.
This is urls.py
from django.conf.urls import url
from . import views
urlpatterns = [
url(r'^$', views.login_page, name='login_page'),
]
my views.py like this
def login_page(request):
return render(request, 'mileage/login_page.html', {})
this is my html code
<!DOCTYPE html>
<html>
<head>
<meta name="viewport" content="user-scalable=no, initial-scale=1.0, maximum-scale=1.0, minimum-scale=1.0, width=device-width" >
<meta charset="UTF-8">
<title>Test</title>
<link rel="stylesheet" href="{% static 'css/style.css' %}">
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.1.0/jquery.min.js">
</script>
</head>
<body bgcolor="#4599e8">
<div class="title"><span><h1>Test</h1></span></div>
<div class="home_password">
<div class="password"><input type="password" name="password" placeholder="Password"></div>
<div class="button"><button>OK</button></div>
</div>
</body>
</html>
And start server, but my localhost:8080/ shows only html text not page.
Using Chrome Developer Console, I checked element.
<html>
<head></head>
<body>
<pre style="word-wrap: break-word; white-space: pre-wrap;">
"
my html code here.
"
</pre>
</body>
</html>
I don't know how to solve it.
Who is inserting all your html code inside the pre tag is your browser because it probably receives a Content-type: text/plain header with the response and it thinks you want to see the html code instead of the rendered webpage.
Try making a test using:
render(request, 'mileage/login_page.html', {}, content_type='text/html')
If it works, set the DEFAULT_CONTENT_TYPE constant to 'text/html' in your settings.
DEFAULT_CONTENT_TYPE
Default: 'text/html'
Default content type to use for all HttpResponse objects, if a MIME
type isn’t manually specified. Used with DEFAULT_CHARSET to construct
the Content-Type header.
Probably an environment variable is messing you up with this, It's weird that it has a default 'text/plain' content type set.
So with flask I know that I can add CSS with
<link ... href="{{ url_for('static', filename='stylesheets/style.css') }}" />
but if I am adding a google font which usually in HTML looks like
<link href='http://fonts.googleapis.com/css?family=PT+Sans:400,700' rel='stylesheet' type='text/css'>
what do I need to edit/add for it to work with Flask?
Add the google font link to your index.html or any page that you want like this:
{% extends "base.html" %}
{% import "bootstrap/wtf.html" as wtf %}
{% block styles %}
{{ super() }}
<link rel="stylesheet" href="{{ url_for('static', filename= 'mystyle.css') }}">
<link href='http://fonts.googleapis.com/css?family=Open+Sans+Condensed:300' rel='stylesheet' type='text/css'>
{% endblock %}
Then, add the CSS font statement to your custom CSS file (mine is static/mysyle.css) :
body {
font-family: 'Open Sans Condensed', sans-serif;`
}
You can't use static here like you would normally for a link to a resource on the webserver. Your link is still essentially static but not related to anything you are serving. So you either put the Google font link directly in the HTML template, or as a variable expanding to the full link (which would be convenient if you aren't using the same header template everywhere and may change the font later).