Custom field names in ModelForm

244 views
Skip to first unread message

Bhashkar Sharma

unread,
May 10, 2012, 9:42:44 AM5/10/12
to django...@googlegroups.com
Is there a way to customize the field name (not just label) while creating a ModelForm?

Eg. for the model:
class Book(models.Model):
    title = models.CharField(max_length=256, db_index=True)
    author = models.CharField(max_length=512, db_index=True)
    published = models.DateTimeField(db_index=True)

the ModelForm can be:

class BookForm(forms.ModelForm):
    fields = ('title', 'author')

Is there a way I can expose 'title' as 'book_name'? As in, the form HTML should have:

<tr><th><label for="id_book_name">book_name:</label></th><td><input id="id_book_name" type="text" name="book_name" maxlength="256" /></td></tr>
<tr><th><label for="id_author">Author:</label></th><td><input id="id_author" type="text" name="author" maxlength="512" /></td></tr>

Rajeesh Nair

unread,
May 10, 2012, 2:47:54 PM5/10/12
to django...@googlegroups.com

Is there a way to customize the field name (not just label) while creating a ModelForm?


Override the change_form template for the concerned model and put the label for the field
in whatever way you like. Check out the django-templates documentation to know how to
do this.

Bhashkar Sharma

unread,
May 11, 2012, 1:36:59 AM5/11/12
to django...@googlegroups.com
Thanks for the reply Rajneesh, but I'm looking for a more scalable option.
(Ideally I would like to write a wrapper of some kind which does the task regardless of which Model is it)
My use case is that I'm using django-piston for building a REST API, which I tweaked to give me what I wanted (http://rockerhome.wordpress.com/2012/05/06/hacking-django-piston/)
Since I'm exposing different field names to the external world as mentioned in my post, I want to validate those while still continuing to use the django Forms/ModelForms for validation of submitted data for data updation. It has to work for partial updates too.

I don't know if I was able to explain myself.
Let me know.
Reply all
Reply to author
Forward
0 new messages