How to add custom view in django adminlte? - json

I created an environment using pycharm & installed adminlte by git clone from https://github.com/app-generator/django-dashboard-adminlte.git. And installed adminlte3 , django3.1 & all requirements. Then run python manage.py runserver and registered a new user & was able to login ,view all pages, added new link to a html page. But I am unable to add view with jsonresponse to a button click on new page, geting Error 500 - Server Error.
My new html page is
{% extends "layouts/base.html" %}
{% block title %} Layout Boxed {% endblock %}
<!-- Element injected in the BODY element -->
{% block body_class %} sidebar-mini layout-boxed {% endblock body_class %}
<!-- Specific Page CSS goes HERE -->
{% block stylesheets %}
<!-- Google Font: Source Sans Pro -->
<link rel="stylesheet" href="https://fonts.googleapis.com/css?family=Source+Sans+Pro:300,400,400i,700&display=fallback">
<!-- Font Awesome -->
<link rel="stylesheet" href="/static/assets/plugins/fontawesome-free/css/all.min.css">
<!-- Theme style -->
<link rel="stylesheet" href="/static/assets/css/adminlte.min.css">
<link rel="stylesheet" href="/static/assets/css/mapstyle.css">
<link rel="stylesheet" href="/static/assets/js/pages/gis/dist/map.css">
<style>
.map {
margin: 0;
padding: 0;
width: 900px;
height: 500px;
background:white !important;
border:1px solid #ccc;
}
</style>
{% endblock stylesheets %}
{% block content %}
<div class="content-wrapper">
<div id="lyrDiv"></div>
<div id="map" class="map"></div>
<button id="search">Search</button>
</div>
{% endblock content %}
<!-- Specific Page JS goes HERE -->
{% block javascripts %}
<!-- jQuery -->
<script src="/static/assets/plugins/jquery/jquery.min.js"></script>
<!-- Bootstrap 4 -->
<script src="/static/assets/plugins/bootstrap/js/bootstrap.bundle.min.js"></script>
<!-- AdminLTE App -->
<script src="/static/assets/js/adminlte.min.js"></script>
<!-- AdminLTE for demo purposes -->
<script src="/static/assets/js/demo.js"></script>
<script src="/static/assets/js/pages/map.js"></script>
<script src="/static/assets/js/pages/search.js"></script>
{% endblock javascripts %}
search.js
$( "#search" ).click(function() {
$.get('/search/',{'csrfmiddlewaretoken':csrftoken},function(data){
alert(data); // here getting Error 500 - Server Error
});
});
I added below line to /django-dashboard-adminlte/app/urls.py
re_path(r'^search/$', search.spatial_srch, name='search'),
and search.py
from app.models import *
from django.views.decorators.csrf import csrf_exempt
from django.http import JsonResponse
#csrf_exempt
def spatial_srch(request):
data= Demotable.objects.all()
searchArr = []
output = {}
for c in data:
searchArr.append({'type': 'Feature', 'properties': {'id':c.id,'name': str(c.name)},'geometry': {'type': 'Point', 'coordinates': [c.the_geom.x, c.the_geom.y]}})
output = {'type': 'FeatureCollection', 'features': searchArr}
return JsonResponse(output)
When I click on the 'Serach' button the request is not going to the view search.py What is wrong in my code ? what configuration did I miss?
The post shows
The Error 500 shows only adminlte Error page. Nothing more

The problem is in the (not so nice) way they generate the error. It's anti-pattern hell there, but in short it means there's an except thrown in either:
finding the template
loading the template
or rendering the template
and they catch it and don't let you see what happened. Not very nice code and you're have to modify that file to even begin debugging it:
#login_required(login_url="/login/")
def pages(request):
context = {}
# All resource paths end in .html.
# Pick out the html file name from the url. And load that template.
try:
load_template = request.path.split('/')[-1]
html_template = loader.get_template( load_template )
return HttpResponse(html_template.render(context, request))
except template.TemplateDoesNotExist:
html_template = loader.get_template( 'page-404.html' )
return HttpResponse(html_template.render(context, request))
# Remove or comment these lines:
#except:
#
# html_template = loader.get_template( 'page-500.html' )
# return HttpResponse(html_template.render(context, request))
Also I'm not sure this the specific spot where the error is generated, they might be doing similar things in other places.
Edit
This is very .... unprofessional code:
# Matches any html file
re_path(r'^.*\.*', views.pages, name='pages'),
No, it doesn't not match any "html" file - it matches everything cause they don't get regular expressions:
^ - start of string
.* - anything or nothing
\.* - >>>zero<<< or more dots
Result: \.* is ignored as it is irrelevant so it matches everything and if you placed your re_path below it, it will never be consulted, because Django uses first match wins approach.
So your url matches theirs, which then routes it to pages view:
load_template = request.path.split('/')[-1]
Since request.path is '/search/', '/search/'.split('/')[-1] gives the empty string and that creates your problem.
I highly suggest fixing their url path:
# Matches any html file
re_path(r'\.html$', views.pages, name='pages'),
Or put your re_path above theirs.

Related

Can I use Rust / Yew / Trunk to generate just a DOM node and script for use in HTML templates?

TLDR
Total n00b with rust, yew and trunk.
I want to find out how to rust, yew and trunk to build an HTML file containing just one DOM node, not a whole HTML page.
Background
Day-to-day, I use Django, the python web framework. Its admin console uses HTML template rendering, and an example of a template might look like this:
{% extends 'django_twined/question_changeform.html' %}
{% block object-tools-items %}
{% if show_set_active %}
<li>Set active</li>
{% endif %}
{{ block.super }}
{% endblock %}
Where in this example the {% %} and {{ }} get evaluated at render time into a valid HTML structure (from other template files), and the <li> is an extra node that gets added to the DOM.
Instead of a vanilla li element, I want to build a complex DOM node using Rust/Yew/Trunk. Then I can include the resulting head and body elements file in a django template, something like:
{% extends 'django_twined/question_changeform.html' %}
{% block head %}
{{ block.super }}
<!-- Include the scripts generated by trunk build -->
{% include 'my-dom-node-head.html' %}
{% endblock %}
{% block object-tools-items %}
<!-- Include the elements generated by trunk build -->
{% include 'my-dom-node-body.html' %}
{{ block.super }}
{% endblock %}
Where I'm at
I've used the yew starter app to get myself to an app. The input index.html is:
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8" />
<title>Yew App</title>
</head>
</html>
And the main.rs file looks like:
use yew::prelude::*;
enum Msg {
AddOne,
}
struct Model {
value: i64,
}
impl Component for Model {
type Message = Msg;
type Properties = ();
fn create(_ctx: &Context<Self>) -> Self {
Self {
value: 0,
}
}
fn update(&mut self, _ctx: &Context<Self>, msg: Self::Message) -> bool {
match msg {
Msg::AddOne => {
self.value += 1;
// the value has changed so we need to
// re-render for it to appear on the page
true
}
}
}
fn view(&self, ctx: &Context<Self>) -> Html {
// This gives us a component's "`Scope`" which allows us to send messages, etc to the component.
let link = ctx.link();
html! {
<div>
<button onclick={link.callback(|_| Msg::AddOne)}>{ "+1" }</button>
<p>{ self.value }</p>
</div>
}
}
}
fn main() {
yew::start_app::<Model>();
}
After trunk build, the output index.html looks like:
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8" />
<title>Yew App</title>
<link
rel="preload"
href="/yew-app-caccf6c60742c530_bg.wasm"
as="fetch"
type="application/wasm"
crossorigin=""
/>
<link rel="modulepreload" href="/yew-app-caccf6c60742c530.js" />
</head>
<body>
<script type="module">
import init from "/yew-app-caccf6c60742c530.js";
init("/yew-app-caccf6c60742c530_bg.wasm");
</script>
</body>
</html>
Where next?
So basically I need to get the <link> and <script> elements added by trunk build and put them into my template.
What should I do next? Would you suggest I try to:
Get trunk build --filehash false to output deterministic .js and .wasm file names without the hash (caccf6c60742c530 in this case) so that I can directly write the includes into my template (I'm concerned this will cause me development problems down the road)?
Get trunk build to output separate head link and body script?
Post-process the output index.html to extract the inserted scripts?
Alter main.rs in some way to output only what I need/want?

Why is Flask not loading images the second time I render a template?

I have made a ML model which I am deploying in a website using Flask. This is the code for it:
main.py
#imports
app = Flask(__name__)
def check(url):
#function to check whether the URL entered by user is Phishing or not and return the result
#app.route('/')
def home():
return render_template("home.html") #renders homepage template
#app.route('/phish/<url>')
def phish(url):
for i in range(0,len(url)):
if url[i]=="$":
url = url[:i]+"/"+url[i+1:] #changing url back to original
return render_template("phish.html", url=url)
#app.route('/safe/<url>')
def safe(url):
for i in range(0,len(url)):
if url[i]=="$":
url = url[:i]+"/"+url[i+1:] #changing url back to original
return render_template("safe.html", url=url)
#app.route('/', methods=['POST'])
def results():
url = request.form['url']
result = check(url)
for i in range(0,len(url)):
if url[i]=="/":
url = url[:i]+"$"+url[i+1:] #changing "//" to "$$"
if result==1 :
return redirect(url_for("phish", url=url))
else :
return redirect(url_for("safe", url=url))
if __name__ == '__main__':
app.run()
home.html
<!DOCTYPE html>
<html lang="en">
<head>
<!-- bunch of meta tags -->
<title>PhishLearn</title>
<link href="{{ url_for('static', filename='css/bootstrap.css') }}" rel="stylesheet">
<link href="{{ url_for('static', filename='css/main.css') }}" rel="stylesheet"> <!-- for loading
css -->
</head>
<body>
<!-- body code -->
<script src="https://code.jquery.com/jquery-1.10.2.min.js"></script>
<script src="static/js/bootstrap.min.js"></script>
</body>
</html>
The code for phish.html and safe.html is also exactly same except for some changes in the body part.
Now when I initially run my main.py file the home page is loaded perfectly. But when I input a URL and click submit the page that is then rendered according to the result (phish or safe) does not display any image. Here are the screenshots of the pages:
Homepage
Result Page
As you can see when safe.html is rendered it does not shows any images. Can anyone tell me why this is happening and how to solve this issue?
I just use the src attribute of img tag to specify the path of file. Since all my html resources (css, js, images, etc.) are inside the static folder so I write src = "static/img/image-name.jpg"
That's your problem (as I kind of guessed).
When the URL in your browser is /phish/foople.blarp.quux, then static/img/image-name.jpg relative to that path is /phish/foople.blarp.quux/static/img/image-name.jpg which obviously 404s.
You need to
use the {% url_for("static", filename=...) %} form so Flask will deal with forming the correct static URL,
or alternately but less preferably (since changing the static files' root path will then require you to edit every template you have) use an absolute path /static/img/image-name.jpg.
or if you feel like using esoteric and often-forgot-about HTML features, set <base> and never worry about relative paths, but really please don't do that.

Why can't I post data to the flask server using ajax? nothing gets printed out

#app.route('/')
def index():
users = [[1],[2],[3]]
return render_template('index.html', users=users)
#app.route('/update', methods=['GET', 'POST'])
def update():
print(' post received ')
if request.method == 'POST':
print(request.form['idval']
return jsonify({'result': 'success'})
and this is my simple html
{% block body %}
<body>
{% for user in users %}
<td id='position{{user[0]}}' class='updateposition'></td>
<td id='amount{{user[0]}}' class='updateamount'></td>
{% endfor %}
<script src="http://code.jquery.com/jquery.js"></script>
<script src="http://maxcdn.bootstrapcdn.com/bootstrap/3.2.0/js/bootstrap.min.js"></script>
<script src="{{ url_for('static', filename='app.js') }}"></script>
</body>
{% endblock %}
and here's my app.js file within static folder which contains the jquery
$(document).ready(function() {
setInterval(ajaxCall, 1000);
function ajaxCall(){
var positionIds = Array.prototype.slice.call(document.querySelectorAll('.updatecurrposition')).map(function ( element ) { return element.id;});
var amountIds = Array.prototype.slice.call(document.querySelectorAll('.updatepositionamount')).map(function ( element ) {return element.id;});
console.log(positionIds[0])
for (i = 0; i < positionIds.length; i++){
req = $.ajax({
url : '/update',
type : 'POST',
data : {idval : positionIds[i]}
});
}
}
and this example was taken from
https://github.com/PrettyPrinted/youtube_video_code/tree/master/2017/03/27/Using%20jQuery%20to%20Update%20a%20Page%20Without%20Refresh%20(Part%201%20of%202)/ajax_without_update
I've literally copied every single tutorials online and tried to implement it in my own (and most of the tutorials themselves fail in my computer for some reason)
and it just seems it can't get the data. I get a proper initial 200 response to get the html template but when the POST request does work, it only shows 304 redirect message, but nothing gets printed in the console
this perhaps seems to be the reason when I try to update the value upon receiving the data from the flask server, nothing happens. i.e.
req.done(function(data){
$('#'+positionIds[i]).text(data.result);
});
adding this right after req = $.ajax seems to change nothing
Does changing the td tags to something like p work? From tests I think that empty td tags aren't generated. I changed the tags and it was printing (to the console) successfully.

Slim 3 not rendering assets

So I'm trying to render my global stylesheet but I am getting an error
[Error] Did not parse stylesheet at 'http://localhost:8888/css/app.css' because non CSS MIME types are not allowed in strict mode.
Here is my code:
app.twig
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>App</title>
<link href="https://fonts.googleapis.com/css?family=Playfair+Display" rel="stylesheet">
<link rel="stylesheet" href="{{ base_url() }}/css/app.css">
</head>
<body>
{% block content %}{% endblock %}
</body>
</html>
index.twig
{% extends 'app.twig' %}
{% block content %}
Hello from {{ appName }}!
{% endblock %}
app.css
* { box-sizing: border-box; }
html, body {
font-family: 'Playfair Display', serif;
background: yellow;
}
As you can see in my structure the file is there screenshot
I've been looking to resolve this issue but can't see to find the fix, any help is appreciated.
You should configure your web server to parse and send the CSS file directly.
If you're using the built-in PHP web server, then add this to the top of index.php:
if (PHP_SAPI == 'cli-server') {
$_SERVER['SCRIPT_NAME'] = basename(__FILE__);
// To help the built-in PHP dev server, check if the request was actually for
// something which should probably be served as a static file
$url = parse_url($_SERVER['REQUEST_URI']);
$file = __DIR__ . $url['path'];
if (is_file($file)) {
return false;
}
}
If you're using Apache or Nginx, then look at https://www.slimframework.com/docs/start/web-servers.html

How to get rid of "%20" code in URLs (django)

Am working with django 1.3 and doing some template inheritance. My /static/ settings path seems to have problems once I leave the home page. Issue is, when I load home.html which inherits from base.html, the CSS and Image links work okay. But once I go to an extra URL (in this case vehicle.html), the css and image get lost with the error below:
console error
"GET /static/%20/static/images/logo_2.jpg HTTP/1.1" 404 1771
"GET /static/%20/static/css/default.css HTTP/1.1" 404 1765
view page source
<link rel="stylesheet" type="text/css" href="/static/ /static/css/default.css">
<link rel="stylesheet" type="text/css" href="/static/ /static/css/default.css">
It looks like some space is appearing from somewhere. Also, from the vehilce.html file, the page source shows that its adding an extra /static/ to the url plust the space. Where could I be going wrong? See below for my documents:
settings.py
STATIC_ROOT = 'D:/dev/workspace/vehicle_request/vehicle_request/mvmanager/static/'
STATIC_URL = '/static/'
urls.py
urlpatterns = patterns('',
url(r'^$', home_page),
(r'^admin/', include(admin.site.urls)),
(r'^media/(?P<path>.*)$', 'django.views.static.serve',{'document_root': settings.MEDIA_ROOT}), #Not in use in my code yet
(r'^static/(?P<path>.*)$', 'django.views.static.serve',{'document_root': settings.STATIC_ROOT}),
(r'^vehicle/', vehicle),
(r'^driver/', driver),
base.html
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN">
<html lang="en">
<head>
<link rel="stylesheet" type="text/css" href="{{STATIC_URL}}/static/css/default.css">
<title>{% block title %}{% endblock %}</title>
</head>
<body>
<header>
<a href="http://localhost:8000" title="Home Page">
<img alt="logo2:" src="{{ STATIC_URL }}/static/images/logo_2.jpg"
style="float:left; margin:5px" height="100"; border=none"></a><br><br>
<h1>Vehicle Request System <span class="version">(Version 0.1 beta)</span></h1>
</header>
<hr style="clear: left">
<hr>
</body>
</html>
vehicle.html
{% extends "base.html" %}
{% block title %}Vehicle Registration{% endblock %}
{% block content %}
<html>
<head></head>
<body></body>
</html>
{% endblock %}
Thanks.
Edits
1. I've changed the stati in href="{{STATIC_URL}} /static/css/default.css"> to read static as that is how it is in my code. I must have backspaced by mistake while posting. Moving on however,
2. When I change {{STATIC_url}} /Static to {{STATIC_URL}}/Static ie. I remove the space between those two words -as suggested by #sarnold below-, home.html works as usual but vehicle.html still doesn't load the css and the image and it spews the error below in the console:
File "c:\Python27\lib\site-packages\django\core\files\storage.py", line 234, in path
raise SuspiciousOperation("Attempted access to '%s' denied." % name)
SuspiciousOperation: Attempted access to '\static\images\logo_2.jpg' denied.
[10/Feb/2012 06:11:55] "GET /static//static/images/logo_2.jpg HTTP/1.1" 500 1731
File "c:\Python27\lib\site-packages\django\core\files\storage.py", line 234, in path
raise SuspiciousOperation("Attempted access to '%s' denied." % name)
SuspiciousOperation: Attempted access to '\static\css\default.css' denied.
[10/Feb/2012 06:23:29] "GET /static//static/images/logo_2.jpg HTTP/1.1" 500 1731
3. When I combine #sarnold and #cptphil suggestions, vehicle.html loads perfectly the css and the image. home.html however fails. See the changes to base.html below:
base.html (edited to look like this)
<link rel="stylesheet" type="text/css" href="{{STATIC_URL}}css/default.css">
<img alt="logo2:" src="{{STATIC_URL}}images/logo_2.jpg"
home.html now doesnt' work! (viewing page source)
<link rel="stylesheet" type="text/css" href="css/default.css">
<img alt="logo2:" src="images/logo_2.jpg"
vehicle.html now works (viewing page source)
<link rel="stylesheet" type="text/css" href="/static/css/default.css">
<img alt="logo2:" src="/static/images/logo_2.jpg"
And this is how the home.html looks like in raw form
{% extends "base.html" %}
{% block title %}GEL: Vehicle Request System{% endblock %}
{% block content %}
{% endblock %}
I believe the template engine is doing what you are asking it to do.
href="{{STATIC_URL}} /stati/css/default.css"
correctly translates to
/static/ /stati/css/default.css
Try
href="{{STATIC_URL}}css/default.css"
in base.html if what you are after is
/static/css/default.css
Can't account for why home.html would work correctly though.
It looks to me like you added the spaces manually to base.html:
<link rel="stylesheet" type="text/css" href="{{STATIC_URL}} /stati/css/defau...
<img alt="logo2:" src="{{ STATIC_URL }} /static/imag....
Take out the space before /stati/css and /static/imag and see if the problem goes away.
space = %20. Be sure to omit space from your url...
like : <script src="{% static " js/dashboard/salesPieChart.js" %}"></script>
To: <script src="{% static "js/dashboard/salesPieChart.js" %}"></script>