This is a custom form-field designed to make those optional "enter a discount code" fields a little easier to deal with. You create one like this:
code = CodeLookupField(model=MyModel, field_name='slug', max_length=20)
And then when you validate your form, cleaned_data['code'] will be the actual object if anything was retrieved, or None if the user entered a bad piece of data.
1 2 3 4 5 6 7 8 9 10 11 12 | class CodeLookupField(forms.CharField):
def __init__(self, model, field_name, *args, **kwargs):
self.model = model
self.field_name = field_name
super(CodeLookupField, self).__init__(*args, **kwargs)
def clean(self, data):
try:
return self.model.objects.get(**{self.field_name:data})
except self.model.DoesNotExist:
return None
|
More like this
- LazyPrimaryKeyRelatedField by LLyaudet 2 days, 19 hours ago
- CacheInDictManager by LLyaudet 3 days, 2 hours ago
- MYSQL Full Text Expression by Bidaya0 3 days, 20 hours ago
- Custom model manager chaining (Python 3 re-write) by Spotted1270 1 week, 3 days ago
- Django Standard API Response Middleware for DRF for modern frontend easy usage by Denactive 3 weeks, 4 days ago
Comments
Please login first before commenting.