Django ModelForms: cleanest way to hide fields and enforce defaults -


let's have single modelform can filled out different tiers of users. admin can edit field of form; other users, need have fields pre-defined, , read-only and/or hidden.

using cbv's get_form_kwargs method, have made form aware of user that's bringing up, and, in __init__ method react accordingly, tweaking form's exclude, , fields' required , initial properties; , then, in view's form_valid, further enforce values. but, frankly, i'm neither sure every operation needed, nor whether there's gaping hole i'm not aware of.

so, what's best, cleanest way of doing this?

assuming there aren't lot of combinations, create different form meets different needs of users. override def get_form_class , return correct form based on needs. keeps different use cases separate , gives flexibility if need change things in future without breaking other forms.

# models.py class foo(models.model):     bar = model.charfield(max_length=100)     baz = model.charfield(max_length=100)     biz = model.charfield(max_length=100)  # forms.py class fooform(forms.modelform):  # admins     class meta:         model = foo  class fooform(forms.modelform):  # users can't see bar     boo = forms.charfield()      class meta:         model = foo         exclude = ['bar']  class fooformn(forms.modelform):  # many different scenarios need     def __init__(self, *args, **kwargs)         super(fooformn, self).__init__(*args, **kwargs)         self.fields['biz'].widget.attrs['readonly'] = true      class meta:         model = foo  # views.py class someview(updateview):     def get_form_class(self):         if self.request.user.groups.filter(name="some_group").exists():             return fooform         # etc. 

Comments

Popular posts from this blog

Ansible - ERROR! the field 'hosts' is required but was not set -

customize file_field button ruby on rails -

SoapUI on windows 10 - high DPI/4K scaling issue -