Search code examples
djangodjango-admin

Action to redirect users to URL


Could you tell me how to create an action in the admin site that will redirect users to a certain URL? That is, in the admin site a user chooses this action and finds themselves on Google.

def google(modeladmin, request, queryset):
    """
    I myself write some code here to prevent Django from asking users to select an object.
    """

    URL = "https://google.com"

    ... Here goes the code to redirect the user to URL ...

@admin.register(SemanticsCorePhrases)
class SemanticsCorePhrasesAdmin(admin.ModelAdmin):
    actions = [google, ]

Solution

  • To redirect a user to a URL in the Django admin site, you can use the redirect function from django.shortcuts.

    from django.shortcuts import redirect
    
    def google(modeladmin, request, queryset):
    
    """I myself write some code here to prevent Django from asking users to select an object.
    """
    
        URL = "https://google.com"
    
        return redirect(URL)
    
    @admin.register(SemanticsCorePhrases)
    class SemanticsCorePhrasesAdmin(admin.ModelAdmin):
        actions = [google, ]
    

    Please see https://docs.djangoproject.com/en/4.1/topics/http/shortcuts/#:~:text=xhtml%2Bxml%27)-,redirect,-()%C2%B6