3

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)
Craig Trader
15.7k6 gold badges41 silver badges56 bronze badges
asked Aug 23, 2010 at 17:29
2
  • 5
    There is no 'ForeignField' in Django - it's ForeignKey. Commented Aug 23, 2010 at 17:36
  • The Contact model doesn't need the author field. The author is accessible from the email field of the Contact model. Other than that, this seems reasonable to me. Commented Sep 2, 2010 at 9:27

2 Answers 2

1

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()
answered Aug 28, 2010 at 11:45
Sign up to request clarification or add additional context in comments.

Comments

0

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().

answered Aug 23, 2010 at 17:43

1 Comment

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.

Your Answer

Draft saved
Draft discarded

Sign up or log in

Sign up using Google
Sign up using Email and Password

Post as a guest

Required, but never shown

Post as a guest

Required, but never shown

By clicking "Post Your Answer", you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.