Correct way to extend AbstractUser in Django? - python

I'm trying to integrate two django apps where each had their individual auths working. To do that, I'm trying to subclass AbstractUser instead of User. I'm following the PyBB docs and Django#substituting_custom_model. I've removed all migration files in all my apps apart from their individual init.py (including the migrations from the PyBB library sitting in my site-packages). I've also changed the Mysql database to a blank one to start afresh and I'm trying to subclass AbstractUser as shown below.
My Models.py:
from django.contrib.auth.models import User
from django.contrib.auth.models import AbstractUser
from django.db import models
class Student_User(models.Model):
"""
Table to store accounts
"""
su_student = models.OneToOneField(AbstractUser)
USERNAME_FIELD = 'su_student'
su_type = models.PositiveSmallIntegerField(db_column='su_type', default=0)
su_access = models.TextField(db_column='su_access', default='')
su_packs = models.TextField(db_column='su_packs', default='')
REQUIRED_FIELDS = []
def __unicode__(self):
return str(self.su_student)
My settings.py:
AUTH_USER_MODEL = "app.Student_User"
PYBB_PROFILE_RELATED_NAME = 'pybb_profile'
When running makemigrations for my primary app, I get this error:
app.Student_User.su_student: (fields.E300) Field defines a relation with model 'AbstractUser', which is either not installed, or is abstract.
How do I achieve what I am trying to do here?
PS: The app was working fine with onetoone with User without username_field or required_field.
PPS: I just checked the AbstractUser model in my contrib.auth.models and it has class Meta: abstract = True. Ok so its abstract, still, how do I resolve this? I just need one login, currently, two parts of my site, although connected through urls, ask for seperate logins and dont detect each others logins. What do I need to do for this?

You can't have a one-to-one relationship with an abstract model; by definition, an abstract model is never actually instantiated.
AbstractUser is supposed to be inherited. Your structure should be:
class Student_User(AbstractUser):
...

Related

How to reference allauth user as foreign key in Django

If I use normal user provided django default, my model will be like this.
from django.db import models
from django.contrib.auth.models import Users
class Photo(models.Model):
photographer=models.ForeignKey(User, on_delete=models.CASCADE, related_name='user') # 5
# other fields
If I want to implement allauth, what should I have to pass for the first argument in line#5, instead of User?
Django-allauth still uses the User model from django's auth, so you don't have to change anything. Unless you've extended a custom user model.

Two models pointing to one database table in Django 2.1

I'm working on a Django project made by a former employee of the company (so I'm refactoring a whole project made by somebody else that didn't follow Django Best Practices), that have two models on different apps using the same tables on database. The City and State tables are used in both apps.
I want to know which is the best way to apply DRY concepts and use only one model for the two apps access these tables.
The two apps are on the project folder and each one has his own models.py with the following code for city/state:
from django.db import models
from django.contrib.auth.models import User,Group
from django.db.models.signals import post_save
from django.dispatch import receiver
class state(models.Model):
class Meta:
db_table = '"db_property"."state"'
created_at = models.DateTimeField(db_column='created_at')
updated_at = models.DateTimeField(db_column='updated_at')
name = models.CharField(db_column='name',max_length=50)
class city(models.Model):
class Meta:
db_table = '"db_property"."city"'
created_at = models.DateTimeField(db_column='created_at')
updated_at = models.DateTimeField(db_column='updated_at')
name = models.CharField(db_column='name',max_length=50)
state = models.ForeignKey(state,on_delete=models.CASCADE)
Am I missing something?
Put city and state in one or other app, or even in their own citystate app, and import them from the place they are defined. In an app called foo:
from citystate.models import city, state
In passing, Django models are classes, and as such one would normally start them with a capital letter: City and State. Honoring conventions like this matter: you may not be confused (yet) but you will confuse the heck out of anybody else reading this code, who will think that these things being imported are functions not classes!
An app is not required to have any views, urls, etc. It can be just a place to put common models and their migrations, and maybe some admin classes.

Django M2M Through extra fields with multiple models

I'm trying to figure out the best way to set up the following django model (genericised for security reasons).
ThingA:
User(M2M through "UserRelation")
ThingB:
User(M2M through "UserRelation")
ThingC:
User(M2M through "UserRelation")
User:
Login_name
UserRelation:
User (foreginkey)
Thing (foreignkey) #is this generic to any of the above "things"
Privilege
I understand using "through" between two distinct models, but I'm not sure how to apply this to multiple models. Would I define a foreignkey for each of the "Thing" models in my UserRelation Model?
It looks like you are trying to setup a generic many-to-many relationship. There is a dedicated django app that you can be use for this purpose: django-gm2m
Here is how to use it in your generic case:
from django.db import models
from django.contrib.contenttypes.fields import GenericForeignKey
from gm2m import GM2MField
class ThingA(models.Model):
pass
class ThingB(models.Model):
pass
class ThingC(models.Model):
pass
class User(models.Model):
login_name = models.CharField(max_length=255)
things = GM2MField(through='UserRelation')
class UserRelation(models.Model):
user = models.ForeignKey(User)
thing = GenericForeignKey(ct_field='thing_ct', fk_field='thing_fk')
thing_ct = models.ForeignKey(ContentType)
thing_fk = models.CharField(max_length=255)
privilege = models.CharField(max_length=1)
You can now access all the things for a given user and all the User instances for a given 'thing', as well as the privilege attribute for each UserRelation instance.
This will additionally provide you with a handful of benefits (reverse relations, prefetching, etc.) you may need. A GM2MField basically behaves exactly like a django ManyToManyField.
Disclaimer: I am the author of django-gm2m

from django.contrib.auth.models import User vs defining an user ForeignKey as owner = models.ForeignKey('auth.User')

How come to import User from the auth package that comes with Django, I need to do:
from django.contrib.auth.models import User
while to refer to the same User model to create a ForeignKey, I need to do:
owner = models.ForeignKey('auth.User', related_name='snippets')
and not 'auth.models.User'?
I am following the example here : http://www.django-rest-framework.org/tutorial/4-authentication-and-permissions
This is due to Django's "lazy relationships". You can see the code for this here. You don't need to specify the exact module, in this case models because anything inheriting from Django's models.Model will fire off a class_prepared signal once it's initialised and up to this point, it's still only a string.
Just provide the app and model, or just the model name if it's in the same app.

How to add custom permission to the User model in django?

in django by default when syncdb is run with django.contrib.auth installed, it creates default permissions on each model... like foo.can_change , foo.can_delete and foo.can_add. To add custom permissions to models one can add class Meta: under the model and define permissions there, as explained here https://docs.djangoproject.com/en/4.1/topics/auth/customizing/#custom-permissions
My question is that what should I do if I want to add a custom permission to the User model? like foo.can_view. I could do this with the following snippet,
ct = ContentType.objects.get(app_label='auth', model='user')
perm = Permission.objects.create(codename='can_view', name='Can View Users',
content_type=ct)
perm.save()
But I want something that plays nicely with syncdb, for example the class Meta under my custom models. Should I just have these in class Meta: under UserProfile since that is the way to extend the user model. but is that the RIGHT way to do it? Wouldn't that tie it to UserProfile model?
You could do something like this:
in the __init__.py of your Django app add:
from django.db.models.signals import post_syncdb
from django.contrib.contenttypes.models import ContentType
from django.contrib.auth import models as auth_models
from django.contrib.auth.models import Permission
# custom user related permissions
def add_user_permissions(sender, **kwargs):
ct = ContentType.objects.get(app_label='auth', model='user')
perm, created = Permission.objects.get_or_create(codename='can_view', name='Can View Users', content_type=ct)
post_syncdb.connect(add_user_permissions, sender=auth_models)
I don't think there is a "right" answer here, but i used the exact same code as you except i changed Permission.objects.create to Permission.objects.get_or_create and that worked find to sync with syncdb
An updated answer for Django 1.8. The signal pre_migrate is used instead of pre_syncdb, since syncdb is deprecated and the docs recommend using pre_migrate instead of post_migrate if the signal will alter the database. Also, #receiver is used to connect add_user_permissions to the signal.
from django.db.models.signals import pre_migrate
from django.contrib.contenttypes.models import ContentType
from django.contrib.auth import models as auth_models
from django.contrib.auth.models import Permission
from django.conf import settings
from django.dispatch import receiver
# custom user related permissions
#receiver(pre_migrate, sender=auth_models)
def add_user_permissions(sender, **kwargs):
content_type = ContentType.objects.get_for_model(settings.AUTH_USER_MODEL)
Permission.objects.get_or_create(codename='view_user', name='View user', content_type=content_type)
This is a bit hacky but mentioning it here anyway for reference.
My site has a generic model called Setting, which stores various settings concerning the site I want certain users to be able to edit, without needing to go through me the developer (like registration limit, or an address, or the cost of items, etc).
All the permissions that don't nicely map onto other models (eg "Send Password Reminder Email to Student", "Generate Payment Reconciliation Report", "Generate PDF Receipt"), which really just relate to pages that get viewed in the admin area, get dumped onto this Setting model.
For example, here's the model:
class Setting(models.Model):
name = models.CharField(max_length=50, unique=True)
slug = models.SlugField(editable=False)
description = models.TextField()
value = models.TextField()
class Meta:
#for permissions that don't really relate to a particular model, and I don't want to programmatically create them.
permissions = (
("password_reminder", "Send Password Reminder"),
("generate_payment_reconciliation_report", "Generate Payment Reconciliation Report"),
("generate_pdf_receipt", "Generate PDF Receipt"),
)
Do each of those settings strictly relate to the Setting model? No, which is why I said this is a bit hacky. But it is nice that I can now just dump all those permissions here, and Django's migration commands will take care of the rest.

Categories

Resources