开发者

Making a CharField use a PasswordInput in the admin

I have a Django site in which the site admin inputs their Twitter 开发者_如何学PythonUsername/Password in order to use the Twitter API. The Model is set up like this:

class TwitterUser(models.Model):
screen_name = models.CharField(max_length=100)
password = models.CharField(max_length=255)
def __unicode__(self):
    return self.screen_name

I need the Admin site to display the password field as a password input, but can't seem to figure out how to do it. I have tried using a ModelAdmin class, a ModelAdmin with a ModelForm, but can't seem to figure out how to make django display that form as a password input...


From the docs, you can build your own form, something like this:

from django.forms import ModelForm, PasswordInput

class TwitterUserForm(ModelForm):
    class Meta:
        model = TwitterUser
        widgets = {
            'password': PasswordInput(),
        }

Or you can do it like this:

from django.forms import ModelForm, PasswordInput

class TwitterUserForm(ModelForm):
    password = forms.CharField(widget=PasswordInput())
    class Meta:
        model = TwitterUser

I've no idea which one is better - I slightly prefer the first one, since it means you'll still get any help_text and verbose_name from your model.

Regardless of which of those two approaches you take, you can then make the admin use your form like this (in your app's admin.py):

from django.contrib import admin

class TwitterUserAdmin(admin.ModelAdmin):
    form = TwitterUserForm

admin.site.register(TwitterUser, TwitterUserAdmin)
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜