Domanda

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:

  1. 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.
  2. 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
È stato utile?

Soluzione 2

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.

Altri suggerimenti

I know writing custom user models are not fun, which involves writing/extending a lot of custom forms, such as this question. If I were to stick to the normal user model, I would say the Specialist model to have OneToOne relationship with user,

class Specialist(models.Model):

user = models.OneToOneField(User)

so you can query the profile like this request.user.specialist

Autorizzato sotto: CC-BY-SA insieme a attribuzione
Non affiliato a StackOverflow
scroll top