6π
β
This is how I limited the options displayed:
In forms.py add an init method for your form
class TaskForm(forms.ModelForm):
....
def __init__(self, user, *args, **kwargs):
'''
limit the choice of owner to the currently logged in users hats
'''
super(TaskForm, self).__init__(*args, **kwargs)
# get different list of choices here
choices = Who.objects.filter(owner=user).values_list('id','name')
self.fields["owner"].choices = choices
π€PhoebeB
1π
Choices are for lists only, not CharFields. What you need to do is create a custom validator on clean()
.
in forms.py
CAMPAIGN_TYPES = ('email', 'display', 'search')
# this would be derived from your Campaign modelform
class EnhancedCampaignForm(CampaignForm):
# override clean_FIELD
def clean_type(self):
cleaned_data = self.cleaned_data
campaign_type = cleaned_data.get("type")
# strip whitespace and lowercase the field string for better matching
campaign_type = campaign_type.strip().lower()
# ensure the field string matches a CAMPAIGN_TYPE, otherwise
# raise an exception so validation fails
if not campaign_type in CAMPAIGN_TYPE:
raise forms.ValidationError("Not a valid campaign type.")
# if everything worked, return the field's original value
return cleaned_data
π€Soviut
- [Django]-How do I resolve access denied aws s3 files?
- [Django]-Unable to override django-allauth templates
- [Django]-Double Foreign Key in Django?
- [Django]-Urls in Django 1.7 when the Url Contains spaces
- [Django]-Including static js files in django 1.7
1π
It seems that this is the best way to do it by overriding the βtypeβ field:
class CampaignForm(ModelForm):
type = forms.ModelChoiceField(queryset=OtherModel.objects.filter(type__id=1))
class Meta:
model = Campaign
Iβm not sure right now how to pass β1β but this will be good enough even if it needs to be hardcoded. Plus, it lets Django do most of the heavy lifting.
@soviut I will change the field name to a non-reserved word. Thanks for the heads up.
π€Adam Nelson
- [Django]-Annotation with a subquery with multiple result in Django
- [Django]-Django LookupError: App 'accounts' doesn't have a 'User' model
- [Django]-Two process in one Heroku app vs two heroku apps
- [Django]-Django β new field: How to set default callable for existing objects
- [Django]-Django template for loop iterating two item
Source:stackexchange.com