CBV Django Form View set data for ChoiceField -
i'm using django form view , want enter custom choices per user choicefield.
how can this?
can use maybe get_initial function? can overwrite field?
when want change things form such label text, adding required fields or filtering list of choices etc. follow pattern use modelform , add few utility methods contain overriding code (this helps keep __init__ tidy). these methods called __init__ override defaults.
class profileform(forms.modelform): class meta: model = profile fields = ('country', 'contact_phone', ) def __init__(self, *args, **kwargs): super(profileform, self).__init__(*args, **kwargs) self.set_querysets() self.set_labels() self.set_required_values() self.set_initial_values() def set_querysets(self): """filter choicefields here.""" # show active countries in ‘country’ choices list self.fields["country"].queryset = country.objects.filter(active=true) def set_labels(self): """override field labels here.""" pass def set_required_values(self): """make specific fields mandatory here.""" pass def set_initial_values(self): """set initial field values here.""" pass if choicefield thing you're going customising, need:
class profileform(forms.modelform): class meta: model = profile fields = ('country', 'contact_phone', ) def __init__(self, *args, **kwargs): super(profileform, self).__init__(*args, **kwargs) # show active countries in ‘country’ choices list self.fields["country"].queryset = country.objects.filter(active=true) you can make formview use form this:
class profileformview(formview): template_name = "profile.html" form_class = profileform
Comments
Post a Comment