Login

Username form field

Author:
sma
Posted:
November 16, 2008
Language:
Python
Version:
1.0
Score:
1 (after 1 ratings)

Use a UserField if you want to replace the usual select menu with a simple input field that only accepts valid user names. Should be easy to generalize for other models by passing a query set and the attribute name that represents the instance.

Example:

class Book(models.Model):
    owner = models.ForeignKey(User)

class BookForm(forms.ModelForm):
    owner = UserField()
    class Meta:
        model = Book
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
class UserField(forms.CharField): 
    class widget(forms.widgets.TextInput): 
        def render(self, name, value, attrs=None): 
            if isinstance(value, int): 
                value = unicode(User.objects.get(pk=value)) 
            return super(UserField.widget, self).render(name, value, attrs) 
        
    def clean(self, value): 
        value = super(UserField, self).clean(value) 
        if not value: 
            return None 
        try: 
            return User.objects.get(username=value) 
        except User.DoesNotExist: 
            raise forms.ValidationError(u'invalid user name') 

More like this

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

Comments

Please login first before commenting.