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)

1 Answer 1

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')
Sign up to request clarification or add additional context in comments.

4 Comments

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.
Yes, using a dict, like this: {'GetAjaxView' : GetAjaxView, 'GetHectorView': GetHectorView}[classname] seems like a safe and concise solution
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.
@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.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.