Login

Username form field

Author:
sma
Posted:
November 16, 2008
Language:
Python
Version:
1.0
Tags:
user form field username textual
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. Duplicate related objects of model instance by johnboxall 6 years, 2 months ago
  2. PatchModelForm - A ModelForm subclass with the semantics of the PATCH HTTP method by gnrfan 2 years, 10 months ago
  3. UnicodeReprMixIn by ashcrow 6 years, 2 months ago
  4. ISBN model field: displays 10- and 13-digit variants and external links by fish2000 4 years, 11 months ago
  5. UsernameField (for clean error messages) by davepeck 5 years, 7 months ago

Comments

Please login first before commenting.