简体   繁体   中英

Adding a Django Action to User Admin

I'm using the Django User model for my users. What I need is to add an action on the User admin that will enable me to send a text message to the users I'll have selected. This is how it's supposed to work:

  • I log into Django admin
  • Select the Users model
  • Select a user from the list of users and then select the "Send Message" action I have created.
  • I should be redirected to another page that will have the selected user names, and fields from a "Text Message" model that I have created to handle text messages.

So far I've had to create another model:

class UserProfile(models.Model):
    user = models.OneToOneField(User) #extended the User model
    phone_number = models.CharField(u'Number', max_length=20)

and then the form for the Text Messages:

class TextMessageForm(ModelForm):
    class Meta:
        model = TextMessage
        fields = ('sender', 'to', 'message')

but I'm having trouble adding an action to the User model(raises an "model already registered error" which I solved by unregistering but then the passwords in the User model are viscible. That's why I created the UserProfile model)

So, can I be able to add an action to the User model without having to mess with how it'll display stuff on the admin? Can I have the action redirect to the text form(or another template for that matter)? Or is this a bad way to think of it... I'm using this API to send my texts. Any direction you can offer?

You could extend the UserAdmin admin page:

# admin.py
from django.contrib import admin
from django.contrib.auth.admin import UserAdmin
from django.contrib.auth.models import User

# Define a new User admin
class UserAdmin(UserAdmin):
    """My User Admin"""
    # eg.
    form = MyFancyForm
    # or use my fancy template for the form
    add_form_template = 'myadmin/user/add_form.html'
    # or maybe add it to the change list
    change_list_template = 'myadmin/user/change_list.html'

# Re-register UserAdmin
admin.site.unregister(User)
admin.site.register(User, UserAdmin)

https://docs.djangoproject.com/en/1.7/topics/auth/customizing/#extending-the-existing-user-model

If you just want to add a button to go to another page to send a message, I'd modify the list template to add that button.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM