I'm starting to learn Django using Mongodb, creating a poll app following the djangoproject tutorial. I have a problem at the moment of raising a 404 error. If I do this:
def detail(request, poll_id):
try:
poll = Poll.objects.get(pk=poll_id)
except Poll.DoesNotExist:
raise Http404
return render(request, 'polls/detail.html', {'poll': poll})
it works, but if I try to use a django shortcut:
def detail(request, poll_id):
poll = get_object_or_404(Poll, pk=poll_id)
return render(request, 'polls/detail.html', {'poll': poll})
I get this error
Object is of type 'Poll', but must be a Django Model, Manager, or QuerySet
I think this error occurs because in models.py I've defined the Poll model as a mongoengine Document and not as a django Model
class Poll(Document):
What should I do to have the get_object_or_404() method working?
It's time to roll your own shortcut then?
def get_obj_or_404(klass, *args, **kwargs):
try:
return klass.objects.get(*args, **kwargs)
except klass.DoesNotExist:
raise Http404
def detail(request, poll_id):
poll = get_obj_or_404(Poll, pk=poll_id)
return render(request, 'polls/detail.html', {'poll': poll})
I haven't tested it yet but that's the basic idea.
I don't think you are doing anything wrong, it's just that that Django shortcut doesn't support the Document class. Check the Django source code, specifically the function get_object_or_404() (which uses the function _get_queryset(), the one that raised the exception you got) then I think you will understand.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With