Login

CodeLookupField

Author:
girasquid
Posted:
June 8, 2009
Language:
Python
Version:
1.0
Tags:
forms field
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. Automatically trim newforms text fields by miracle2k 7 years, 10 months ago
  2. User or Group entry field & widget by Scanner 8 years, 2 months ago
  3. Currency Fields with newforms by sago 8 years, 3 months ago
  4. Convert Unicode to ASCII by coordt 7 years, 5 months ago
  5. List all errors in a form +bootstrap highlighting by ibrahimlawal 2 years, 10 months ago

Comments

Please login first before commenting.