Hello,
I'm using a ManyToManyField to model a relationship where a "Project"
object may have many different "Stain" objects. The code is working
successfully and looks like this
class Stain(models.Model):
def __unicode__(self):
return unicode(self.name)
name = models.CharField(max_length=40)
class Project(models.Model):
name = models.CharField(max_length=200)
stains = models.ManyToManyField(Stain, blank=True) # not required
...
However, I've also subclassed ModelForm in the interest of defining a
readonly view of the Project data (ie: a view without inputs). The
code in forms.py is like this:
class ReadOnlyWidget(forms.Widget):
'''
Widget used by our ModelForm when rendering in readonly mode.
'''
def __init__(self, original_value, display_value):
self.original_value = original_value
self.display_value = display_value
super(ReadOnlyWidget, self).__init__()
def render(self, name, value, attrs=None):
if self.display_value is not None:
return unicode(self.display_value)
if type(value) == list:
#
# Need to format list fields so they're seen in read only
view
#
return unicode(value)
return unicode(self.original_value)
def value_from_datadict(self, data, files, name):
return self.original_value
class ModelForm(forms.ModelForm):
'''
Define our own model forms so we can use the form to render a
read-only detail page.
'''
def __init__(self, *args, **kwargs):
readonly = kwargs.get('readonly', False)
if readonly:
del kwargs['readonly']
super(ModelForm, self).__init__(*args, **kwargs)
if readonly:
obj = self.instance
for field_name in self.fields:
if hasattr(obj, 'get_%s_display' % field_name):
display_value = getattr(obj,
'get_%s_display' %
field_name)()
else:
display_value = None
self.fields[field_name].widget = ReadOnlyWidget(getattr
(obj, field_name, ''), display_value)
class ProjectForm(ModelForm):
class Meta:
model = Project
The problem I'm running into is that the value that comes into render
for the ManyToManyField is a list of the id's for the selected stains
and not the stains themselves. I assume I should be getting them
somehow through the django.db.models.fields.related.ManyRelatedManager
which is in the original_value, but I haven't been able to figure out
how.
Anyone know what I'm missing?
--~--~---------~--~----~------------~-------~--~----~
You received this message because you are subscribed to the Google Groups
"Django users" group.
To post to this group, send email to [email protected]
To unsubscribe from this group, send email to
[email protected]
For more options, visit this group at
http://groups.google.com/group/django-users?hl=en
-~----------~----~----~----~------~----~------~--~---