About change AUTH_USER_MODEL and customize the built-in User model - django

The doc says" If you intend to set AUTH_USER_MODEL, you should set it before creating any migrations or running manage.py migrate for the first time.".
So i want to double check about this, and is it possible to change the built-in User model the DB setup?

You can create your own user model rather than changing the built-in one. That's what AUTH_USER_MODEL does. It tells django to use your user model as the default, rather than the default django.contrib.auth.models.User.
You should do this once in the beginning of the project and then stick with whatever you have setup; as this setting has effects for many other areas of the framework. That is why there is a warning in the documentation.

Related

How to migrate default user data to custom user model in Django

As I want to customize Django user model, I migrated from default user model to my own custom user model. Since my Django project has been working since a long time ago, I need to keep the existing user data.
I was thinking to move them manually, but Django default user model's passwords are hidden. How can I safely move existing user data to my custom user model?
Moving to CustomUser is no easy task in Django. If you want to keep the existing data, then as per ticket #25313, you need to do the following steps:
Create a custom user model identical to auth.User, call it User (so many-to-many tables keep the same name) and set db_table='auth_user' (so it uses the same table).
Throw away all your migrations from all the apps(except for __init__.py file inside the migrations folder).
Recreate a fresh set of migrations(using python manage.py makemigrations).
Make a backup of your database.
Delete all entries from django_migrations table from DB.
Fake-apply the new set of migrations(using python manage.py migrate --fake).
Optional: Set db_table="your_custom_table" or remove it altogether.
Make other changes to the custom model, generate migrations, apply them.
You can dump your existing model data with dumpdata command and also able to reload those data to that model or your changed custom model with loaddata command. Here is a good example how you can able to do that. link

Don't apply existing migrations for a Django model

I need to tell Django not to apply already existing migrations for a model. Is there a way I can achieve it?
Why: I have some customizations on top of django.contrib.auth. With those, Group model is left unused. However, migrations for it are included into the auth app. Unlike User, Group is not swappable.
You can set MIGRATION_MODULES and django will use migrations from setted directory for app
MIGRATION_MODULES = {'django.contrib.auth': 'local_package'}
You can simply edit the migrations files.
So, simply comment out the parts you don't want to be applied.
You can also set your Model to be managed=False , but I'm not sure if that is what you need.

Django: issues migrating to custom user model

I've been writing a Django webapp without much concern for my User model- the provided model has been good, but I've realized that I'd like to be able to customize it somehow.
Starting from scratch with a custom user model looks pretty straightforward, but migrating to one while keeping existing users is a bit trickier, and has been giving me a lot of issues. I found this guide that uses a special package and has step-by-step instructions for my exact situation (Django 1.8, Python 3.4).
One of the prep steps is
You must have ensured that everywhere in your project (including 3rd party libraries) you are using AUTH_USER_MODEL and django.contrib.auth.get_user_model() rather than "auth.User" and django.contrib.auth.models.User.
My project isn't super complex- the only references to the User model are in ForeignKeys as well as a couple lines that get User objects.
Where should I use django.contrib.auth.get_user_model()? My impression is that ForeignKeys need to use settings.AUTH_USER_MODEL and any runtime operation (e.g. obj = User.objects.get(<criteria>) would set User with get_user_model(). Is that correct?
I currently have my AUTH_USER_MODEL setting like:
AUTH_USER_MODEL = User
as an intermediate step, with an import of django.contrib.auth.models.User at the top of settings.py.
I tried to switch my models to use the setting:
class League(models.Model):
name = models.CharField(max_length=100)
users = models.ManyToManyField(settings.AUTH_USER_MODEL)
However when I start the server, I keep getting an error about settings.py
raise ImproperlyConfigured("The SECRET_KEY setting must not be empty.")
django.core.exceptions.ImproperlyConfigured: The SECRET_KEY setting must not be empty.
What am I doing wrong here? The SECRET_KEY setting isn't empty, so I'm thinking there's a different error in the settings.
A little unclear where you're at right now in the switch from the default to your custom user, but like the docs say here, your AUTH_USER_MODEL should be set like:
AUTH_USER_MODEL = 'auth.User'
As a string, not importing the model directly. 'auth.User' is the default setting, so if you want to use the default user in your code just set it like that, and when you're ready to switch it over change it to whatever app name and model so: 'my_app.CustomUser'
You're getting the SECRET_KEY error because you're trying to import django.contrib.auth.models.User at the top of settings.py., and so it's importing other parts of the django library before the settings file, but the settings file is supposed to be loaded first.

Adding fields to user's personal info in Django admin page

I just started a Django project (there are no apps in it). I activated the admin in settings file and can access the Django administration page. There is a column in Django page to add users; while adding users I get only three fields under personnal info, but I need to store some more information about users. I Googled around and found that I can use user profiles to accomplish this. I tried, but I am having problems.
My aim is to add three more fields to the user table:
role
contact number
other
I need details like: which function I need to write and where to do this.
I found this, but I do not know where I need to write these steps. I would greatly appreciate a more clear explanation of this.
Django User Profiles is what you need. The blog you linked to has clear steps on how to do it. You can check out the Django documentation. http://www.turnkeylinux.org/blog/django-profile also provides a good explanation.
Basically you need to create a new model with User as ForeignKey and define the model in the settings.py as AUTH_PROFILE_MODULE = "django_app.your_profile_modelname". Create the profile and save it just like any other model, and access it using user.get_profile()
Adding a couple of things in response to your questions below:
First, do not create apps as a directory. Use startapp <appname> [destination] as described here. That will create the app directory.
Second, you have to add the app to INSTALLED_APPS in the project's settings file, do a syncdb. Basically, follow the steps in Django tutorial on writing your first app.
Third, UserProfile is a separate model. It is not an extension of User. It is associated with the User just because you added User as the ForeignKey.
Fourth, to be able to see the user profile model in admin, you do exactly what you would do to add any other model to admin page. Create a file names admin.py under your app with:
from django.contrib import admin
from myproject.app.models import UserProfile
admin.site.register(UserProfile)
There are three key concepts to understand:
There is no built in "profile" system in Django, beyond the limited auth app which is really geared just to user login. You are expected to roll your own.
There is nothing magical about a profile record in itslef, it is just like any other record that takes User as a foreign key (or, more properly, a one-to-one field as per the docs). You create it by creating a custom django app (traditionally called profiles) and a model for that app (traditionally called UserProfile, since Profile is not allowed as a model name).
The only thing that sets UserProfile aparts as a model is that you specify it as the AUTH_PROFILE_MODULE which means that it is accessible when called .get_profile() on a User record. That's it. If you set up the UserProfile like so:
def UserProfile(models.Model):
user = models.OneToOneField(User, related_name='profile')
other fields
then you can also access the profile as user.profile rather than user.get_profile() which some people prefer.
Again, nothing magical about the profile model -- it is just a model record like any other model record.
If you want to be able to edit additional fields within the user form that's more complicated; easiest way is probable unregister User and then register it again using your custom ModelAdmin and form class but judging by your question you're probably not at that level yet.

Django custom User model authentication

Since i'm not using the Auth User from Django, I have my own model CustomUser and I want make authentication on site through this model (CustomUser does not inherit from User model and not related to it at all).
class CustomUser(models.Model):
password = models.CharField(max_length = 40)
email = models.EmailField(max_length = 72, unique = True)
#stuff...
I checked https://docs.djangoproject.com/en/dev/topics/auth/#writing-an-authentication-backend and the main thing I don't understand is:
from django.contrib.auth.models import User
Do I need to import Django User if I want to use my CustomUser?
I can't find a good tutorial which explains how you can use Django without standard Auth User.
*edit:
I know I can extend with User. But I just don't want that. The question is not: what is the best way to use User and store additional information etc etc. I appreciate it though.
BUT how I can use a Custom User without using Auth User. Even if I don't have a reason to. *
If it is possible I want to know how.
The whole Django auth system is tightly coupled with django.contrib.auth.models.User, so you should use it in the backend. Quoting Django docs
For now, the best way to deal with this is to create a Django User object for each user that exists for your backend
But the main question here is: what is so special about your CustomUser that you can't implement with normal User model (may be extended)? In 99% of cases using User is the best way.
Check out this post.
Most of the Django projects I’ve worked on need to store information about each user in addition to the standard name and email address held by the contrib.auth.models.User model.
If you’re using trunk as of revision 7477 (26th April 2008), your model classes can inherit from an existing model class. Additional fields are stored in a separate table which is linked to the table of the base model. When you retrieve your model, the query uses a join to get the fields from it and the base model.
http://scottbarnham.com/blog/2008/08/21/extending-the-django-user-model-with-inheritance/
And this post.
Copy the auth application over into your own project and modify it to your needs. This avoids some of the maintenance troubles, but removes the utility of Django bundling an auth system in the first place. It can also cause compatibility problems with other applications which expect the User model to be in django.contrib.auth.
http://www.b-list.org/weblog/2006/jun/06/django-tips-extending-user-model/
Perhaps this answers your question:
From 'https://docs.djangoproject.com/en/1.6/topics/auth/customizing/#substituting-a-custom-user-model':
Substituting a custom User model
New in Django 1.5.
Some kinds of projects may have authentication requirements for which Django’s built-in User model is not always appropriate. For instance, on some sites it makes more sense to use an email address as your identification token instead of a username.
Django allows you to override the default User model by providing a value for the AUTH_USER_MODEL setting that references a custom model:
AUTH_USER_MODEL = 'myapp.MyUser'
This dotted pair describes the name of the Django app (which must be in your INSTALLED_APPS), and the name of the Django model that you wish to use as your User model.
Of course there are some requisite warnings to consider (available at the above link), but this is looking like a good answer to your question: https://docs.djangoproject.com/en/1.6/ref/settings/#auth-user-model
There are also some custom model compliance expectations to consider (too many to list here): https://docs.djangoproject.com/en/1.6/topics/auth/customizing/#specifying-a-custom-user-model
Unless there can be more than one value for AUTH_USER_MODEL (I doubt that is sane), then I think I will need to build my own custom authentication backend: https://docs.djangoproject.com/en/1.6/topics/auth/customizing/#writing-an-authentication-backend
I hope this helps any other lost souls out there that need distinct User and Device authentication schemes (perhaps because of some pre-existing spec that makes messy what could be soooo easy).
Cheers!