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
- Image compression before saving the new model / work with JPG, PNG by Schleidens 1 week ago
- Help text hyperlinks by sa2812 1 month ago
- Stuff by NixonDash 3 months, 1 week ago
- Add custom fields to the built-in Group model by jmoppel 5 months, 1 week ago
- Month / Year SelectDateWidget based on django SelectDateWidget by pierreben 8 months, 3 weeks ago
Comments
Please login first before commenting.