Django Project structure, recommended structure to share an extended auth “User” model across apps?

女生的网名这么多〃 提交于 2019-12-06 16:38:08

Why are you extending User? Please clarify.

If you're adding more information about the users, you don't need to roll your own user and auth system. Django's version of that is quite solid. The user management is located in django.contrib.auth.

If you need to customize the information stored with users, first define a model such as

class Profile(models.Model):
    ...
    user = models.ForeignKey("django.contrib.auth.models.User", unique=True)

and then set

AUTH_PROFILE_MODULE = "appname.profile"

in your settings.py

The advantage of setting this allows you to use code like this in your views:

def my_view(request):
    profile = request.user.get_profile()
    etc...

If you're trying to provide more ways for users to authenticate, you can add an auth backend. Extend or re-implement django.contrib.auth.backends.ModelBackend and set it as your AUTHENTICATION_BACKENDS in settings.py.

If you want to make use of a different permissions or groups concept than is provided by django, there's nothing that will stop you. Django makes use of those two concepts only in django.contrib.admin (That I know of), and you are free to use some other concept for those topics as you see fit.

You should check first if the contrib.auth module satisfies your needs, so you don't have to reinvent the wheel:

http://docs.djangoproject.com/en/dev/topics/auth/#topics-auth

edit:

Check this snippet that creates a UserProfile after the creation of a new User.

def create_user_profile_handler(sender, instance, created, **kwargs):
    if not created: return

    user_profile = UserProfile.objects.create(user=instance)
    user_profile.save()

post_save.connect(create_user_profile_handler, sender=User) 

i think the 'project/app' names are badly chosen. it's more like 'site/module'. an app can be very useful without having views, for example.

check the 2008 DjangoCon talks on YouTube, especially the one about reusable apps, it will make you think totally different about how to structure your project.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!