2010-03-21 4 views
2

J'ai trois classes de modèles qui ont l'air comme ci-dessous:Remplacer textfields avec les champs déroulants sélectionnez

class Model(models.Model): 
    model = models.CharField(max_length=20, blank=False) 
    manufacturer = models.ForeignKey(Manufacturer) 
    date_added = models.DateField(default=datetime.today) 
    def __unicode__(self): 
     name = ''+str(self.manufacturer)+" "+str(self.model) 
     return name 

class Series(models.Model): 
    series = models.CharField(max_length=20, blank=True, null=True) 
    model = models.ForeignKey(Model) 
    date_added = models.DateField(default=datetime.today) 
    def __unicode__(self): 
     name = str(self.model)+" "+str(self.series) 
     return name 
class Manufacturer(models.Model): 
    MANUFACTURER_POPULARITY_CHOICES = (
     ('1', 'Primary'), 
     ('2', 'Secondary'), 
     ('3', 'Tertiary'), 
    ) 

    manufacturer = models.CharField(max_length=15, blank=False) 
    date_added = models.DateField(default=datetime.today) 
    manufacturer_popularity = models.CharField(max_length=1, 
     choices=MANUFACTURER_POPULARITY_CHOICES) 
    def __unicode__(self): 
     return self.manufacturer 

je veux avoir les champs pour modelseries et manufacturer représentée comme dropdowns au lieu des champs de texte. Je mesure les modèles de formulaires comme ci-dessous:

class SeriesForm(ModelForm): 
    series = forms.ModelChoiceField(queryset=Series.objects.all()) 
    class Meta: 
     model = Series 
     exclude = ('model', 'date_added',) 

class ModelForm(ModelForm): 
    model = forms.ModelChoiceField(queryset=Model.objects.all()) 
    class Meta: 
     model = Model 
     exclude = ('manufacturer', 'date_added',) 

class ManufacturerForm(ModelForm): 
    manufacturer = forms.ModelChoiceField(queryset=Manufacturer.objects.all()) 
    class Meta: 
     model = Manufacturer 
     exclude = ('date_added',) 

Cependant, les listes déroulantes sont peuplées de l'unicode dans la classe respective ... Comment puis-je personnaliser ce pour obtenir le résultat final que je veux?

En outre, comment puis-je remplir les formulaires avec les données correctes pour l'édition? Actuellement seulement SeriesForm est rempli. Le point de départ de tout cela est d'une autre classe dont la déclaration est comme ci-dessous:

class CommonVehicle(models.Model): 
    year = models.ForeignKey(Year) 
    series = models.ForeignKey(Series) 
    .... 

    def __unicode__(self): 
     name = ''+str(self.year)+" "+str(self.series) 
     return name 

Répondre

2

Découvrez http://docs.djangoproject.com/en/dev/ref/forms/fields/#modelchoicefield et en particulier le morceau qui commence

La méthode unicode du modèle sera appelé générer des représentations sous forme de chaîne des objets à utiliser dans les choix du champ; Pour fournir des représentations personnalisées, sous-classe ModelChoiceField et remplacez label_from_instance. Cette méthode recevra un objet de modèle, et devrait renvoyer une chaîne appropriée pour la représenter.

[Suit un bon exemple de la façon de le faire]

HTH

Steve

+0

C'est exactement ce que je avais besoin .... laissez-moi essayer. Thnx – Stephen

-3

fichiers .h: (UIView Créer)

#import <UIKit/UIKit.h> 



@class NIDropDown; 

@protocol NIDropDownDelegate 

- (void) niDropDownDelegateMethod: (NIDropDown *) sender; 

@end 



@interface NIDropDown : UIView <UITableViewDelegate, UITableViewDataSource> 

{ 

    NSString *animationDirection; 

    UIImageView *imgView; 

} 

@property (nonatomic, retain) id <NIDropDownDelegate> delegate; 

@property (nonatomic, retain) NSString *animationDirection; 

-(void)hideDropDown:(UIButton *)b; 

- (id)showDropDown:(UIButton *)b :(CGFloat *)height :(NSArray *)arr :(NSArray *)imgArr :(NSString *)direction; 

@end 

.m Fichiers:

#import "NIDropDown.h" 

#import "QuartzCore/QuartzCore.h" 



@interface NIDropDown() 

@property(nonatomic, strong) UITableView *table; 

@property(nonatomic, strong) UIButton *btnSender; 

@property(nonatomic, retain) NSArray *list; 

@property(nonatomic, retain) NSArray *imageList; 

@end 



@implementation NIDropDown 

@synthesize table; 

@synthesize btnSender; 

@synthesize list; 

@synthesize imageList; 

@synthesize delegate; 

@synthesize animationDirection; 



- (id)showDropDown:(UIButton *)b :(CGFloat *)height :(NSArray *)arr :(NSArray *)imgArr :(NSString *)direction { 

    btnSender = b; 

    animationDirection = direction; 

    self.table = (UITableView *)[super init]; 

    if (self) { 

     // Initialization code 

     CGRect btn = b.frame; 

     self.list = [NSArray arrayWithArray:arr]; 

     self.imageList = [NSArray arrayWithArray:imgArr]; 

     if ([direction isEqualToString:@"up"]) { 

      self.frame = CGRectMake(btn.origin.x, btn.origin.y, btn.size.width, 0); 

      self.layer.shadowOffset = CGSizeMake(-5, -5); 

     }else if ([direction isEqualToString:@"down"]) { 

      self.frame = CGRectMake(btn.origin.x, btn.origin.y+btn.size.height, btn.size.width, 0); 

      self.layer.shadowOffset = CGSizeMake(-5, 5); 

     } 



     self.layer.masksToBounds = NO; 

     self.layer.cornerRadius = 8; 

     self.layer.shadowRadius = 5; 

     self.layer.shadowOpacity = 0.5; 



     table = [[UITableView alloc] initWithFrame:CGRectMake(0, 0, btn.size.width, 0)]; 

     table.delegate = self; 

     table.dataSource = self; 

     table.layer.cornerRadius = 5; 

     //table.backgroundColor = [UIColor clearColor]; 

     table.backgroundColor = [UIColor scrollViewTexturedBackgroundColor];//[UIColor colorWithRed:0.239 green:0.239 blue:0.239 alpha:1]; 

     table.separatorStyle = UITableViewCellSeparatorStyleNone; 

     table.separatorColor = [UIColor clearColor]; 



     [UIView beginAnimations:nil context:nil]; 

     [UIView setAnimationDuration:0.5]; 

     if ([direction isEqualToString:@"up"]) { 

      self.frame = CGRectMake(btn.origin.x, btn.origin.y-*height, btn.size.width, *height); 

     } else if([direction isEqualToString:@"down"]) { 

      self.frame = CGRectMake(btn.origin.x, btn.origin.y+btn.size.height, btn.size.width, *height); 

     } 

     table.frame = CGRectMake(0, 0, btn.size.width, *height); 

     [UIView commitAnimations]; 

     [b.superview addSubview:self]; 

     [self addSubview:table]; 

    } 

    return self; 

} 



-(void)hideDropDown:(UIButton *)b { 

    CGRect btn = b.frame; 



    [UIView beginAnimations:nil context:nil]; 

    [UIView setAnimationDuration:0.5]; 

    if ([animationDirection isEqualToString:@"up"]) { 

     self.frame = CGRectMake(btn.origin.x, btn.origin.y, btn.size.width, 0); 

    }else if ([animationDirection isEqualToString:@"down"]) { 

     self.frame = CGRectMake(btn.origin.x, btn.origin.y+btn.size.height, btn.size.width, 0); 

    } 

    table.frame = CGRectMake(0, 0, btn.size.width, 0); 

    [UIView commitAnimations]; 

} 



- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView { 

    return 1; 

} 



-(CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath { 

    return 40; 

} 



- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section { 

    return [self.list count]; 

} 





- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath { 

    static NSString *CellIdentifier = @"Cell"; 



    UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier]; 

    if (cell == nil) { 

     cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:CellIdentifier]; 

     if(UI_USER_INTERFACE_IDIOM() == UIUserInterfaceIdiomPad){ 

      cell.textLabel.font = [UIFont systemFontOfSize:20]; 

     } else { 

      cell.textLabel.font = [UIFont systemFontOfSize:8]; 

     } 

     cell.textLabel.textAlignment = UITextAlignmentCenter; 

    } 

    if ([self.imageList count] == [self.list count]) { 

     //cell.textLabel.text =[list objectAtIndex:indexPath.row]; 

     //cell.imageView.image = [imageList objectAtIndex:indexPath.row]; 

    } else if ([self.imageList count] > [self.list count]) { 

     // cell.textLabel.text =[list objectAtIndex:indexPath.row]; 

     if (indexPath.row < [imageList count]) { 

      // cell.imageView.image = [imageList objectAtIndex:indexPath.row]; 

     } 

    } else if ([self.imageList count] < [self.list count]) { 

     cell.textLabel.text =[list objectAtIndex:indexPath.row]; 

     if (indexPath.row < [imageList count]) { 

      //cell.imageView.image = [imageList objectAtIndex:indexPath.row]; 

     } 

    } 



    cell.textLabel.textColor = [UIColor blackColor]; 



    UIView * v = [[UIView alloc] init]; 

    v.backgroundColor = [UIColor grayColor]; 

    cell.selectedBackgroundView = v; 



    return cell; 

} 



- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath { 

    [self hideDropDown:btnSender]; 



    UITableViewCell *c = [tableView cellForRowAtIndexPath:indexPath]; 

    //[btnSender setTitle:c.textLabel.text forState:UIControlStateNormal]; 

    NSUserDefaults *prefCountOne = [NSUserDefaults standardUserDefaults]; 

    [prefCountOne setObject:c.textLabel.text forKey:@"TYPETEXT"]; 



    for (UIView *subview in btnSender.subviews) { 

     if ([subview isKindOfClass:[UIImageView class]]) { 

      [subview removeFromSuperview]; 

     } 

    } 

    imgView.image = c.imageView.image; 

    imgView = [[UIImageView alloc] initWithImage:c.imageView.image]; 

    imgView.frame = CGRectMake(5, 5, 25, 25); 

    [btnSender addSubview:imgView]; 

    [self myDelegate]; 

} 



- (void) myDelegate { 

    [self.delegate niDropDownDelegateMethod:self]; 

} 

Utilisation TextField dans .m Fichiers:

- (IBAction) fnDisplayCategory:(id)sender { 

[pTxtCategory resignFirstResponder]; 

if(pBtnCategory == nil) { 

CGFloat f = 200; 

pBtnCategory = [[NIDropDownForTwoArrays alloc]showDropDown:pTxtCategory :&f :pArCategory :@"down" :1]; 

pBtnCategory.delegate = self; 

NSUserDefaults *defaults = [NSUserDefaults standardUserDefaults]; 

[defaults setObject:@"First" forKey:@"DropDown"]; 

     [[NSUserDefaults standardUserDefaults] synchronize]; 

} 

else { 

[pBtnCategory hideDropDown:pTxtCategory]; 

[self rel]; 

} 

} 



- (void)rel { 

    pBtnCategory = nil; 

} 
Questions connexes