Render return html into text - python

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.

Related

The value I got from the jQuery is NoneType in django

I want to implement a function that updates the graph and displays the number of updates when the button is pressed.
However, when I try to get the parameter in view.py using jQuery, it returns NoneType instead of the intended value. What is the problem?
Also, I don't know if this is related, but when I use console.log() in a jQuery function, there is no output on the console of the browser developer tools. This doesn't seem to have anything to do with the error-only mode or the filter I entered in Console.
The error is
TypeError at /graph/update_graph
int() argument must be a string, a bytes-like object or a number, not 'NoneType'
Thank you.
Here is the code
views.py
from xml.etree.ElementInclude import include
from django.shortcuts import render
from django.http import JsonResponse
from . import graphdata
def index(request):
fig = graphdata.get_scatter_figure()
plot_fig = fig.to_html(fig, include_plotlyjs=False)
return render(request, 'graph/index.html', {'graph':plot_fig})
def update_graph(request):
graph = graphdata.get_scatter_figure()
grahp_html = graph.to_html(graph, include_plotlyjs=False)
cnt = int(request.POST.get('count')) # <-- This is the error point
cnt += 1
data = {
"graph": grahp_html,
"count": cnt,
}
return JsonResponse(data)
index.html
<!DOCTYPE html>
<html lang="ja">
<head>
<meta charset="utf-8" />
<meta http-equiv="X-UA-Compatible" content="IE=edge,chrome=1" />
<!-- plotly JS Files -->
<script src="https://cdn.plot.ly/plotly-latest.min.js"></script>
<meta content='width=device-width, initial-scale=1.0, shrink-to-fit=no' name='viewport' />
</head>
<body>
<div id="update-num">0</div>
<div id="update-text">update</div>
<form id="graph-update-form" action="{% url 'graph:update_graph' %}" method="POST">
{% csrf_token %}
<button type="submit" id="upadate-bt">update</button>
</form>
<div class="graph" id="scatter-graph">{{ graph| safe }}</div>
<!-- jquery script -->
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<script>
$("#update-graph-from").on("submit", function(e){
e.preventDefault();
// These outputs will not be displayed in the console
console.log('hello');
console.log($("#update-num").text());
$.ajax(
{
url: "{% url 'graph:update_graph' %}",
type: "POST",
data: {
count: $("#update-num").text(),
},
dataType: "json",
}
)
.done(function(response){
$("#update-num").remove();
$("#update-num").prepend(response.count);
});
});
</script>
</body>
</html>
urls.py
from django.urls import path
from . import views
app_name = "graph"
urlpatterns = [
path('', views.index, name='index'),
path('update_graph', views.update_graph, name='update_graph'),
]
You have form with id="graph-update-form" and you are submitting the form with id="update-graph-from". Also since you already set url in your ajax you don't need your action="{% url 'graph:update_graph' %}" and method="POST" in your form. Also you can directly set your ajax response vale you don't need to remove the element so you don't have to prepend. Change your index.html as
<!DOCTYPE html>
<html lang="ja">
<head>
<meta charset="utf-8" />
<meta http-equiv="X-UA-Compatible" content="IE=edge,chrome=1" />
<!-- plotly JS Files -->
<script src="https://cdn.plot.ly/plotly-latest.min.js"></script>
<meta content='width=device-width, initial-scale=1.0, shrink-to-fit=no' name='viewport' />
</head>
<body>
<div id="update-num">0</div>
<div id="update-text">update</div>
<form id="graph-update-form">
{% csrf_token %}
<button type="submit" id="upadate-bt">update</button>
</form>
<div class="graph" id="scatter-graph">{{ graph| safe }}</div>
<!-- jquery script -->
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<script>
$("#graph-update-form").on("submit", function (e) {
e.preventDefault();
// These outputs will not be displayed in the console
console.log('hello');
console.log($("#update-num").text());
$.ajax({
url: "{% url 'update_graph' %}",
type: "POST",
'headers': {
'X-CSRFToken': $('#graph-update-form').find('input[name="csrfmiddlewaretoken"]').val()
},
data: {
count: $("#update-num").text(),
},
dataType: "json",
})
.done(function (response) {
$("#update-num").text(response.count);
});
});

data given in the Ajax is not reaching in the views.py file and hence alert function is not working

I tried to reset password using Ajax in Django.For that, firstly I took email id from input box using a function and send it to views.py file using Ajax.In views.py file,there is a code for receiving email-id using GET method and check whether the email-id is available or not in the table.If available send the email-id back to html file using HttpResponse and display it using alert function.But it does not work properly.Can anyone suggest a solution for this.
HTML file :
<!DOCTYPE html>
<html lang="en">
{% load static %}
<head>
<meta charset="UTF-8">
<title>Index Page</title>
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0/css/bootstrap.min.css" integrity="sha384-Gn5384xqQ1aoWXA+058RXPxPg6fy4IWvTNh0E263XmFcJlSAwiGgFAW/dAiS6JXm" crossorigin="anonymous">
<link href="{% static 'styles/style.css' %}" rel="stylesheet"/>
<script>
function getpass(){
let username=$("#uname").val()
$.ajax({
url : "{% url 'passwordreset' %}",
type : "GET",
data : {username : username},
success :function(data){
alert(data);
}
})
}
</script>
</head>
<body>
<section class="sflog" id="sflog">
<div class="container-fluid">
<div class="row">
<div class="col-12" id="std">
<form method="GET" action="">
{%csrf_token%}
<center>
<h3>Password <span>Reset</span></h3><br><br>
</center>
<div id="result"></div>
<label style="color:white;padding-left:13%;">Enter Your Username</label>
<center>
<input type="text" id="uname" name="username" placeholder="Username" required><br>
</center>
<button type="submit" style="margin-left:12%;" onclick="getpass()" name="login">Submit</button><br><br><br><br>
</form>
</div>
</div>
</div>
</section>
<script src="https://code.jquery.com/jquery-3.2.1.slim.min.js" integrity="sha384-KJ3o2DKtIkvYIK3UENzmM7KCkRr/rE9/Qpg6aAZGJwFDMVNA/GpGFF93hXpG5KkN" crossorigin="anonymous"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.12.9/umd/popper.min.js" integrity="sha384-ApNbgh9B+Y1QKtv3Rn7W3mgPxhU9K/ScQsAP7hUibX39j7fakFPskvXusvfa0b4Q" crossorigin="anonymous"></script>
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0/js/bootstrap.min.js" integrity="sha384-JZR6Spejh4U02d8jOt6vLEHfe/JQGiRRSQQxSfFWpi1MquVdAyjUar5+76PVCmYl" crossorigin="anonymous"></script>
</body>
</html>
urls.py
from django.urls import path
from . import views
urlpatterns=[
path('User/Forgot_Password',views.user_forgot_password,name="ufpassword"),
path('User/Forgot_Password/Reset',views.user_forgot_password_reset,name="passwordreset"),
]
views.py
from django.shortcuts import render,redirect,get_object_or_404
from user.models import clientlogin
from django.http import HttpResponse
def user_forgot_password(request):
return render(request,"forgot_password.html")
def user_forgot_password_reset(request):
if request.method == 'GET':
un = request.GET.get('username')
print(un)
try:
user = get_object_or_404(clientlogin, Username=un)
return HttpResponse(user.Username)
except:
return HttpResponse("No user registered with this Email ID")
else:
return render(request, "forgot_password.html")
First change the order in urls
urlpatterns=[
path('User/Forgot_Password',views.user_forgot_password,name="ufpassword"),
path('User/Forgot_Password/Reset',views.user_forgot_password_reset,name="passwordreset")
]
Because when request arrives, it will match the first always so either edit it to be
re_path('User/Forgot_Password$',views.user_forgot_password,name="ufpassword")
This way your reset URL won't match the forget password.
As some said put JQuery before $ sign.

Vue app doesn't load when served through Python Flask server

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>

Django render_to_string <body><head> tag

I'm my django app I would like to load a static html page into a main template. This static html page is an email template. My goal is to edit this email in my main template. The email html page don't have a view in url.py. I don't use include in main template and I don't want to use iframe. The problem is that I would like to load ALL the html email tag (like
<html>
<head>
<body>
) but when I do the page's render this tag is deleted (or I don't see them in main template...). This is my code:
view.py
def my_view(request):
file_name = "/templates/path/emailtemplate.html"
htmlblock = render_to_string(file_name, {})
return render_to_response('main_template.html', {
'htmlblock': htmlblock,
},
context_instance = RequestContext(request))
main_template.html
<html>
<head>
....
<head>
<body>
<div id="content">
{{htmlblock}}
</div>
</body>
</html>
this is what I would like to have:
<html>
<head>
....
<head>
<body>
<div id="content">
<html>
<head>
....
</head>
<body>
...
</body>
</html>
</div>
</body>
</html>
Is this possible without iframe? Thanks a lot for your help.
EDIT
My goal is to have the
<html>
<head>
<body>
tag into
<div id="content">
where I load the email template.
My goal is to edit this email in my main template.
You can read the template into string by
with open('/templates/path/emailtemplate.html', 'r') as content_file:
content = content_file.read()
You can use the same as a value to an edit field and it will be visible as usual. This can be used as.
return render_to_response('main_template.html', {
'htmlblock': content,
}, context_instance = RequestContext(request))
You can further use the same in edit field as:
<textarea value={{htmlblock}}>
Or render the same normally in
<div id="content">{{htmlblock}}</div>

Post JSON data using Angular.js

This is my first crack at Angular. I'm posting JSON data to an html page using Angular.js. I know I'm missing something but can't seem to get it working. Below is the html. I have a python script posting to the same URL below.
<!doctype html>
<html lang="en" ng-app id="ng-app">
<head>
<title>File Analysis</title>
<script src="js/angular.js"></script>
<script>
var myApp = angular.module('fileAnalysis', []);
myapp.controller('PostsCtrlAjax', function($scope, $http)
{
$http({method: 'POST', url: 'http://test.com'}).success(function(data)
{$scope.posts = data;}) // response data
});
</script>
</head>
<body>
<h1>You should begin to see new files being analyzed!</h1>
<div id="ng-app" ng-app ng-controller="PostsCtrlAjax">
<div ng-repeat="post in posts" >
<h2>
<a href='{{post.url}}'>{{post.title}}</a>
</h2>
<td>
{{post.filename}}
</td>
</div>
</body>
</html>

Categories