4👍
You should use modelform_factory to create the form on the fly and pass in the fields you want to exclude.
def django.forms.models.modelform_factory (
model,
form = ModelForm,
fields = None,
exclude = None,
formfield_callback = lambda f: f.formfield()
)
So something like
modelform_factory(MyModel, MyModelForm, exclude=('name',))
- RexProScriptException transaction is not open in Django with Titan (graph DB)
- Django on Heroku – Broken Admin Static Files
- Docker compose for production and development
2👍
You should use self._meta
instead of self.Meta
, because the ModelForm.__new__
method get attributes form self.Meta
and puts them into self._meta
.
- Django ALLOWED_HOSTS for Amazon ELB
- Best practices for preventing Denial of Service Attack in Django
- Foreign Key to User model
- Docker error with pipenv on django app: Warning: –system is intended to be used for pre-existing Pipfile
- Django – OperationalError: (2006, 'MySQL server has gone away')
1👍
Related, to exclude fields from a sub-class, I have extended the ModelForm class like so:
class ModelForm(djangoforms.ModelForm):
def __init__(self, *args, **kwargs):
super(ModelForm, self).__init__(*args, **kwargs)
meta = getattr(self, 'Meta', None)
exclude = getattr(meta, 'exclude', [])
for field_name in exclude:
if field_name in self.fields:
del self.fields[field_name]
- Merge two fields in one in a Django Rest Framework Serializer
- Could not import 'oauth2_provider.ext.rest_framework.OAuth2Authentication' for API setting 'DEFAULT_AUTHENTICATION_CLASSES'
- Disable Django Debugging for Celery
- Django form with fields from two different models
1👍
I made like this:
class Meta:
exclude = [field.label for field in Fields.objects.filter(visible=False)] + ['language', 'created_at']
👤quux
- Django REST framework – multiple lookup fields?
- Django aggregate Count only True values
- Difference between Response and HttpResponse django
- How can I automatically let syncdb add a column (no full migration needed)
0👍
Just to note: if your form is called from a ModelAdmin class, just create a get_form method for the ModelAdmin:
def get_form(self, request, obj=None, **kwargs):
exclude = ()
if not request.user.is_superuser:
exclude += ('field1',)
if obj:
exclude += ('field2',)
self.exclude = exclude
return super(ProfessorAdmin, self).get_form(request, obj, **kwargs)
PS: change ProfessorAdmin by the method “owner” class.
- RexProScriptException transaction is not open in Django with Titan (graph DB)
- TypedChoiceField or ChoiceField in Django
- Heroku Django DEBUG Setting not applied
- Django: How to automatically change a field's value at the time mentioned in the same object?
- In django, is aggregate(Count()) faster or better than .count() in anyway?
Source:stackexchange.com