I want to put the email of user in my model Article.
from django.db import models
from django import forms
from django.contrib.auth.models import User
class Article(models.Model):
#auteur
email = models.ForeignKey(User.email, unique=True)
name = models.CharField(max_length=200)
#titre
title = models.CharField(max_length=200)
title_en = models.CharField(max_length=200)
subtitle = models.CharField(max_length=200)
subtitle_en = models.CharField(max_length=200)
1 Answer 1
What you have written has no sense. You have to keep a ForeignKey on the user, and then access to his email through user.email:
class Article(models.Model):
#auteur
user = models.ForeignKey(User, unique=True)
#titre
title = models.CharField(max_length=200)
title_en = models.CharField(max_length=200)
subtitle = models.CharField(max_length=200)
subtitle_en = models.CharField(max_length=200)
Then, Article.user.username (or self.user.username inside an Article method) gives you the name and Article.user.email the e-mail.
Some explanations
In Django, you can create ForeignKey only on Model object, and not object field. This will be translate in SQL as a classic reference between tables. (If you check your Article SQL database, you'll see a user_id field. This field will contains the ID of the user, extract from the auth_user table, which created the Article.