[Answered ]-Importing classes from another app in Django

2👍

You can’t do import accounts.forms.UserForm because UserForm is a class, not a module. You can however do:

import accounts.forms
form = accounts.form.UserForm(request.POST)

Personally, I prefer your first approach. As long as UserForm doesn’t clash with another UserForm from account.views it won’t cause any problems. The import shows you where it has been imported from, so I don’t think ‘Explicit is better than implicit’ is an issue here.

from accounts.form import UserForm
form = UserForm(request.POST)

0👍

When we import anything python search for the named module not for class or function. UserForm is a class according to you, thats why import accounts.forms.UserForm is not working. You can also do it by:

from accounts.forms import *
form = UserForm(request.POST)

For more on import statement you can go https://docs.python.org/3/reference/import.html and https://docs.python.org/3/reference/simple_stmts.html#import

Leave a comment