Login

CodeLookupField

Author:
girasquid
Posted:
June 8, 2009
Language:
Python
Version:
1.0
Score:
0 (after 0 ratings)

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

  1. Template tag - list punctuation for a list of items by shapiromatron 3 months, 1 week ago
  2. JSONRequestMiddleware adds a .json() method to your HttpRequests by cdcarter 3 months, 2 weeks ago
  3. Serializer factory with Django Rest Framework by julio 10 months, 2 weeks ago
  4. Image compression before saving the new model / work with JPG, PNG by Schleidens 11 months ago
  5. Help text hyperlinks by sa2812 12 months ago

Comments

Please login first before commenting.