[Django]-NoReverseMatch error when creating new users through admin

6👍

You’ve replaced your primary key with a CharField but you’re still using Django’s UserAdmin ModelAdmin. Django’s UserAdmin doesn’t ask for the ID – it’s defaulting to an empty string. (You can verify this by checking for the empty string in the arguments from the NoReverseMatch Exception.)

You need to create a ModelAdmin that allows you to specify the ID so it doesn’t end up as an empty string. The following admin.py will allow you to specify the ID thus getting rid of your NoReverseMatch exception.

# -*- coding: utf-8 -*-
from __future__ import unicode_literals

from django.contrib import admin
from django.contrib.auth.admin import UserAdmin

from .models import MyUser

class MyUserAdmin(UserAdmin):
    add_fieldsets = (
        (None, {
            'fields': ('id', 'username', 'password1', 'password2'),
        }),
    )

# Register your models here.
admin.site.register(MyUser, MyUserAdmin)

0👍

you’d have register your model in admin site

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

admin.site.register(User, UserAdmin)

also you must have your model with id with integer number

class MyUser(AbstractUser):
     pass

0👍

The error message shows the url as /myuser/add and your urls say it only have the /myuser/change/ defined. Define the /myuser/add class/function view or update the url to point to the add class/function view.

0👍

after a long search and struggle, I found this solution really it’s working for me. its enables me to add edit API user from admin UI with my customizations.

you just need to add this code into your app’s admin.py file and only replace your custom model name with your model then it’s working fine.

import typing
from django.contrib import admin, messages
from django.db import models
from django.http.request import HttpRequest
from your_app.models import your_custom_model
from rest_framework_api_key.models import AbstractAPIKey

class APIKeyModelAdmin(admin.ModelAdmin):
    model: typing.Type[AbstractAPIKey]
    list_display = (
        "prefix",
        "name",
        "created",
        "_has_expired",
        "revoked",
    )
    list_filter = ("created",)
    search_fields = ("name", "prefix", "client_id")
    def get_readonly_fields(
        self, request: HttpRequest, obj: models.Model = None
    ) -> typing.Tuple[str, ...]:
        obj = typing.cast(AbstractAPIKey, obj)
        fields: typing.Tuple[str, ...]
        fields = ("prefix",)
        if obj is not None and obj.revoked:
            fields = fields + ("name", "revoked", "expiry_date")
        return fields

    def save_model(
        self,
        request: HttpRequest,
        obj: AbstractAPIKey,
        form: typing.Any = None,
        change: bool = False,
    ) -> None:
        created = not obj.pk
        if created:
            key = self.model.objects.assign_key(obj)
            obj.save()
            message = (
                "The API key for {} is: {}. ".format(obj.name, key)
                + "Please store it somewhere safe: "
                + "you will not be able to see it again."
            )
            messages.add_message(request, messages.WARNING, message)
        else:
            obj.save()

admin.site.register(your_custom_model, APIKeyModelAdmin)
👤Aman

Leave a comment