How to use the Django User part in a model?

2

I'm doing a blog and the question has arisen, how can I use the Django user system to make a ForeignKey in my author variable?

from django.db import models


class Category(DatastampMixin):
    name = models.CharField(max_length=20)
    active = models.BooleanField(default=True)

    class Meta:
        verbose_name = 'Categoria'
        verbose_name_plural = 'Categorias'

    def __str__(self):
        return self.name


class Post(DatastampMixin):
    title = models.CharField(max_length=30)
    content = models.TextField()
    author = # ?????????
    category = models.ForeignKey(Category, on_delete=models.CASCADE)
    
asked by anonymous 15.03.2018 / 01:34

2 answers

0

from django.db import models
from django.contrib.auth.models import User


class Category(DatastampMixin):
    name = models.CharField(max_length=20)
    active = models.BooleanField(default=True)

    class Meta:
        verbose_name = 'Categoria'
        verbose_name_plural = 'Categorias'

    def __str__(self):
        return self.name


class Post(DatastampMixin):
    title = models.CharField(max_length=30)
    content = models.TextField()
    author = models.ForeignKey(User, on_delete=models.CASCADE)
    category = models.ForeignKey(Category, on_delete=models.CASCADE)

    class Meta:
        verbose_name = 'Post'
        verbose_name_plural = 'Posts'

    def __str__(self):
        return self.title
    
15.03.2018 / 03:32
0

There is another possibility, I just do not know if it suits what you need.

author = models.ForeignKey('auth.User', on_delete=models.CASCADE)
    
18.03.2018 / 17:42