Sunday, January 30, 2011

Dynamic ModelForm fields

Hello,
I tried my best with no luck.
Here are the relevant code snippets:

##################################################
Item model:
class Item(models.Model):
category = models.ForeignKey(Category, related_name='items')
activation_code = models.CharField(max_length=64)
is_active = models.BooleanField(default=False)
is_deleted = models.BooleanField(default=False)
email = models.EmailField()
created_at = models.DateTimeField(auto_now_add=True)
updated_at = models.DateTimeField(auto_now=True)
title = models.CharField(max_length=200)
price = models.IntegerField(default=0)
is_used = models.BooleanField(default=False)
bedrooms = models.IntegerField(default=0)
bathrooms = models.IntegerField(default=0)
kitchens = models.IntegerField(default=0)
transmission = models.CharField(max_length=1,
choices=TRANSMISSION_CHOICES)
mileage = models.IntegerField(default=0)
model_year = models.IntegerField(default=0)

objects = ItemManager()

class Meta():
ordering = ('-created_at',)

def __unicode__(self):
return self.title

##############################################
Category model:
class Category(models.Model):
name = models.CharField(max_length=100, unique=True)
slug = models.SlugField(max_length=100, unique=True)
is_active = models.BooleanField(default=False)
show_fields = models.CharField(max_length=200)

class Meta():
ordering = ('name',)
verbose_name_plural = 'categories'

def __unicode__(self):
return self.name

#################################################
Item form:
class ItemForm(forms.ModelForm):
def __init__(self, fields_list, *args, **kwargs):
super(ItemForm, self).__init__(*args, **kwargs)
for field in self.fields:
if field not in fields_list:
field_name = str(field)
del self.fields[field_name]

class Meta():
model = Item

#################################################

I know this is not the best way to do this, but I just want to
understand why this happens.
For some reason, the for loop in ItemForm doesn't loop through all the
fields.
It only goes through 8, sometimes 9 fields out of the 14 in
self.fields. (e.g., I can't see the activation_code field in the
loop).
I printed self.fields and it showed all the fields in the Item model,
so why don't some of them show up in the loop?
I want to filter the fields based on the category chosen. The
fields_list parameter is a list of strings representing the fields I
want to include in the final form.

Any help would be appreciated. I've spent more hours than I can count
on this.
Thank you.

--
You received this message because you are subscribed to the Google Groups "Django users" group.
To post to this group, send email to django-users@googlegroups.com.
To unsubscribe from this group, send email to django-users+unsubscribe@googlegroups.com.
For more options, visit this group at http://groups.google.com/group/django-users?hl=en.

No comments:

Post a Comment