Taking first steps into django's (1.5)
auth features and had a lot of trouble so far just attempting so pull in the user's email address (which is the username field in the user model) as a ForeignKey
in a profile model Specialist
.
Two questions:
- Is this the best practice way of foreign keying to the current users details in a profile model? Note, I'm not trying to save a new user, just associate their profile details back the their authenticated user object (CustomUser). By the time the user reaches the below view, they are already authenticated.
- What changes are required to the below to get this to work as it should ?
Note, before getting this far, I hit several user_id
cannot be null or must be in instance of a CustomUser object errors, I'm now seeing nothing is being saved in the database once I have been redirected to /profile/
.
# view
@login_required
def profile_setup_specialist(request):
if request.method == 'POST':
current_user = CustomUser.objects.get(email = request.user.email)
posted_form = SpecialistCreationForm(request.POST, instance=current_user)
if posted_form.is_valid():
profile = posted_form.save(commit=False)
profile.user = current_user
profile.save()
return HttpResponseRedirect('/profile/')
# ..
# profile model
class Specialist(models.Model):
user = models.ForeignKey(CustomUser, related_name='Specialist')
foo = models.CharField(max_length=100)
# ...
def __unicode__(self):
return self.foo
# form
class SpecialistCreationForm(forms.ModelForm):
class Meta:
model = Specialist
exclude = ['user']
# custom user model
class CustomUser(AbstractBaseUser, PermissionsMixin):
email = models.EmailField(
verbose_name='email address',
max_length=255,
unique=True,
db_index=True,
)
# ..
objects = CustomUserManager()
USERNAME_FIELD = 'email'
REQUIRED_FIELDS = ['first_name', 'last_name', 'state']
def __unicode__(self):
return self.email