Pylons + Mako -- Access POST data from templates - python

How can I access my request.params post data from my Mako template with Pylons?

Same as in the controller.
${request.params['my_param']}
or preferably:
${request.params.get('my_param', '')}

Related

Django forms in ReactJs

Is there any way I can use Django forms inside a ReactJS script, like include {{ form }} in the JSX file?
I have a view which displays a from and it is rendered using React. When I load this page from one page the data in these fields should be empty, but when I hit this view from another page I want date to be prefilled in this form. I know how to do this using Django forms and form views, but I am clueless where to bring in React.
The {{ form }} statement is relative to Django template. Django templates responsible for rendering HTML and so do React, so you don't have to mix the two together.
What you probably want to do is to use the Django form validation mechanism server side, let React render the form client-side. In your Django view, simply return a JSON object that you can use in your React code to initialize your form component.

Django REST API with multiple representations/formats

I'm new in web dev and I'm trying for a project to develop a Restful web api and a website. I'm using Django framework and following tutos, I always see html files as static and the different views rendering an html template. This way of doing seems to me as backend and frontend are not much separated. Is it possible to have backend only developed in Django ?
edit:
I have actually a problem more specific. I having this app (records) with a view having "patient_list" using Response class from REST framework that renders some data and an html template like this:
def patient_list(request):
"""
List all records, or create a new .
"""
if request.method == 'GET':
#data = Patient.objects.all()
data= Patient.objects.all()
#serializer = PatientSerializer(data, many=True)
#return JSONResponse(serializer.data)
return Response({'patients': data}, template_name='records.html')
in my urls.py I have:
url(r'^records/$', views.patient_list),
and here I'm a little confused. Suppose one called this /records, so patient_list is called and will response with an html page. From what I understood (maybe wrong), a restful API should renders data in a standard view so that it can be used from any "frontend" (html pages or mobile app). Is this statement correct ? am I doing it wrong using Response with an html template ?
With Vanilla Django
Of course it's possible, and without any additional libraries to Django.
E.g. You can define a Django view that returns JSON data instead of rendering it into a HTML template server-side. Effectively making an API instead of a "website".
Here's an example with a class-based view that accepts GET requests and returns some JSON data with JsonResponse
from django.views.generic import View
from django.http import JsonResponse
class MyView(View):
def get(self, request):
my_data = {'something': 'some value'}
return JsonResponse(my_data, mimetype='application/json')
As you can see, you don't have to use the HTML rendering facilities in Django, they're there only if you want to use them.
With REST libraries
And of course there is a host of libraries to build RESTful APIs with Django, like Django REST Framework and Tastypie
Multiple representations and content negotiation
Content negotiation is the process of selecting one of multiple possible representations to return to a client, based on client or server preferences.
You can support more than one format in your REST API. E.g. you can support both HTML and JSON formats. There are various ways to do this:
You may use a GET param ?format=JSON (and have it default to HTML e.g.)
You may use Accept headers
You may have two URLs /records.html and /records.json (the format suffix method)
More on this topic in DRF's documentation
E.g. if you were to implement the first method with the GET params you could modify your code this way:
if request.method == 'GET':
data = Patient.objects.all()
format = request.GET.get('format', None)
if format == 'JSON':
serializer = PatientSerializer(data, many=True)
return JSONResponse(serializer.data)
else:
# Return HTML format by default
return Response({'patients': data}, template_name='records.html')

How can I use a Jinja2 template inside a Python program?

I have one python script which I want to execute as a daily cron job to send emails to all users. Currently I have hard-coded the html inside the script and it looks dirty. I have read the docs, but I haven't figured out how can I render the template within my script.
Is there any way that I can have the separate html file with placeholders which I can use python to populate and then send as the email's body?
I want something like this:
mydict = {}
template = '/templates/email.j2'
fillTemplate(mydict)
html = getHtml(filledTemplate)
I am going to expand on #Mauro's answer. You would move all of the email HTML and/or text into a template file(s). Then use the Jinja API to read the template in from the file; finally, you would render the template by providing the variables that are in the template.
# copied directly from the docs
from jinja2 import Environment, PackageLoader
env = Environment(loader=PackageLoader('yourapplication', 'templates'))
template = env.get_template('mytemplate.html')
print template.render(the='variables', go='here')
This is a link to an example of using the API with the template.
I was looking to do the same thing using Jinja within the Flask framework. Here's an example borrowed from Miguel Grinberg's Flask tutorial:
from flask import render_template
from flask.ext.mail import Message
from app import mail
subject = 'Test Email'
sender = 'alice#example.com'
recipients = ['bob#example.com']
msg = Message(subject, sender=sender, recipients=recipients)
msg.body = render_template('emails/test.txt', name='Bob')
msg.html = render_template('emails/test.html', name='Bob')
mail.send(msg)
It assumes something like the following templates:
templates/emails/test.txt
Hi {{ name }},
This is just a test.
templates/emails/test.html
<p>Hi {{ name }},</p>
<p>This is just a test.</p>
You can use Jinja2, a template language for Python. It has template inheritance feature. Look at this example from official docs.

Is there feature in Pyramid to specify a route in the template like Django templates?

For example in Django if I have a url named 'home' then I can put {% url home %} in the template and it will navigate to that url. I couldn't find anything specific in the Pyramid docs so I am looking to tou Stack Overflow.
Thanks
The brackets depend on the templating engine you are using, but request.route_url('home') is the Python code you need inside.
For example, in your desired template file:
jinja2--> {{ request.route_url('home') }}
mako/chameleon--> ${ request.route_url('home') }
If your route definition includes pattern matching, such as config.add_route('sometestpage', '/test/{pagename}'), then you would do request.route_url('sometestpage', pagename='myfavoritepage')

zope template namespaces gone?

Where can I find the zope namespaces for my templates? I setup a pyramid project using SQLAlchemy + URL dispatch + Chameleon templates. These URLs don't exist anymore...
http://xml.zope.org/namespaces/tal
http://xml.zope.org/namespaces/metal
Thanks.
The TAL specification says:
This is not a URL, but merely a unique identifier. Do not expect a browser to resolve it successfully.
http://wiki.zope.org/ZPT/TALSpecification14

Categories