0

I'm trying to create and manage a custom user in django. I saw there are two possibilities, and i've chosen to extend (not create a new auth).

Models

models.py

class Artists(models.Model):
    user = models.OneToOneField(User)
    artist_image = models.ImageField(null=True, blank=True, upload_to="/artist_image/")

    def __str__(self):
        return 'Profil de {0}'.format(self.username)

    def get_absolute_url(self):
        return reverse('artist-details', kwargs={'pk': self.pk})

As i read in doc, I just make a OneToOne field with the User class of django auth models, so I can access method and properties, such as username, email, on my own user (here Artists).

form.py

class CreateArtistForm(UserCreationForm):
    class Meta:
        model = User
        fields = ('username', 'email')

    def save(self, commit=True):
        user = super(CreateArtistForm, self).save(commit=False)
        user.email = self.cleaned_data['email']
        if commit:
            user.save()
        return user

Here I extend UserCreationForm to prepare a form a little different (I want to have email field on my register form).

But here is my question : I first tried with

class Meta:
    model = Artists
    fields = ('user.username', 'user.email')

But I the error fields unknown in model Artist. So I tried just with username and email and same error.

So I changed the model = Artists to User, and it works fine.

But now how i register my Artist Object when the user is saved?

Do I have to make something like (in save()):

artist = Artists()
artist.user = user
artist.save()

Or override create_user()? I'm quite lost here and i'm looking docs and questions not able to find something because most of example people define their own auth.

Thanks in advance

Besta

edit : i'm using django 1.8.2 and python 3.4

Community
  • 1
  • 1
Bestasttung
  • 2,388
  • 4
  • 22
  • 34
  • yes this could be a simple approach, if you don't want to complicate things for yourself. – Ajay Gupta Jul 09 '15 at 14:16
  • And how i can access users fields in my form if i want to directly set model to Artist and not user? I suppose if i do that i wouldn't have to do that trick cause an Artist will be saved (and user too). @AjayGupta – Bestasttung Jul 09 '15 at 14:20
  • Why didn't you just subclass `User`? – dursk Jul 09 '15 at 14:34
  • What do you mean @mattm? – Bestasttung Jul 09 '15 at 14:51
  • http://stackoverflow.com/questions/5452288/django-why-create-a-onetoone-to-userprofile-instead-of-subclassing-auth-user @mattm – Bestasttung Jul 09 '15 at 15:04
  • I think your approach for Overriding the UserCreationForm and change it's save method is correct one I think, its more cleaner. @Bestasttung – ruddra Jul 14 '15 at 04:45

0 Answers0