Hakan B.
Hakan B.

Reputation: 2379

Django Form Fields: Represent field values as model field besides PK?

Is it possible to have a Django form field represent form values as slugs (e.g. <input value="groceries">) instead of IDs (<input value="1">) without significantly rewriting form methods? The slug is available on the model (e.g. Category.slug).

Forms.py:

from django import forms
from django.forms import ModelMultipleChoiceField, CheckboxSelectMultiple    
from myproject.common.models import Category

class MyForm(forms.Form): 
    cats = ModelMultipleChoiceField(required=False, queryset=Category.objects.all(), widget=CheckboxSelectMultiple)

Current HTML for each choice:

<label for="id_cats_0"><input type="checkbox" name="cats" value="1" id="id_cats_0" /> Groceries</label>

Instead, I would like to see the HTML rendered as ...

<label for="id_cats_0"><input type="checkbox" name="cats" value="groceries" id="id_cats_0" /> Groceries</label>

... and I would like for the rest of the Django form functionality to work as normal.

Maybe I'm dreaming, but is there an option that would allow me to specify a field besides PK by which to identify the form field choices? I need to use the slug field instead of the ID in order to support a legacy search system. Thanks in advance.

Upvotes: 1

Views: 508

Answers (1)

Andrew Ingram
Andrew Ingram

Reputation: 5230

try this:

cats = ModelMultipleChoiceField(required=False, to_field_name='slug', queryset=Category.objects.all(), widget=CheckboxSelectMultiple)

Upvotes: 1

Related Questions