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
- Template tag - list punctuation for a list of items by shapiromatron 10 months, 3 weeks ago
- JSONRequestMiddleware adds a .json() method to your HttpRequests by cdcarter 11 months ago
- Serializer factory with Django Rest Framework by julio 1 year, 5 months ago
- Image compression before saving the new model / work with JPG, PNG by Schleidens 1 year, 6 months ago
- Help text hyperlinks by sa2812 1 year, 7 months ago
Comments
Please login first before commenting.