Django data validation in form (admin/auth/user)
in my User administration for each individual's page, besides the default django fieldsets, I also have two other inlines (UserProfile and a model called "Extension"). However, whenever I modify fields in the Extension's inline, I want to be able to process/validate all these fields too.
UserProfile:
user = models.ForeignKey(User, unique=True)
client = models.ForeignKey(Client)
Extension:
user = models.ForeignKey(User)
date_created = models.DateTimeField(auto_now_add=True, auto_now=True)
number = models.CharField(max_length=16, unique=False)
For example, when I'm editing a user's extension numbers, I want to be able to grab all values inside each field (which are dynamic). Right now I'm using self.data[""] like this:
extension_fields = [self.data["extension_set-0-number"],
self.data["extension_set-1开发者_运维百科-number"],
self.data["extension_set-2-number"]]
One problem this poses is that I'm assuming there always will only be 3 fields for extension, which is not always true. How can I loop through each inline field correctly?
How can I loop through each inline field correctly?
You can use a list comprehension to loop through them:
extension_fields = [self.data[k] for k in self.data.keys() if 'extension_set' in k]
I'm not entirely convinced this is the correct way to implement this, however. You haven't provided enough example code to explain what you're doing exactly. If you're trying to process and validate this data, Django should be doing this for you (probably using a ModelForm). You shouldn't have to be hardcoding this yourself.
精彩评论