views:

91

answers:

2

I needed some help in model design. I wanted a model where a user can associate himself with numerous emails by submitting them from a form. And when the user wants to use the websites contact form, he can choose the email he wants a reply on. Will it be something like this :

class Email(models.Model):
    author = models.ForeignKey(User)
    email = models.EmailField()

class Contact(models.Model)
    author = models.ForeignKey(User)
    email = models.ForeignKey(Email)
A: 

You want to add a user profile to your users.

from django.contrib import auth

class UserProfile(models.Model):
    """A user profile."""
    user = models.OneToOneField(auth.models.User)
    # ... put more fields here


def user_post_save(sender, instance, **kwargs):
    """Make sure that every new user gets a profile."""
    profile, new = UserProfile.objects.get_or_create(user=instance)

models.signals.post_save.connect(user_post_save, sender=auth.models.User)

then you can access it with request.user.get_profile().

Radomir Dopieralski
wouldnt my way be simpler?
Ali
Well, with this you are taking advantage of things Django has built-in for this purpose. You are probably going to add more things to your user's profile anyways.
Radomir Dopieralski
+1  A: 

Your example means each Contact can have a single email address, and each email address can belong to multiple contacts. This is the wrong way round, i.e. you should put the ForeignKey on the Email model.

This should let you store multiple email addresses for each user.

class Email(models.Model):
    email = models.EmailField()
    user = models.ForeignKey(User)

u = User.objects.get(pk=1)
u.email_set.all()
Michaelnt