django get data using multiple objects by referring to foreign keys - django

I have two data models, one is User and other one is ShibUser, ShibUser associate with User by storing User table's id as its Foreign Key.
Here is my ShibUser Table:
+----+--------------+------------------+----------------+
| id | auth_user_id | shib_username | shib_user_role |
+----+--------------+------------------+----------------+
| 1 | 4 | auser#domain.edu | Student |
| 2 | 5 | buser#domain.edu | Student |
+----+--------------+------------------+----------------+
from django.db import models
from askbot.deps.django_authopenid.models import User
class ShibUser(models.Model):
auth_user = models.ForeignKey(User)
shib_username = models.CharField(max_length = 200)
shib_user_role = models.CharField(max_length = 200)
Here is my User (auth_user) table:
+----+----------------+------------+--------+
| id | username | reputation | status |
+----+----------------+------------+--------+
| 4 | aaUser | 1 | w |
| 5 | MrBUser_Cool | 1 | w |
+----+----------------+------------+--------+
Model Definition for User:
class User(models.Model):
"""
Users within the Django authentication system are represented by this
model.
Username and password are required. Other fields are optional.
"""
username = models.CharField(_('username'), max_length=30, unique=True,
help_text=_('Required. 30 characters or fewer. Letters, numbers and '
'#/./+/-/_ characters'))
first_name = models.CharField(_('first name'), max_length=30, blank=True)
last_name = models.CharField(_('last name'), max_length=30, blank=True)
email = models.EmailField(_('e-mail address'), blank=True)
password = models.CharField(_('password'), max_length=128)
is_staff = models.BooleanField(_('staff status'), default=False,
help_text=_('Designates whether the user can log into this admin '
'site.'))
is_active = models.BooleanField(_('active'), default=True,
help_text=_('Designates whether this user should be treated as '
'active. Unselect this instead of deleting accounts.'))
is_superuser = models.BooleanField(_('superuser status'), default=False,
help_text=_('Designates that this user has all permissions without '
'explicitly assigning them.'))
last_login = models.DateTimeField(_('last login'), default=timezone.now)
date_joined = models.DateTimeField(_('date joined'), default=timezone.now)
groups = models.ManyToManyField(Group, verbose_name=_('groups'),
blank=True, help_text=_('The groups this user belongs to. A user will '
'get all permissions granted to each of '
'his/her group.'))
user_permissions = models.ManyToManyField(Permission,
verbose_name=_('user permissions'), blank=True,
help_text='Specific permissions for this user.')
objects = UserManager()
class Meta:
verbose_name = _('user')
verbose_name_plural = _('users')
def __unicode__(self):
return self.username
def natural_key(self):
return (self.username,)
def get_absolute_url(self):
return "/users/%s/" % urllib.quote(smart_str(self.username))
def is_anonymous(self):
"""
Always returns False. This is a way of comparing User objects to
anonymous users.
"""
return False
def is_authenticated(self):
"""
Always return True. This is a way to tell if the user has been
authenticated in templates.
"""
return True
def get_full_name(self):
"""
Returns the first_name plus the last_name, with a space in between.
"""
full_name = u'%s %s' % (self.first_name, self.last_name)
return full_name.strip()
def set_password(self, raw_password):
self.password = make_password(raw_password)
def check_password(self, raw_password):
"""
Returns a boolean of whether the raw_password was correct. Handles
hashing formats behind the scenes.
"""
def setter(raw_password):
self.set_password(raw_password)
self.save()
return check_password(raw_password, self.password, setter)
def set_unusable_password(self):
# Sets a value that will never be a valid hash
self.password = make_password(None)
def has_usable_password(self):
return is_password_usable(self.password)
def get_group_permissions(self, obj=None):
"""
Returns a list of permission strings that this user has through his/her
groups. This method queries all available auth backends. If an object
is passed in, only permissions matching this object are returned.
"""
permissions = set()
for backend in auth.get_backends():
if hasattr(backend, "get_group_permissions"):
if obj is not None:
permissions.update(backend.get_group_permissions(self,
obj))
else:
permissions.update(backend.get_group_permissions(self))
return permissions
def get_all_permissions(self, obj=None):
return _user_get_all_permissions(self, obj)
def has_perm(self, perm, obj=None):
"""
Returns True if the user has the specified permission. This method
queries all available auth backends, but returns immediately if any
backend returns True. Thus, a user who has permission from a single
auth backend is assumed to have permission in general. If an object is
provided, permissions for this specific object are checked.
"""
# Active superusers have all permissions.
if self.is_active and self.is_superuser:
return True
# Otherwise we need to check the backends.
return _user_has_perm(self, perm, obj)
def has_perms(self, perm_list, obj=None):
"""
Returns True if the user has each of the specified permissions. If
object is passed, it checks if the user has all required perms for this
object.
"""
for perm in perm_list:
if not self.has_perm(perm, obj):
return False
return True
def has_module_perms(self, app_label):
"""
Returns True if the user has any permissions in the given app label.
Uses pretty much the same logic as has_perm, above.
"""
# Active superusers have all permissions.
if self.is_active and self.is_superuser:
return True
return _user_has_module_perms(self, app_label)
def email_user(self, subject, message, from_email=None):
"""
Sends an email to this User.
"""
send_mail(subject, message, from_email, [self.email])
def get_profile(self):
"""
Returns site-specific profile for this user. Raises
SiteProfileNotAvailable if this site does not allow profiles.
"""
if not hasattr(self, '_profile_cache'):
from django.conf import settings
if not getattr(settings, 'AUTH_PROFILE_MODULE', False):
raise SiteProfileNotAvailable(
'You need to set AUTH_PROFILE_MODULE in your project '
'settings')
try:
app_label, model_name = settings.AUTH_PROFILE_MODULE.split('.')
except ValueError:
raise SiteProfileNotAvailable(
'app_label and model_name should be separated by a dot in '
'the AUTH_PROFILE_MODULE setting')
try:
model = models.get_model(app_label, model_name)
if model is None:
raise SiteProfileNotAvailable(
'Unable to load the profile model, check '
'AUTH_PROFILE_MODULE in your project settings')
self._profile_cache = model._default_manager.using(
self._state.db).get(user__id__exact=self.id)
self._profile_cache.user = self
except (ImportError, ImproperlyConfigured):
raise SiteProfileNotAvailable
return self._profile_cache
I have a form which represent the user profile and I want to show the role of the user, I have import both the objects in my form but I am struggling on how to really get the user role based on User objects username.
Here is the exact place I am trying to add this:
from askbot.shibapp.models import ShibUser
from django.contrib.auth.models import User
def __init__(self, user, *args, **kwargs):
super(EditUserForm, self).__init__(*args, **kwargs)
logging.debug('initializing the form')
shib_user_role = ShibUser.objects.get(auth_user=4)
if askbot_settings.EDITABLE_SCREEN_NAME:
self.fields['username'] = UserNameField(label=_('Screen name'))
self.fields['username'].initial = user.username
self.fields['username'].user_instance = user
self.fields['email'].initial = user.email
self.fields['realname'].initial = user.real_name
self.fields['website'].initial = user.website
self.fields['city'].initial = user.location
if askbot_settings.EDITABLE_SCREEN_NAME:
self.fields['role'].initial = "test_role" (Instead of 'test_role')
I am very new to django world.

Ok so I think you're trying to go from auth.User.username to ShibUser to do this follow the ForeignKeys backwards:
user = User.objects.get(username=username)
# for reverse relationships the foo_set is created by django enabling
# reverse relationship. You can override this by providing a related_name
shibuser = user.shibuser_set.get()
# Alternative syntax
shibuser = user.shibuser_set.all()[0]
From there you can get your ShibUser role. If More than one ShibUser can exist per User then you want to drop the index and will instead have a queryset of ShibUser objects to work with.
If only one ShibUser object can exist per User you should make this a OneToOneField instead of a foreignkey and things become simpler:
shibuser = user.shibuser
Finally you can even start from the ShibUser model and work with it:
shibuser = ShibUser.objects.get(auth_user__username=username)
# Or if you already had the User object instance
shibuser = ShibUser.objects.get(auth_user=user)
Keep in mind several exceptions can be raised around this depending on the approach: the User could not exist or the ShibUser for the given User could not exist. Perhaps more than one ShibUser could be related to a single user and therefore the .get() calls will result in a MultipleObjectsReturned exception. Your schema isn't very tight to your use case it sounds like so I would probably improve that with a OneToOneField

Related

Password error when customizing Django authentication

I'm trying to customize the authentication that comes by default in Django with a table of Mysql already made (collaborators).
When I want to register a user (with the command python manage.py createsuperuser) I get the following error:
django.db.utils.OperationalError: (1054, "Unknown column 'collaborators.password' in 'field list'").
That error mentions that the password column does not exist, and indeed I do not have it in the table, is there any way to indicate that the password is obtained from a column called contrasena_general?
I attach my code.
models.py
class MyUserManager(BaseUserManager):
use_in_migrations = True
def create_superuser(self, no_colaborador, nombres_colaborador, apellido_paterno_colaborador, apellido_materno_colaborador,
id_plantel, id_area_colaborador, no_empleado_sup, contrasena_general, empleado_interno):
user = self.model(no_colaborador = no_colaborador, nombres_colaborador = nombres_colaborador,
apellido_paterno_colaborador = apellido_paterno_colaborador, apellido_materno_colaborador = apellido_materno_colaborador,
id_plantel = id_plantel, id_area_colaborador = id_area_colaborador, no_empleado_sup = no_empleado_sup,
contrasena_general = contrasena_general, empleado_interno = empleado_interno,)
user.set_password(contrasena_general)
user.save(using=self._db)
return user
class Colaboradores(AbstractBaseUser):
no_colaborador = models.IntegerField(primary_key=True)
nombres_colaborador = models.CharField(max_length=150)
apellido_paterno_colaborador = models.CharField(max_length=150)
apellido_materno_colaborador = models.CharField(max_length=150)
id_plantel = models.IntegerField()
id_area_colaborador = models.IntegerField()
id_centro_costos = models.IntegerField()
no_empleado_sup = models.IntegerField()
contrasena_general = models.CharField(max_length=100)
empleado_interno = models.CharField(max_length=10)
objects = MyUserManager()
USERNAME_FIELD = "no_colaborador"
class Meta:
managed = False
db_table = 'collaborators'
app_label = "journal"
def __str__ (self):
return self.email
def def_full_name (self):
return self.nombres_colaborador
def has_perm(self, perm, obj=None):
return self.no_colaborador
def has_module_perms(self, app_label):
return self.no_colaborador
# backends.py
class MyAuthBackend(object):
def authenticate(self, no_colaborador, contrasena_general):
try:
user = Colaboradores.objects.get(no_colaborador=no_colaborador)
if user.check_password(contrasena_general):
return user
else:
return None
except Colaboradores.DoesNotExist:
logging.getLogger("error_logger").error("user with login %s does not exists " % login)
return None
except Exception as e:
logging.getLogger("error_logger").error(repr(e))
return None
def get_user(self, no_colaborador):
try:
user = Colaboradores.objects.get(no_colaborador=no_colaborador)
if user.is_active:
return user
return None
except Colaboradores.DoesNotExist:
logging.getLogger("error_logger").error("user with %(no_colaborador)d not found")
return None
# setting.py
...
AUTH_USER_MODEL = 'journal.Colaboradores'
AUTHENTICATION_BACKENDS = ('clientes.backends.MyAuthBackend', 'django.contrib.auth.backends.ModelBackend',)
How could you indicate that the password is obtained from a column in the table that is not called a password?
I think creating your own createsuperuser command would solve this issue.
Ref: Is it possible to make my own createsuperuser command in django?
You can make your based on the the original source code for Django's createsuperuser that can be found on Github.
As you can see from there, there is a constant on line 20 that says:
PASSWORD_FIELD = 'password'
So I guess that since you changed it in the model to contrasena_general, you need to make your own custom command.

Django: authenticate() returns none except one case

So i am stuck at a point in my project. I am trying to create users and I have extended User model using the OneToOnefield method as recommended in Documentation to create a user profile. There is no problem in creation of the user as all the details are correctly stored in both the auth_user and appname_userprofile table.
The problem I get is when I try to login with any user stored in the auth_user table. Except one case( which i created before creating the userProfile model). So in my auth_user Table the pass for this one case is encoded but for the remaining cases it's plain text.
Here is my function handling the view -
def login_view(request):
if request.method == 'POST':
print(request.body)
username = request.POST.get('id_username')
password = request.POST.get('id_password')
print(username, password)
try:
import pdb; pdb.set_trace()
user = authenticate(username=username, password=password)
print('This is ',user)
if user is not None:
login(request,user)
else:
return redirect('fileupload')
print('This is ',user).... some more code
Now when i pass the credentials for this one case and try to authenticate. the login works(except my code gets stuck at some later point because this user doesn't have any profile).
When i pass the credentials for user created after creating the UserProfile model. The
authenticate(username=username, password=password)
function returns
None
I have included this in my settings.py -
AUTHENTICATION_BACKENDS = (
'django.contrib.auth.backends.ModelBackend',
)
This is my model -
from django.db import models
from django.contrib.auth.models import User
from django.db.models.signals import post_save
from django.dispatch import receiver
class UserProfile(models.Model):
user = models.OneToOneField(User, on_delete=models.CASCADE, null=True)
contact_no = models.CharField(max_length=10, null=True)
# email = models.EmailField()
department = models.CharField(max_length=25, null=True)
status = models.IntegerField(null=True)
industry_segment = models.CharField(max_length=50, null=True)
created_at = models.DateTimeField(auto_now_add=True)
created_by = models.IntegerField(null=True)
updated_at = models.DateTimeField(auto_now=True)
updated_by = models.IntegerField(null=True)
#receiver(post_save, sender=User)
def create_user_profile(sender, instance, created, **kwargs):
if created:
UserProfile.objects.create(user=instance)
#receiver(post_save, sender=User)
def save_user_profile(sender, instance, **kwargs):
instance.userprofile.save()
This is how i am saving the users -
def user_view(request):
print(request.user)
if request.is_ajax():
print(request.user)
data = json.load(request)
u_name = data['txtfirstName'] + " " + data['txtlastName']
user=User(username=u_name,password='test123',email=data['txtemailId'])
user.save()
# userprofile= UserProfile.objects.create(user=request.user)
user.userprofile.contact_no = data['txtcontactNo']
# user.userprofile.email = data['txtemailId']
user.userprofile.department = data['txtdeptvalue']
user.userprofile.status = data['txtstatusvalue']
user.userprofile.industry_segment = 'Software'
user.userprofile.created_at = datetime.datetime.now()
user.userprofile.created_by = request.user.id
user.userprofile.updated_at = datetime.datetime.now()
user.userprofile.updated_by = request.user.id
user.save()
ignore the formatting of this code... but it is working
So can anyone help me with the authentication problem ?
You must not create users like that. The password will not be hashed, so will never match in authenticate. You must always use the create_user manager method.
user = User.objects.create_user(username=u_name, password='test123', email=data['txtemailId'])

django register user as superuser

I am using a OneToOne relationship to create a custom user like this:
class Patient(models.Model):
user = models.OneToOneField(Django_User, on_delete=models.CASCADE)
models.PositiveSmallIntegerField(choices=USER_TYPE_CHOICES)
birthday=models.DateField(auto_now=False, null=True, blank=True)
USERNAME_FIELD='username'
def __str__(self):
return self.user.username
def save(self, *args, **kwargs):
super(Patient, self).save(*args, **kwargs)
def set_birthday(self, birthday):
birthday = self.birthday
Now there have been some additions to my task and i need to give every user is_staff or is_superuser permissions.
I created a form:
class UserPermissionForm(forms.Form):
permission = [(1, 'Patient'),
(2, 'Lieferant'),
(3, 'Andere'),
(4, 'Mitarbeiter'),
(5, 'Admin')]
Zugriffsrechte = forms.ChoiceField(choices= permission, widget=forms.Select())
And tried setting the permissions in my view - genericform is just the usual django user creation form, form is the form where the birthday is set and permission is the form seen above:
def register_user_view(request):
title="Register User"
genericform = GenericCreationForm(request.POST or None)
form=UserRegisterForm(request.POST or None)
permission = UserPermissionForm(request.POST or None)
if form.is_valid() * genericform.is_valid() * permission.is_valid():
genericform.save()
username = genericform.cleaned_data.get('username')
raw_password = genericform.cleaned_data.get('password1')
user_type = int(request.POST.get('Zugriffsrechte'))
new_user = authenticate(username=username, password=raw_password)
profile = form.save(commit=False)
profile.user = new_user
profile.save()
is_superuser = False
is_staff = False
if user_type > 3:
is_staff = True
print('YOU SHALL BE STAFF')
if user_type > 4:
is_superuser = True
print('YOU SHALL BE ADMIN')
profile.user.is_staff = is_staff
profile.user.is_superuser = is_superuser
login(request,profile.user)
return redirect("/register/done")
context={
"form":form,
"genericform":genericform,
"permissionform": permission,
"title":title,
}
return render(request,"profile_form.html",context)
My first question is if and how i could set is_staff or is_superuser. The code above causes no errors but the created user is still just a regular user.
Also i know this can be simplyfied (i am working with other people so at some point everything got a bit unstructured) so question 2 is: what is the best approach to make this code better? A custom user with a custom user manager? Or is the OneToOne Field still a good option?
Seems like you are missing on the saving part. Add profile.save() after you are changing it. Something like this.
profile.user.is_staff = is_staff
profile.user.is_superuser = is_superuser
profile.save()

python-social not saving response to custom model

Ive been running into a number of problem in relation to using django's custom model. This one in particular is not raising any errors. For some reason after authenticating via steam and returning to the landing page the database tables for both steamuser_user (custom user) and social_auth_usersocialauth are empty. Nothing is being saved, no errors are being displayed etc.
My custom model which is quite similar to the one on django docs official page is as follows:
from django.db import models
from django.contrib.auth.models import AbstractBaseUser
from django.contrib.auth.models import BaseUserManager
# Create your models here.
class UserManager(BaseUserManager):
def create_user(self, steamid, username, password=None):
if not steamid:
msg = 'User has no Steam ID set'
raise ValueError(msg)
if not username:
msg = 'User has no name set'
raise ValueError(msg)
user = self.model(steamid=steamid,
username=username)
user.set_password(password)
user.save(using=self._db)
return user
def create_superuser(self, steamid, username, password):
super_user = self.create_user(steamid=steamid,
username=username,
password=password)
super_user.is_staff = True
super_user.is_admin = True
super_user.is_mod = True
super_user.save(using=self._db)
return super_user
class User(AbstractBaseUser):
steamid = models.CharField(max_length=20, unique=True)
username = models.CharField(max_length=80)
email = models.EmailField(null=True,blank=True)
is_active = models.BooleanField(default=True)
is_staff = models.BooleanField(default=False)
is_admin = models.BooleanField(default=False)
is_mod = models.BooleanField(default=False)
date_joined = models.DateTimeField(auto_now_add=True)
reputation = models.IntegerField(max_length=6, default=0)
USERNAME_FIELD = 'steamid'
objects = UserManager()
def __unicode__(self):
return self.username
def get_full_name(self):
return self.steamid
def get_short_name(self):
return self.username
The settings I've used are as follows:
SOCIAL_AUTH_USER_MODEL = 'steamuser.User'
AUTH_USER_MODEL = 'steamuser.User'
TEMPLATE_CONTEXT_PROCESSORS = global_settings.TEMPLATE_CONTEXT_PROCESSORS + (
'social.apps.django_app.context_processors.backends',
'social.apps.django_app.context_processors.login_redirect',
)
AUTHENTICATION_BACKENDS = (
'social.backends.steam.SteamOpenId',
'django.contrib.auth.backends.ModelBackend',
)
#Steam OpenAuth
SOCIAL_AUTH_STEAM_API_KEY = 'B1D7C629D093D4B72577F2F11DE4EBE2'
LOGIN_URL = '/'
SOCIAL_AUTH_LOGIN_REDIRECT_URL = '/'
SOCIAL_AUTH_ENABLED_BACKENDS = (
'steam',
)
Any help would be appreciated!
EDIT
Backends steam.py
def get_user_details(self, response):
player = self.get_json(USER_INFO, params={
'key': self.setting('API_KEY'),
'steamids': self._user_id(response)
})
if len(player['response']['players']) > 0:
player = player['response']['players'][0]
details = {'steamid': player.get('steamid'),
'username': player.get('personaname'),
}
else:
details = {}
return details
EDIT 2
Well despite my logical reasoning, I just gave up and created a custom pipeline to create the new steam user as follows:
from django.contrib.auth import get_user_model
def create_steamuser(details, user=None, *args, **kwargs):
if user:
return {'is_new': False}
if not details:
return
try:
steam_user = get_user_model().objects.get(steamid=details['steamid'])
except steam_user.DoesNotExist:
get_user_model().objects.create_user(details['steamid'], details['username'])
return {
'is_new': True,
}
Now I still have the problem where social_user is not being created. I've set the social user model to use my new custom model but there must be something that I am missing.
python-social-auth won't be able to pass the steamid and date_joined parameters to your custom create_user() method in the manager. To make that possible you have three options:
Set =None to those parameters and set some default vaules for them
Override the default create_user pipeline and pass the extra parameters.
Add a custom pipeline function before create_user and fill details with steamid and date_joined, then define SOCIAL_AUTH_STEAM_USER_FIELDS = ('username', 'email', 'steamid', 'date_joined').

Django authentication - modifying existing user on signup

I am building a photo sharing site with django where users are allowed to create groups to share photos. I have problems creating a proper user data model/logic which would cover all my requirements.
The basic requirements are:
User A is allowed to create a group where he can add another users (User B)
If the user B which has to be added to the group already exists then we will use this existing user B to be added to manytomany field of the group model representing the group
If the user B doesn't exist we will create a sort of "dummy" user. Setting the user_active to false. This is because the user B doesn't have set any sort of verification or password yet.
Now if the new added user B wants to be registered to the site, instead of creating a new user I would like to change the already existing user with the provided data from the signup form.
I would like to mention that I plan to use also the django-allauth for the social accounts users.
My question (considering the Django 1.5) is what would be the preferred way how to make this working:
Is this is something I should create my own User Manager or should I look into authentication backends ? I am really lost at this point.
Below is the diagram which represent both of the scenarios, signing up and adding of the user to the group:
http://i821.photobucket.com/albums/zz136/jorge_sanchez4/f79934d4-d0a4-4862-ab8b-7e1d09cd5642_zps06ec08f3.jpg
UPDATE:
So I tried following, created the custom user model where in the __new__ method I am returning the relevant object if it already exists and the is_active is set to False. Below is the both UserManager and user model:
class GruppuUserManager(BaseUserManager):
def create_user(self, username, email=None, password=None, phonenumber=None, **extra_fields):
now = timezone.now()
if not username:
raise ValueError('The given username must be set')
if not phonenumber:
raise ValueError('The given phonenumber must be set')
''' now lookup the user if it exists and is_active is set
then it is duplicate, otherwise return the user
and set the is_active to true '''
email = self.normalize_email(email)
if GruppUser.objects.filter(phonenumber__exact=phonenumber).exists():
if GruppUser.objects.filter(phonenumber__exact=phonenumber).values('is_active'):
''' duplicate - raise error '''
raise ValueError('The user is duplicate ')
else:
''' get the subscriber and set all the values '''
user = GruppUser.objects.filter(phonenumber__exact=phonenumber)
user.set_password(password)
user.is_active=True
if email:
user.email = email
user.save(using=self._db)
return user
user = self.model(username=username, email=email,
is_staff=False, is_active=True, is_superuser=False,
last_login=now, date_joined=now, phonenumber=phonenumber, **extra_fields)
user.set_password(password)
user.save(using=self._db)
return user
def create_superuser(self, username, email=None, password=None, phonenumber=None, **extra_fields):
u = self.create_user(username, email, password, phonenumber, **extra_fields)
u.is_staff = True
u.is_active = True
u.is_superuser = True
u.save(using=self._db)
return u
class GruppUser(AbstractBaseUser, PermissionsMixin):
''' django 1.5 - creating custom user model '''
id = models.AutoField(primary_key=True)
username = models.CharField(_('username'), max_length=30, unique=True,
help_text=_('Required. 30 characters or fewer. Letters, numbers and '
'#/./+/-/_ characters'),
validators=[
validators.RegexValidator(re.compile('^[\w.#+-]+$'), _('Enter a valid username.'), 'invalid')
])
first_name = models.CharField(_('first name'), max_length=30, blank=True)
last_name = models.CharField(_('last name'), max_length=30, blank=True)
email = models.EmailField(_('email address'), blank=True)
is_staff = models.BooleanField(_('staff status'), default=False,
help_text=_('Designates whether the user can log into this admin '
'site.'))
is_active = models.BooleanField(_('active'), default=True,
help_text=_('Designates whether this user should be treated as '
'active. Unselect this instead of deleting accounts.'))
date_joined = models.DateTimeField(_('date joined'), default=timezone.now)
phonenumber = models.CharField(max_length=10)
#following = models.ManyToManyField(Stream,blank=True,null=True)
blocked_con = models.ManyToManyField(Blocked_Content,blank=True,null=True)
mmsemail = models.EmailField(_('email address'), blank=True)
smsemail = models.EmailField(_('email address'), blank=True)
verified = models.BooleanField(_('verified'), default=False,
help_text=_('Defines if the user has been verified'))
objects = GruppuUserManager()
USERNAME_FIELD = 'username'
REQUIRED_FIELDS = ['phonenumber']
class Meta:
verbose_name = _('user')
verbose_name_plural = _('users')
def __init__(self,phone=None,*args, **kwargs):
''' save the phone number '''
super(GruppUser,self).__init__(*args, **kwargs)
self.phonetocheck = phone
#staticmethod
def __new__(cls,phone=None,*args, **kwargs):
''' lookup for the same user '''
if GruppUser.objects.filter(phonenumber__exact=phone).exists():
if self.objects.filter(phonenumber__exact=phone).values('is_active'):
''' duplicate - raise error '''
raise ValueError('The user is duplicate')
else:
''' get the subscriber and set all the values '''
user = self.objects.filter(phonenumber__exact=phone)
user.is_active = True
return user
return super(GruppUser,cls).__new__(cls,*args, **kwargs)
def get_full_name(self):
"""
Returns the first_name plus the last_name, with a space in between.
"""
full_name = '%s %s' % (self.first_name, self.last_name)
return full_name.strip()
def get_short_name(self):
"Returns the short name for the user."
return self.first_name
def email_user(self, subject, message, from_email=None):
"""
Sends an email to this User.
"""
send_mail(subject, message, from_email, [self.email])
Anyway the strange issue I am having right now is that I can't connect to the admin site which is giving me following error:
I have traced the django and it seems that the query set is somehow shifted to the left:
(Pdb) context[self.user].phonenumber
u''
(Pdb) context[self.user].date_joined
u'9135261969'
(Pdb) context[self.user].is_active
datetime.datetime(2013, 9, 8, 20, 47, 30, tzinfo=<UTC>)
But the data in mysql is correct:
mysql> select is_active from demo_app_gruppuser;
+-----------+
| is_active |
+-----------+
| 1 |
+-----------+
1 row in set (0.00 sec)
mysql> select phonenumber from demo_app_gruppuser;
+-------------+
| phonenumber |
+-------------+
| 9135261969 |
+-------------+
1 row in set (0.00 sec)
mysql> select date_joined from demo_app_gruppuser;
+---------------------+
| date_joined |
+---------------------+
| 2013-09-08 20:47:30 |
+---------------------+
1 row in set (0.00 sec)
Here is the backtrace when trying to login to the admin:
20. context[self.varname] = LogEntry.objects.filter(user__id__exact=user_id).select_related('content_type', 'user')[:int(self.limit)]
File "/usr/site/gruppe/lib/python2.7/site-packages/django/db/models/manager.py" in filter
155. return self.get_query_set().filter(*args, **kwargs)
File "/usr/site/gruppe/lib/python2.7/site-packages/django/db/models/query.py" in filter
667. return self._filter_or_exclude(False, *args, **kwargs)
File "/usr/site/gruppe/lib/python2.7/site-packages/django/db/models/query.py" in _filter_or_exclude
685. clone.query.add_q(Q(*args, **kwargs))
File "/usr/site/gruppe/lib/python2.7/site-packages/django/db/models/sql/query.py" in add_q
1259. can_reuse=used_aliases, force_having=force_having)
File "/usr/site/gruppe/lib/python2.7/site-packages/django/db/models/sql/query.py" in add_filter
1190. connector)
File "/usr/site/gruppe/lib/python2.7/site-packages/django/db/models/sql/where.py" in add
71. value = obj.prepare(lookup_type, value)
File "/usr/site/gruppe/lib/python2.7/site-packages/django/db/models/sql/where.py" in prepare
339. return self.field.get_prep_lookup(lookup_type, value)
File "/usr/site/gruppe/lib/python2.7/site-packages/django/db/models/fields/__init__.py" in get_prep_lookup
322. return self.get_prep_value(value)
File "/usr/site/gruppe/lib/python2.7/site-packages/django/db/models/fields/__init__.py" in get_prep_value
555. return int(value)
Exception Type: ValueError at /admin/
Exception Value: invalid literal for int() with base 10: 'root'
Also in pdb is interesting that self.user.id which should be in this case 1 is returning "root" back. Seems that somehow django messed up what my pk are in this model even when I specified it in the model :
id = models.AutoField(primary_key=True)
Turns out that using __new__ method on Django model is not good idea, using the Model Manager create_user is working ok.