未加星标

Django hack: Help text on a model instance

字体大小 | |
[开发(python) 所属分类 开发(python) | 发布者 店小二04 | 时间 2016 | 作者 红领巾 ] 0人收藏点击收藏

If you've been been working with Django for a while, you're probably familiar with the help_text attribute for model fields. It gives us a hook for adding descriptive text that gets automatically included on forms or in the admin.

But what if you want to access that same information on an instance of model object?

Let's look at an example! Assume we have a simple model:

class BlogPost(models.Model):
title = models.CharField(
max_length=50,
unique=True,
help_text="A unique title for this thing"
)
content = models.TextField(
help_text="A content for this thing"
)

Here we have a simple blog post. If we were building an app, we might use a ModelForm subclass that allows users to create an instance of a BlogPost. It would look something like this:

class BlogPostForm(forms.ModelForm):
class Meta:
model = BlogPost

And in our view we might create an unbound instance of this form with form = BlogPostForm() , then in our template we might have markup that loooks something like this:

<form>
{{ form.as_p }}
</form>

That generates a decent-looking form, with our model's help-text included. The markup would be similar to the following:

<p>
<label for="id_title">Title:</label>
<input id="id_title" maxlength="50" name="title" type="text" />
<span class="helptext">A unique title for this thing</span>
</p>
<p>
<label for="id_description">Description:</label>
<textarea cols="40" id="id_description" name="description" rows="10"></textarea>
<span class="helptext">A description for this thing</span>
</p>

Notice the <span class="helptext"> elements!

Unfortunately, it's not as straightforwad if we want to access that same bit of information on a model instance. However, Django already does something a little magical that for model fields that include a set of choices. From the choices documentation :

For each model field that has choices set, Django will add a method to retrieve the human-readable name for the field’s current value. See get_FOO_display() in the database API documentation.

So, I decided to look up how they did this and I discovered the django implementation of curry, in django.utils.functional.curry .

For the purposes of this post, curry will let us dynamically create a method on a class, defining it's parameters at run-time.

Let's look at how this works. First, lets see how to access a field's help_text :

class BlogPost(models.Model):
title = models.CharField(...)
content = models.TextField(...)
def _get_help_text(self, field_name):
"""Given a field name, return it's help text."""
# Let's iterate over all the fields on this model.
for field in self._meta.fields:# The name of your field is stored as# a name attribute on the field objectif field.name == field_name: # and there's the help_text! return field.help_text

Now, all we need to do is figure out how to dynamically create a method, get_title_help_text that calls _get_help_text('title') . Below is an updated version of our model; Take a look at it's __init__ method.

from django.db import models
from django.utils.functional import curry
class BlogPost(models.Model):
title = models.CharField(
max_length=50,
unique=True,
help_text="A unique title for this thing"
)
content = models.TextField(
help_text="A content for this thing"
)
def _get_help_text(self, field_name):
"""Given a field name, return it's help text."""
for field in self._meta.fields:if field.name == field_name: return field.help_text
def __init__(self, *args, **kwargs):
# Call the superclass first; it'll create all of the field objects.
super(BlogPost, self).__init__(*args, **kwargs)
# Again, iterate over all of our field objects.
for field in self._meta.fields:# Create a string, get_FIELDNAME_help textmethod_name = "get_{0}_help_text".format(field.name)# We can use curry to create the method with a pre-defined argumentcurried_method = curry(self._get_help_text, field_name=field.name)# And we add this method to the instance of the class.setattr(self, method_name, curried_method)

Now, in our template we can display a BlogPost's field values, as well as call a method to access each field's defined help text.

<p>
{{ post.title }}<br/>
<span>{{ post.get_title_help_text }}</span>
</p>
<p>
{{ post.content }}<br/>
<span>{{ post.get_content_help_text }}</span>
</p>

Pretty cool.

本文开发(python)相关术语:python基础教程 python多线程 web开发工程师 软件开发工程师 软件开发流程

主题: Django
分页:12
转载请注明
本文标题:Django hack: Help text on a model instance
本站链接:http://www.codesec.net/view/483317.html
分享请点击:


1.凡CodeSecTeam转载的文章,均出自其它媒体或其他官网介绍,目的在于传递更多的信息,并不代表本站赞同其观点和其真实性负责;
2.转载的文章仅代表原创作者观点,与本站无关。其原创性以及文中陈述文字和内容未经本站证实,本站对该文以及其中全部或者部分内容、文字的真实性、完整性、及时性,不作出任何保证或承若;
3.如本站转载稿涉及版权等问题,请作者及时联系本站,我们会及时处理。
登录后可拥有收藏文章、关注作者等权限...
技术大类 技术大类 | 开发(python) | 评论(0) | 阅读(38)