0

I have a variable initialised with class name. But, when I use this variable for accessing the class based view, it show the error 'str' object has no attribute 'as_view'. How to get the class from a string variable ..?

classname = "GetAjaxView"
return classname.as_view()(request)
Jinto Antony
  • 458
  • 8
  • 26

1 Answers1

1

How about

eval(classname).as_view()(request)?

I'm assuming you don't know what class you want to use in advance, because otherwise you could write GetAjaxView.as_view()(request).

If you are generating the string from user input, do not use eval; instead, devise a solution that only responds to the input that you're expecting, perhaps something like:

if classname == "GetAjaxView":
  return GetAjaxView.as_view()(request)
elif classname in ["GetHectorView", "GetUlyssesView"]:
  return eval(classname).as_view()(request)
else:
  return defaults.server_error(request, template_name='500.html')
user234461
  • 1,133
  • 12
  • 29
  • Yes. That's right. The classname is dynamic. Yes, this works. All I needed was eval(). I think, using a dict is better from your suggestions. – Jinto Antony May 02 '18 at 11:51
  • Yes, using a dict, like this: `{'GetAjaxView' : GetAjaxView, 'GetHectorView': GetHectorView}[classname]` seems like a safe and concise solution – user234461 May 02 '18 at 13:13
  • I am changing all that now. Thanks.Can you upvote my question ? I am new to Django and I have so many doubts, therefore I put too many questions and now I can't ask questions anymore. – Jinto Antony Jul 11 '18 at 04:57
  • @JintoAntony Sounds like you might wish to reconsider how you ask questions, unless you've just been unlucky with the downvote brigade. If you think my answer was useful, please upvote and/or accept it. – user234461 Jul 11 '18 at 13:35