0
votes

Trying to limit my objects to 1 in admin pages. I get "newuserpath object with primary key u'add/foo' does not exist." It would be ok if it would just return without setting anything, but ideally with an error message. This is what I have in my admin.py.

from django.contrib import admin
from fileman.models import Newuserpath
from django.http import HttpResponseRedirect

class NewuserpathAdmin(admin.ModelAdmin):
    def add_view(self, request):
        if request.method == "POST":
            # Assuming you want a single, global Newuserpath object
            if Newuserpath.objects.count() > 0:
                # redirect to a page saying 
                # you can't create more than one
                return HttpResponseRedirect('foo')
        return super(NewuserpathAdmin, self).add_view(request)

admin.site.register(Newuserpath, NewuserpathAdmin)

I'm following the best answer here: Is it possible to limit of object creation of a model in admin panel?

It just doesn't quite work.I tried using the other method by adding code in forms.py and importing it from there. But I'm unsure of how to use that in my admin.py.

1

1 Answers

0
votes

The error is simply that you are using a relative path for your redirect - so the browser is adding 'foo' to the existing URL, admin/app/newuserpath/add/.

The best way to manage this is to use the URL reverse function - assuming you have given your error page URLconf the name 'newuserpath_error':

return HttpResponseRedirect(reverse('newuserpath_error'))