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
- Template tag - list punctuation for a list of items by shapiromatron 10 months, 1 week ago
- JSONRequestMiddleware adds a .json() method to your HttpRequests by cdcarter 10 months, 2 weeks ago
- Serializer factory with Django Rest Framework by julio 1 year, 5 months ago
- Image compression before saving the new model / work with JPG, PNG by Schleidens 1 year, 6 months ago
- Help text hyperlinks by sa2812 1 year, 6 months ago
Comments
Please login first before commenting.