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:
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
The solution to these issues was found by digging around in the SQLite DB, as suggested here.
The manage.py sqlall
command showed the below, where the model's hidden id
field that Django automatically creates is specified as a PRIMARY KEY
.
BEGIN;
CREATE TABLE "profiles_specialist" (
"id" integer NOT NULL PRIMARY KEY,
"user_id" integer NOT NULL REFERENCES "auth2_customuser" ("id"),
The hidden id
field had lost its PK status somehow, and was set only as an INTEGER
that was failing to auto increment itself each time a new object was saved.
This field needed to be reset to INTEGER PRIMARY KEY
, and everything then worked perfectly.