How to call HttpResponse from external function?

217 views Asked by At

I have a views.py (FBV):

def photoalbum_GET(request, album_id):
o = get_object_or_404_alt(PhotoAlbum, id=album_id)
return response_message('', 200)

The function get_object_or_404_alt() is called from outside file my_shortcuts.py:

def get_object_or_404_alt(klass, *args, **kwargs):
queryset = _get_queryset(klass)
try:
    object = queryset.get(*args, **kwargs)
    if object.is_deleted:
        return HttpResponse('Object was deleted', 404)
    if object.is_active == False:
        return HttpResponse('Object is not active', 403)
    ...

    return object
except queryset.model.DoesNotExist:
    raise Http404('No %s matches the given query.' % queryset.model._meta.object_name)

But this snipper does not work. The method HttpResponse() in get_object_or_404_alt() is not raised.

How can I call it in an external python file as I described?

2

There are 2 answers

0
Wtower On

Additionally to @f43d65 's answer, HttpResponse has to be:

    if object.is_deleted:
        return HttpResponse('Object was deleted', status_code=404)
    if object.is_active == False:
        return HttpResponse('Object is not active', status_code=403)

Reference: Django documentation: Request and response: HttpResponse

0
f43d65 On
def photoalbum_GET(request, album_id):
    o = get_object_or_404_alt(PhotoAlbum, id=album_id)
    if isinstance(o, HttpResponse):
        return o
    return response_message('', 200)

HttpResponse is not method, but class. And it is not exception to be raised.