Upgrading Django to 1.5 with Django-CMS - user model issue - django

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.

Related

Django: UserCreationForm not getting Custom User Class

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.

How make Django's auth app use my custom model "User"

Hello I am very new to Django, and I am making an app that stores a lot of information about the user. But django's auth app stores only a bit of information about the user. Is there any way I can create my own model "User" and make Django's auth app use this model. Thanks.
This has been supported since Django 1.5, and is fully covered in the documentation.
Basically, you need to subclass auth.models.AbstractUser, and set the AUTH_USER_MODEL setting to point to your new model.
You can solves your problem with UserProfile model. And you can store the user extra information in this with relation of onetone or ForeignKey with unique property field.
Django user profile
U can multi-table inheritance the user model
from django.contrib.auth import User
class MyUser(User):
//add ur required fields
Reference for in heritance.

django - Extending `auth.models.User` and usering login, logout

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

How to properly extend django User model

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

Django admin - instance needs to have a primary key value before a many-to-many relationship can be used

edit: I wasn't clear before, I am saving my object in the django admin panel, not in a view. Even when I save the object with no many-to-many relationships I still get the error.
I have a model called TogglDetails that has a ForeignKey relationship with the standard django User model and a MayToManyField relationship with a model named Tag. I have registered my models with django admin but when I try to save a TogglDetails instance I get the error in the title.
Here are my models:
class Tag(models.Model):
name = models.CharField(max_length=30)
def __unicode__(self):
return self.name
class TogglDetails(models.Model):
token = models.CharField(max_length=100)
user = models.ForeignKey(User)
tags = models.ManyToManyField(Tag, blank=True, null=True)
def __unicode__(self):
return self.user.username
class Meta:
verbose_name_plural = "toggl details"
As far as I can tell, there should be no issues with my models and django admin should just save the instance without any issues. Is there something obvious that I have missed?
I am using Django 1.3
The answer to my question was this: Postgres sequences without an 'owned by' attribute do not return an id in Django 1.3
The sequences in my postgres database did not have the "Owned by" attribute set and so did not return an id when a new entry was saved to the db.
As stated by other users:
Postgres sequences without an 'owned by' attribute do not return an id in Django 1.3
The sequences in my postgres database did not have the "Owned by" attribute set and so did not return an id when a new entry was saved to the db
In addition:
This is most likely caused by a backwards incompatible change that renders some primary key types in custom models beyond reach for Django 1.3. See Django trac tickets https://code.djangoproject.com/ticket/13295 and http://code.djangoproject.com/ticket/15682 for more information.
I solved the problem by running the follow commands for the affected tables/sequences.
Specifically running the command:
manage.py dbshell
ALTER SEQUENCE tablename_colname_seq OWNED BY tablename.colname;
change tablename_colname_seq and tablename.colname
Don't let us guess and add the Error message to your question, this gives most information about where it fails.
Have you imported the User model?
from django.contrib.auth.models import User
I've had this problem as well and the only thing I could do was make the M2M fields blank and not set them until I hit Save and Continue Editing.
I think this just may be a framework wart, as you will notice the User section of the Admin site also has a very strict "You can only edit these fields until you save the model".
So my recommendation is to adopt that scheme, and hide the M2M form field until the model has a Primary Key.
I tried Django 1.3 using CPython, with different database setups. I copy-pasted the models from the question, and did some changes: first I added
from django.contrib.auth.models import User
at the top of the file and I put the reference to Tag between quotes. That shouldn't make any difference. Further, I created the following admin.py:
from django.contrib import admin
import models
admin.site.register(models.Tag)
admin.site.register(models.TogglDetails)
For Sqlite3, the problem described doesn't occur, neither for MySQL. So I tried PostgreSQL, with the postgresql_psycopg2 back end. Same thing: I can't reproduce the error.
So as far as I can figure, there's nothing wrong with the code in the question. The problem must be elsewhere.