I'm trying to output the description field from my model in a django form without joy.
After searching around and not finding what I need I hope I can ask here.
Here is my models, form, template and template output. I've abrieviated to help make this post concise.
I'm working on the view in this project so the model has been designed by someone else and I can't really change it.
MODELS:
1)
from django.db import models
class Project(models.Model):
description = models.TextField(blank = True)
name = models.CharField(max_length = 255, blank = True)
def __unicode__(self):
""" String representation of projects. """
return unicode(self.name)
2)
from django.db import models
class Share(models.Model):
description = models.TextField
last_access = models.DateTimeField(auto_now = True)
开发者_JS百科location = models.URLField(verify_exists = False)
project = models.ForeignKey('Project', related_name = 'shares')
def __unicode__(self):
return unicode(self.location)
FORM:
from django import forms
from models import Share
class ExportForm(forms.Form):
ps = forms.ModelMultipleChoiceField(queryset=Share.objects.filter(project=1),widget=forms.SelectMultiple())
VIEW:
form = ExportForm()
TEMPLATE:
I have this to ouput the multiple select bos:
{{ form.ps }}
TEMPLATE OUTPUT:
<select multiple="multiple" name="ps" id="id_ps">
<option value="11">Share object </option>
<option value="10">Share object </option>
</select>
I've tried several things from searching around but can't seem to be able to make the 'description' field in there rather than 'Share object'
Any advise much appreciated.
Thanks!
The easiest way to do this is to change the __unicode__
method of the Share model to return description instead of location, but since you say you can't change the model you will need to subclass ModelMultipleChoiceField
and override the label_from_instance
method.
class MyModelMultipleChoiceField(forms.ModelMultipleChoiceField):
def label_from_instance(self, obj):
return obj.description
This is explained in the documentation.
精彩评论