80
You can modify the fields in __init__
in the form. This is DRY since the label, queryset and everything else will be used from the model. This can also be useful for overriding other things (e.g. limiting querysets/choices, adding a help text, changing a label, โฆ).
class ProfileEditPersonalForm(forms.ModelForm):
def __init__(self, *args, **kwargs):
super().__init__(*args, **kwargs)
self.fields['country'].required = True
class Meta:
model = Profile
fields = (...)
Here is a blog post that describes the same "technique": http://collingrady.wordpress.com/2008/07/24/useful-form-tricks-in-django/
13
In Django 3.0 if you for example want to make email required in user registration form, you can set required=True
:
from django import forms
from django.contrib.auth.models import User
from django.contrib.auth.forms import UserCreationForm
class MyForm(UserCreationForm):
email = forms.EmailField(required=True) # <- set here
class Meta:
model = User
fields = ['username', 'email', 'password1', 'password2']
- [Django]-How to run a celery worker with Django app scalable by AWS Elastic Beanstalk?
- [Django]-How can I get a decimal field to show more decimal places in a template?
- [Django]-Django manage.py Unknown command: 'syncdb'
Source:stackexchange.com