Reputation: 4371
I followed this tutorial creating a custom User
.
in views.py
I created a method preseting the user information by userid (i.e. /users/42) but the result is AnonymousUser
. I should mention the db-record I'm trying to get is exist in my DB.
Here's my models.py
file:
from django import forms
from django.db import models
from django.contrib.auth.models import AbstractBaseUser, BaseUserManager
from django.contrib.auth.forms import UserCreationForm
class UserProfileManager(BaseUserManager):
def create_user(self, email, date_of_birth, password=None):
"""
Creates and saves a User with the given email, date of
birth and password.
"""
if not email:
raise ValueError('Users must have an email address')
user = self.model(
email=self.normalize_email(email),
date_of_birth=date_of_birth,
)
user.set_password(password)
user.save(using=self._db)
return user
def create_superuser(self, email, date_of_birth, password):
"""
Creates and saves a superuser with the given email, date of
birth and password.
"""
user = self.create_user(email,
password=password,
date_of_birth=date_of_birth
)
user.is_admin = True
user.save(using=self._db)
return user
class UserProfile(AbstractBaseUser):
email = models.EmailField(
verbose_name='email address',
max_length=255,
unique=True,
db_index=True,
)
date_of_birth = models.DateField()
is_active = models.BooleanField(default=True)
is_admin = models.BooleanField(default=False)
objects = UserProfileManager()
USERNAME_FIELD = 'email'
#REQUIRED_FIELDS = ['date_of_birth']
def get_full_name(self):
# The user is identified by their email address
return self.email
def get_short_name(self):
# The user is identified by their email address
return self.email
# On Python 3: def __str__(self):
def __unicode__(self):
return self.email
def has_perm(self, perm, obj=None):
"Does the user have a specific permission?"
# Simplest possible answer: Yes, always
return True
def has_module_perms(self, app_label):
"Does the user have permissions to view the app `app_label`?"
# Simplest possible answer: Yes, always
return True
@property
def is_staff(self):
"Is the user a member of staff?"
# Simplest possible answer: All admins are staff
return self.is_admin
class UserCreationForm(forms.ModelForm):
"""A form for creating new users. Includes all the required
fields, plus a repeated password."""
password1 = forms.CharField(label='Password', widget=forms.PasswordInput)
password2 = forms.CharField(label='Password confirmation', widget=forms.PasswordInput)
class Meta:
model = UserProfile
fields = ('email', 'date_of_birth')
def clean_password2(self):
# Check that the two password entries match
password1 = self.cleaned_data.get("password1")
password2 = self.cleaned_data.get("password2")
if password1 and password2 and password1 != password2:
raise forms.ValidationError("Passwords don't match")
return password2
def save(self, commit=True):
# Save the provided password in hashed format
user = super(UserCreationForm, self).save(commit=False)
user.set_password(self.cleaned_data["password1"])
if commit:
user.save()
return user
Here's the the method to present the User
:
def show_user(request, user_id):
try:
user = UserProfile.objects.get(id=user_id)
except UserProfile.DoesNotExist:
return None
template = loader.get_template('index.html')
context = RequestContext(request, {
'user': user,
})
return HttpResponse(template.render(context))
Upvotes: 2
Views: 2519
Reputation: 64923
django.contrib.auth.context_processors.auth
injects a user
variable into your context data, and variables injected by context processor can override those supplied into RequestContext.
When context processors are applied
When you use RequestContext, the variables you supply directly are added first, followed any variables supplied by context processors. This means that a context processor may overwrite a variable you’ve supplied, so take care to avoid variable names which overlap with those supplied by your context processors.
Source: https://docs.djangoproject.com/en/dev/ref/templates/api/
Upvotes: 1