I'm trying to extend the default Django's authentication model with additional fields and functionaliy, so I've decided to just go with extending User model and writing my own authentication backend.
from django.db import models
from django.utils.translation import ugettext_lazy as _
from django.contrib.auth.models import User
class MyUser(User):
access_key = models.CharField(_('Acces Key'), max_length=64)
This is really a basic code yet when trying to syncdb I'm cetting a strange error that Google doesn't know about :
CommandError: One or more models did not validate:
core.sldcuser: 'user_ptr' defines a relation with the model 'auth.User', which has been swapped out. Update the relation to point at settings.AUTH_USER_MODEL.
In my settings.py I've added what I guess is required :
AUTH_USER_MODEL = 'core.MyUser'
Had anyone stumbled upon this error ?
Or maybe I should use a one-to-one way, or a hybrid of 1t1 with proxy ?
What you're doing right now, is creating a subclass of User, which is non-abstract. This means creating a table that has a ForeignKey called user_ptr pointing at the primary key on the auth.User table. However, what you're also doing by setting AUTH_USER_MODEL is telling django.contrib.auth not to create that table, because you'll be using MyUser instead. Django is understandably a little confused :P
What you need to do instead is inherit either from AbstractUser or AbstractBaseUser.
Use AbstractUser if you want everything that User has already, and just want to add more fields
Use AbstractBaseUser if you want to start from a clean state, and only inherit generic functions on the User, but implement your own fields.
REF:
https://docs.djangoproject.com/en/dev/topics/auth/customizing/#extending-the-existing-user-model
https://docs.djangoproject.com/en/dev/topics/auth/customizing/#substituting-a-custom-user-model
Related
I have created a custom user model before making any migration and I wanted to move it from the app panel to the auth panel in the admin page.
To do that I created a proxy user model:
class User(AbstractUser):
pass
class ProxyUser(User):
pass
class Meta:
app_label = 'auth'
proxy = True
and then in admin.py:
from django.contrib.auth.admin import UserAdmin
from .models import ProxyUser
admin.site.register(ProxyUser, UserAdmin)
The problem is that the auth_permission table has permissions for user and proxyuser.
Can't understand why if I'm using a proxy and only one user table was created the permissions table behaves as if there were two (proxyuser and user).
Am I missing something?
Thanks in advance
Django uses the content type framework to keep track of "permissions" for various models. Proxy models get their own permissions.
This is explained in the authentication section of Django docs:
Proxy models work exactly the same way as concrete models. Permissions are created using the own content type of the proxy model. Proxy models don’t inherit the permissions of the concrete model they subclass
I feel what you're trying to achieve with the proxy model is unnecessary. I personally wouldn't worry much about 'Users' appearing under a separate section in the Django Admin. You will instead add unnecessary complexity to the code by using a proxy model (A future developer/you would wonder wether to use the custom User class or the ProxyUser class).
You may have done all migrations and no only for your apps, if you don't specify the app to migrate, Django makes all of the migrations. On the other way, maybe you can't log into the admin site if you doesn't do it.
I'm new to Django and I'm running into an odd issue. Using Django 2.2.5 I've created a custom User class, sub-classed from AbstractBaseUser. Other than extending AbstractBaseUser the only major change I made was deleting the username field and adding my own (won't get into why here). I've added the USERNAME_FIELD = "my new username" to the model as well.
This all appeared to work well and I was able to create users. I then installed django-registration, to use that functionality and when I tried to makemigrations I ran into this error:
'django.core.exceptions.FieldError: Unknown field(s) ("My new username") specified for User`
Now, this didn't make any sense to me since the model clearly has a"My new username" field and I'd specified Django should use my User model in setting via AUTH_USER_MODEL. I knew that was working because calling get_user_model() in a shell returned my custom model.
Now here's where it gets weird, I was able to trace the issue to django-registrations, RegistrationForm. This is a form that subclasses Django's UserCreationForm. When RgistrationForm was loading or whatever during makemigrations it was producing the error because the model reference for the form was django.User not my custom user model. RegistrationForm does not declare a model and uses UserCreationForm model which happens to be User from django.contrib.auth.models.
Based on what I've read and how User is written it should reference my model, via the swappable attribute since I've set AUTH_USER_MODEL and it's supposed to swap to the model located in that settings option. For some reason, though it's not working and I don't know enough about Django to debug further.
I'm very confused by this since get_user_model() references the exact same setting and it works.
I've been able to fix this for the moment by editing the RegistrationForm model to add model = "Custom user model in django-registration's forms. I'd rather not have to distribute a custom version of this package with the rest of the site at the moment.
Any idea what's going on with swappable that might be causing this issue?
Edit 1/27/19: Update I tried sub-classing the relevant django-registration classes, but it turns out that simply importing RegistrationForm causes the issue. Importing UserCreationForm does not immediately cause a problem but if I try to check UserCreationForm.Meta.model."My new username" it provides this error:
AttributeError: type object 'User' has no attribute 'UVI_Handle'
This is consistent with the error above. At this point I'm not sure how to proceed again. I could subclass UserCreationForm, but none of django-registration will pick up on that so there doesn't seem to be a point in using it, since I'll have to copy the whole thing.
Instead of changing the package code, you should subclass:
In the case where your user model is compatible with the default
behavior of django-registration, (see below) you will be able to
subclass RegistrationForm, set it to use your custom user model as the
model, and then configure the views in django-registration to use your
form subclass. For example, you might do the following (in a forms.py
module somewhere in your codebase – do not directly edit
django-registration’s code):
from registration.forms import RegistrationForm
from mycustomuserapp.models import MyCustomUser
class MyCustomUserForm(RegistrationForm):
class Meta:
model = MyCustomUser
Above is taken from here, you should also change the urls, which is also described there.
If I create a CustomUser model which inherits from django.contrib.auth.models.User, like so:
in models.py
class CustomUser(django.contrib.auth.models.User):
customfield = TextField()
...
Should I still be able to use
django.contrib.auth.{authenticate, login, logout} in the normal way? Do I have to make some additional configuration change? I know these methods only work on User objects, but technically my CustomUser is-a User.
Currently, authenticate(username=u, password=p) is always returning None, even with valid credentials.
Since Django 1.5 (officially but it doesn't worked for me) and "stable" in 1.6 there is a functionality to extend the User model in a clean way.
At first:
-> Take care that you load the User model only via:
from django.contrib.auth import get_user_model
User = get_user_model()
-> Once you have built the database theres no easy way to change the User model. The database relations will break and Django / South isn't able to fix it.
-> third party modules have to be compatible with that new layout and refer in it's models to "get_user_model()", too.
You have to add some Code for the admin to respect your new model:
See: https://docs.djangoproject.com/en/dev/topics/auth/customizing/#extending-the-existing-user-model
To Override the model you need to inherit from AbstractBaseUser:
from django.contrib.auth.models import AbstractBaseUser
class MyUser(AbstractBaseUser):
...
date_of_birth = models.DateField()
height = models.FloatField()
...
REQUIRED_FIELDS = ['date_of_birth', 'height']
AbstractBaseUser provides you all attributes of the default user model. So you don't have to take care of email, username, first_name, last_name, password etc.
More info about overriding the user model: https://docs.djangoproject.com/en/dev/topics/auth/customizing/#django.contrib.auth.models.CustomUser
In your settings link your new model:
AUTH_USER_MODEL = 'customauth.MyUser'
Please read the whole documentation of customizing the user model, there are some interesting hints for overriding the default manager, admin forms etc. Just remember that bigger changes in an existing project can be a big pain.
A short overview:
- Extend models.AbstractUser
- Set AUTH_USER_MODEL in settings.py
All details can be found here: https://docs.djangoproject.com/en/dev/topics/auth/customizing/#specifying-a-custom-user-model
I have just moved a site from Django-CMS 2.3.5 to 2.4.1 (with help from Stackoverflow) under Django 1.4.
I am now upgrading to Django 1.5, which is only hard because I need to update the old separate user profile to a new custom user model. I followed the excellent instructions here, and also replaced all references to User with settings.AUTH_USER_MODEL.
Unfortunately Django-CMS's models apparently still refer to User though: when I type manage.py runserver, I get this error:
CommandError: One or more models did not validate:
cms.pagemoderatorstate: 'user' defines a relation with the model 'auth.User', which has been swapped out. Update the relation to point at settings.AUTH_USER_MODEL.
cms.globalpagepermission: 'user' defines a relation with the model 'auth.User', which has been swapped out. Update the relation to point at settings.AUTH_USER_MODEL.
cms.pagepermission: 'user' defines a relation with the model 'auth.User', which has been swapped out. Update the relation to point at settings.AUTH_USER_MODEL.
cms.pageuser: 'user_ptr' defines a relation with the model 'auth.User', which has been swapped out. Update the relation to point at settings.AUTH_USER_MODEL.
cms.pageuser: 'created_by' defines a relation with the model 'auth.User', which has been swapped out. Update the relation to point at settings.AUTH_USER_MODEL.
cms.pageusergroup: 'created_by' defines a relation with the model 'auth.User', which has been swapped out. Update the relation to point at settings.AUTH_USER_MODEL.
How can I get Django-CMS to use the new user model?
thanks!
There is very simple solution. Just need to register your custom user before importing CMSPlugin. Example:
from django.db import models
from django.contrib.auth import models as auth_models
from django.contrib.auth.models import AbstractUser
class User(AbstractUser):
telephone = models.CharField(max_length=100)
email = models.CharField(max_length=100)
auth_models.User = User
from cms.models import CMSPlugin
For others with this question, here is my summary of what I have learned from https://github.com/divio/django-cms/issues/1798.
There are four potential options:
If you need your custom user model to have a name other than User, you'll need to wait.
You can call the custom user model User - though when I tried this, I got errors about clashes with related m2m fields. There are some further details on the above link which may help resolve this.
Django 1.5 still lets you use user profiles. So if you are ok with using a deprecated feature, you can still use Django-CMS 2.4 and Django 1.5 with user profiles instead of a custom user model. (I misread the Django docs here and thought user profiles were not supported in Django 1.5.)
You can often get away without either a user profile or a custom user model - they are best used to add data specifically for user authentication. Instead, you can use another model with a one-to-one relationship to User, and use the reverse relationship to access it.
In my case, I am going to go with #3 in the short-run and #4 in the long-run.
I have a model with a generic relation:
TrackedItem --- genericrelation ---> any model
I would like to be able to generically get, from the initial model, the tracked item.
I should be able to do it on any model without modifying it.
To do that I need to get the content type and the object id. Getting the object id is easy since I have the model instance, but getting the content type is not: ContentType.object.filter requires the model (which is just content_object.__class__.__name__) and the app_label.
I have no idea of how to get in a reliable way the app in which a model is.
For now I do app = content_object.__module__.split(".")[0], but it doesn't work with django contrib apps.
The app_label is available as an attribute on the _meta attribute of any model.
from django.contrib.auth.models import User
print User._meta.app_label
# The object name is also available
print User._meta.object_name
You don't need to get the app or model just to get the contenttype - there's a handy method to do just that:
from django.contrib.contenttypes.models import ContentType
ContentType.objects.get_for_model(myobject)
Despite the name, it works for both model classes and instances.
You can get both app_label and model from your object using the built-in ContentType class:
from django.contrib.contenttypes.models import ContentType
from django.contrib.auth.models import User
user_obj = User.objects.create()
obj_content_type = ContentType.objects.get_for_model(user_obj)
print(obj_content_type.app_label)
# u'auth'
print(obj_content_type.model)
# u'user'
This is better approach respect of using the _meta properties that are defined for private purposes.