The hello world of sprox with pyramid - python

I've tried to build the simplest possible form in Sprox using pyramid.
# model.py
class Allocation:
# some fields ...
class SproxForm(AddRecordForm):
__model__ = Allocation
sprox_form = SproxForm(DBSession)
# views.py
def sprox_form(request):
return {'f':sprox_form,'kw':{}}
<html>
<body>
<div tal:content="structure f(kw)"/>
</body>
</html>
But it just prints out {'kw': {}, 'f': } The forms tutorial is written using TurboGears2 and I am unable to translate it to pyramid, because I am new to pyramid.
So could someone tell me what am I doing wrong, or show me a short (but complete) example, which uses pyramid?

Well your form is named sprox_form and your view is named sprox_form. This ambiguity is gonna be a bad idea. Other than that I can't see anything suspicious, assuming your chameleon syntax is correct. If you were using mako it'd be simply ${f(kw)} although instead of f I might suggest using the name widget or form, and instead of kw maybe value or form_input.

Related

Discern 'context' in Django?

The duplicated question explains the meaning of 'context', not explaining why it contradict to its original meaning in real life.
We will use 'content' instead.
Django documentation define 'context' as:
Context:A dict to be used as the template’s context for rendering.
MB defines it as:
the parts of a discourse that surround a word or passage and can throw light on its meaning
They contradict to each other.
Take an instance to explain my question :
In views.py
context = {key:value}
render(request, template_name, context)
in template
<p> The parts of a discourse that surround a
word {{ key }} and can throw lights on its meaning.<\p>
Literallly, the 'context' is the parts outside the curly bracket not the parts inside to be filled in.
Now, django's context is the part within bracket.
How to perceive the definition of context in Django?
Think of the context as the environment that the template is parsed in. So when you have something like {{ key }} inside the template, the template engine looks for something in the context that it is executing in to find the value to insert.
The context "surrounds" the template and "gives it meaning".
'context' is the 'contextual information' submitted for background investigation

Calling a route from a template

Can I have a route that renders a template that I can use in another template?
I imagine something like
#app.route('/tags/')
def tags():
return render_template('tags.html', tags=create_tags())
and then somehow invoke the route from a different template.
<h2>Tags</h2>
{{ render('/tags/') }}
Routes don't render templates, functions do. All the route does is point a url to a function. So, the obvious solution to me is to have a function that returns the rendered tag template:
def render_tags_template():
return render_template('tags.html', tags=create_tags())
Then we want to associate the function with the url "/tags"
app.add_url_rule('/tags', endpoint='tags', view_func=render_tags_template)
We also want to be able to access this function from within our templates. Accessing it via the url through another request would most likely be a job for ajax. So we have to get render_tags_template into the template context.
render_template('some_random_template.html', render_tags_template=render_tags_template
then in your some_random_template.html:
{{render_tags_template()}}
if you don't want to pass render_tags_template explicitly, you can add it as a template global:
app.jinja_env.globals['render_tags_template'] = render_tags_template
and use it freely in all of your templates, without having to pass it explicitly.
Depending on what your actually trying to do, simply including tags.html may be the best and easiest solution. Using a function to generate the content gives you a bit more control and flexibility.
You can include the tags.html template in your template.
{% include "tags.html" %}
You have to pass the tags to your template, but this is the way to do it.

Django - using regex in urls.py to pass values

I just ran into a problem..
I'm trying to build a website at the moment with different pages.
So I created a django app called pages, with the following fields:
title
text
URL
The idea is, that users can create new pages and delete existing ones and it actually affects the navigation in real time.
So in my urls.py I wanted to handle this somehow like this:
from django.conf.urls.defaults import *
urlpatterns = patterns('',
(r'^pages/(/w)', pages.views.display_content),
)
For example there could be a page with URL property "page1", then "page1" should be stored by (/w) and passed over to pages.views.display_content, which then would display the corresponding data. The "page1" page would be accessible through domain.com/pages/page1.
However, as I'm not really good with regex, I think I really need your help.
I would be really happy if someone could explain to me how I have to write my URL rule for this..
Good Night :)
In addition, you could name the parameter that will be captured and passed to your view function with this notation:
...
(r'^pages/(?P<page_name>\w+)', 'pages.views.display_content'),
...
So you can access it with that name in your view function.
Its header should look like this:
def display_content(request, page_name):
...

Django: avoiding multiple evaluations of the same expression in a template?

When passing an object called widget as part of the context to rendering a django template, I may have a method which is a bit expensive, but I want to display the result of it more than once.
Python:
class Widget:
def work(self):
# Do something expensive
Template
This is a widget, the result of whose work is {{widget.work}}. Do
you want to save {{widget.work}} or discard {{widget.work}}?
Clearly I could work around this by evaluating the method once in the view code, and then passing the result in, but this seems to couple the view and the template too much. Is there a way for the template author to stash values for re-use later in the template? I would like to do something like this:
{% work_result = widget.work %}
This is a widget, the result of whose
work is {{work_result}}. Do you want to save {{work_result}} or discard {{work_result}}?
Does such a construct exist in the django template language?
{% with %}
{% with work_result=widget.work %}
Look Django docs for more information

Additional fields in Django admin interface

Suppose I have some persistent model property that's not backed up by a model field, how do I allow editing this field in the admin interface?
Example setup:
# models.py
# appropriate imports...
class MyModel(Model):
# regular fields.
foo = CharField(max_length=50)
bar = BooleanField()
# ...
# custom property, backed by a file.
def _get_meh ( self ):
return ... # read from file
def _set_meh ( self, value ):
... # write to file.
meh = property(_get_meh, _set_meh)
meh's value is actually stored in a file on disk who's path depends on the value in foo. I'd like to be able to edit meh's value from the admin interface.
# admin.py
# appropriate imports...
class MyModelAdmin(ModelAdmin):
# what do I put here?
Note: in case someone needs to ask, I'm using Django version 1.2.1, but upgrading is possible if that is required by your solution. Anything that runs on Python 2.5 will do, this I can't really upgrade for the moment.
Take a look at this:
http://www.scribd.com/doc/68396387/Adding-extra-fields-to-a-model-form-in-Django%E2%80%99s-admin-%E2%80%93-Hindsight-Labs
(this one went offline, http://www.hindsightlabs.com/blog/2010/02/11/adding-extra-fields-to-a-model-form-in-djangos-admin/)
Basically, you'll create a MyModelFrom subclassed from forms.ModelForm and:
Add the extra meh fields to the MyModelFrom definition.
Override the constructor of the MyModelFrom, set the self.initial meh property if a model instance was passed to the form.
Override the save method of the MyModelFrom, set the meh property on the model instance based on the form fields.
This way, the meh property would be correctly filled at your Model, but you'll also need to override MyModel's save() method to actually persist this value to your disk file:
(Google for "django model override save", sry, it seems I can't post more than a link per answer till I get more than 10 rep...)
Cheers,
Ny Django knowledge isn't that great, but depending on how complicated you want it to be, I'm not sure something like this can be easily done without much hackery.
Anyhow, if you want to add it to Add MyModel page, you can edit the appropriate admin template.
So in your template directory, create something like:
admin/app_label/MyModel/change_form.html
Then extend the base template, and add your own content:
{% extends "admin/change_form.html" %}
{% block something_you_want_to_override %}
<p>Your HTML goes here</p>
{% endblock %}
Is there really no way you can get this custom field into an actual Django field though? Surely you can override the save() method on the model and do it that way? Or use a pre_save signal?
Cheers,
Victor

Categories

Resources