I'm following a course online but am stuck, I'm using webpy to create a little website on my localhost server. The CSS and JavaScriptwork perfectly on all pages but one, I'm not sure if it is to do with the regex in the url?
The CSS and Javascript is called on the Mainlayout html page and the page is called under the Navbar with $:page
I use the URL path: '/profile/(.*)/info', 'UserInfo', and '/profile/(.*)', 'UserProfile',
Then define the classes as:
class UserProfile:
def GET(self, user):
login = LoginModel.LoginModel()
user_info = login.get_profile(user)
post_model = Posts.Posts()
posts = post_model.get_user_posts(user)
return render.Profile(posts, user_info)
class UserInfo:
def GET(self, user):
login = LoginModel.LoginModel()
user_info = login.get_profile(user)
return render.Info(user_info)
The CSS and JS are called on the main layout using:
$def with (page)
$var css: static/css/bootstrap.min.css static/css/bootstrap-material-design.min.css static/css/ripples.min.css static/css/jquery-ui.css static/css/custom.css static/css/materialdesignicons.min.css
$var js: static/js/jquery-3.2.1.min.js static/js/bootstrap.min.js static/js/material.min.js static/js/ripples.min.js static/js/scripty.js static/js/ripples.min.js static/js/jquery-ui.min.js static/js/material.min.js
$if self.css:
$for style in self.css.split():
<link rel="stylesheet" type="text/css" href="$style"/>
$if self.js:
$for script in self.js.split()
<script src="$script"></script>
These are the errors I get in the console:
Any tips on where I should look to get this working? I'm not sure what information I need to share for you to have the full picture so please ask if anything else is needed.
Related
In my django project I have a model with a field that contain html code as text:
html_test = models.TextField()
for example in this field could be:
<html>
<header><title>This is title</title></header>
<body>
Hello world
</body>
</html>
I want to retrive this code and render dynamically showing the corresponding html page without create a file or save it on disk.
How can i render an html code in memory for display page and then destroy it?
I'm still not sure what your actual question is. You retrieve the model from the db and return the data to the user, just like anything else. For example, a view might look like this:
def my_view(request, pk):
obj = MyModel.objects.get(pk=pk)
return HttpResponse(obj.html_test)
Using jinja2 as the templating engine,
class YourClassName(generic.TemplateView):
template_name = 'your_template.jinja'
def get_context_data(self, **kwargs):
kwargs['html_data'] = MyModel.objects.get(pk=pk).html_test
return super(YourClassName, self).get_context_data(**kwargs)
In your your_template.jinja
<html>
<header><title>This is title</title></header>
<body>
{{html_data}}
</body>
I have a script which takes uploaded data, munges it together, turns it into a plot (using Bokeh) and then exports it to a directory as JSON.
At some point in the future, a user can hit the right URL and the appropriate plot should be displayed to the user as part of the HTML template.
I can generate the plot. I can save it as JSON. I can get the URL to retrieve it as JSON, but I cannot get the JSON plot to render within the template.
I've had a dig around the Bokeh documentation and examples, but they all seem to use a flask app to serve the pages.
I think I'm on the right track, using views.py to find and return JSON as part of a render() response, and then have Bokeh.embed.embed_items() do the work in the template to make it look right, but it's not working out - everything but the plot is displayed.
1) Create the plot and puts it in the directory for later use (app/results/1)
create plot.py
import os
import json
from django.conf import settings
from bokeh.embed import json_item
from bokeh.plotting import figure
x=[1,2,3,4,5]
y=[0,-1,-2,3,4]
p=figure(title="test_example")
p.line(x, y)
#json_export = json_item(p, "result")
json_export = json_item(p)
with open(os.path.join(settings.RESULTS_DIR,"1", "test.json"), 'w') as fp:
fp.write(json.dumps(json_export))
2) Set up the url
urls.py
urlpatterns=[
path('result/<int:pk>', views.resultdetailview, name='result-detail'),
]
3) Take the request, use the pk to find the plot json and render it all in the appropriate template.
views.py
def resultdetailview(request, pk):
results=str(pk)
with open(os.path.join(settings.RESULTS_DIR, results, "test.json"), 'r') as fp:
#data=json.load(fp)
data=json.loads(fp.read())
#context={'result':data}
#return render(request, 'app/sandbox_detail.html', context)
return render(request=request,
context={'json_object':data, 'resources':CDN.render()})
NB: If I instead use return JsonResponse(data, safe=False) then the url returns the json successfully ...
I think therefore that the issue is in the template.
4) Show the wonderous plot to the user
sandbox_detail.html
<header>
<link rel="stylesheet" href="http://cdn.bokeh.org./bokeh/release/bokeh-0.11.1.min.css" type="text/css" >
<script type="text/javascript" src="http://cdn.bokeh.org./bokeh/release/bokeh-0.11.1.min.js"> </script>
</header>
<h1> Title: Test </h1>
<div>Test</div>
<body>
<div id="result"></div>
<script>
Bokeh.embed.embed_item({{json_object}}, "result");
</script>
</body>
This template renders everything but the 'result' div.
What have I missed?
This is what I see so far:
FIRST: You are mixing 2 methods for injecting plot json data into the page.
According to documentation you can do it using either of these two methods:
1) specify the div directly:
Python: json_data = json.dumps(json_item(p, "myplot"))
JavaScript: Bokeh.embed.embed_item(item);
2) specify the div in embed_item function:
Python: json_data = json.dumps(json_item(p))
JavaScript: Bokeh.embed.embed_item(item, "myplot");
But not both of them at the same time. Could this be the problem?
SECOND: Preferably don't insert Bokeh resources by hand: rather use CDN.render() or INLINE.render() to automatically include all that your script needs:
import json
from bokeh.resources import CDN
return render(request = request,
template_name = 'app/sandbox_detail.html',
context = { json_object = json.loads(json_string),
resources = CDN.render() } )
sandbox_detail.html
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
{{ resources }}
</head>
<body>
<div id="result"></div>
<script>
Bokeh.embed.embed_item({{ json_object }}, "result");
</script>
</body>
</html>
THIRD: Make sure what you embed in the page is json object not a string (see variable naming above)
It helps when you debug your rendered template in your browser's debug tool.
I tried a very similar approach and found one large flaw: My browser noted that it could not find the None object. The reason here is that python stores the empty value as None, while JavaScript expects a null object.
The solution? Python already translates None to null, when you run json.dumps. To keep it that way, read the json string as a string. So instead of your data=json.loads(fp.read()) use data=fp.read().
I'm using Google Books API to integrate with an E-commerce site that I'm developing. The idea is to let the users search for books using a search bar, and then calling the Google API to output the number of books corresponding to the search keyword.
However, I get a 403 Forbidden error after I click submit after entering my query in the form. This is strange, because this never happened when I was testing my application on the localhost. Here's the code for my application:
main.py
class SearchHandler(Handler):
def get(self):
self.render("search.html")
def post(self):
keey = self.request.get('keey')
finaal = "https://www.googleapis.com/books/v1/volumes?q=" + keey + "&key=MY_APP_KEY"
f = urllib2.urlopen(finaal).read()
self.render("jsony.html", finaal = finaal)
app = webapp2.WSGIApplication(('/search', SearchHandler)], debug=True)
search.html
<html>
<head>
<title>Web Mining</title>
</head>
<body>
<form method = "post">
Book Name:<input type = "text" name = "keey">
<input type = "submit">
</form>
</body>
</html>
jsony.html
<html>
<head>
<title>Web Mining</title>
</head>
<body>
<form method = "post">
{{finaal}}
</form>
</body>
Now, the jsony.html is still incomplete. All I'm doing now is displaying the URL which contains the outputted json in it's raw, unprocessed form.
What seems to be causing this 403 error to arise after I deploy my application ?
EDIT 1:
The problem resolves when I remove the following line from my main python file:
f = urllib2.urlopen(finaal).read()
However, I would be needing my API's URL in order to extract data from its source code. What's happening ?
Try adding &country=US to the URL query string.
I copied the screen.css that has the paleblue class shown in the example on the django_tables2 website.
I placed it in my application in the static/css folder and when I call it from my .html it finds it. In the header I placed the following:
<link rel="stylesheet" href="{{ STATIC_URL }}css/screen.css" />
Now, in my tables.py module I have this:
import django_tables2 as tables
class TipPredmetaTable(tables.Table):
class Meta:
model = models.TipPredmeta
attrs = {'class': 'paleblue'}
In my views.py I have this:
def tippredmeta(request):
queryset = TipPredmeta.objects.all()
table = TipPredmetaTable(queryset)
RequestConfig(request).configure(table)
return render_to_response('azuriranje/tabela.html', {"table": table}, context_instance=RequestContext(request))
When I open the page in Mozzila and hit Ctrl+U I can clearly see the following:
<div class="table-container"><table class="paleblue"><thead> <tr>...
My .html is exactly the same as on the django_tables2 website, my STATIC_URL is defined, the staticfiles app is enabled. What am I doing wrong?
Ok, I've figured it out after some more extensive searching through the web and my code. It would seem that me forgetting to put 'django.core.context_processors.static' in the TEMPLATE_CONTEXT_PROCESSOR was the source of my issue.
I just started pyramid and have a problem with loading views. I want to load a view based on a variable fetched from the database like my PHP solution here: rewrite url with htaccess
I've build a script that can do this, but I'm quite sure this is not the right way to do it. I think when I use this in a real site it will get very complicated and messy. Could someone explain how to this properly or point me to an other solution?
My current script:
config.add_route('home', '/')
config.add_route('admin_home', '/admin')
config.add_route('admin_pages', '/admin/pages')
config.add_static_view(name='static', path='website:static')
config.add_route('view_loader', '/*url')
views.py
class ViewLoader(object):
def __init__(self, request):
self.request = request
#view_config(route_name="view_loader", renderer="templates/view_loader.pt")
def view_loader(self):
request = self.request
url = "/%s" % request.matchdict["url"]
page = DBSession.query(Pages).filter_by(url=url).one()
return dict(title=page.title, include=page.template)
view_loader.pt
<!DOCTYPE html>
<html>
<body>
<metal:main use-macro="load: ${include}"></metal:main>
</body>
</html>
Idea of the system:
Admins can create pages in a cms with random url's and have to select a template. The system has to generate these pages.
url = /random/random -> look for template in db -> render template_1
url = /random2/random2 -> look for template in db -> render template_2
So I want to render the template after the class/method is being called to determine what template has to be rendered
I found a more logical approach for my problem with the help of this question Map different URLs to same view. Actually the solution is quite simple I just didn't know it is possible to declare a renderer in add_view()
main.py
pages = DBSession.query(Pages)
for page in pages:
config.add_route(str(page.name), page.url)
if page.template.decode('utf-8') == "home_view":
config.add_view(home_view, route_name=str(page.name), renderer='templates/home.pt')
elif page.template.decode('utf-8') == "detail_view":
config.add_view(home_view, route_name=str(page.name), renderer='templates/detail.pt')
views.py
def home_view(self, request):
return dict(.....)