How to use the Django User part in a model?

Asked

Viewed 326 times

2

I’m blogging and the question arose, has how to use the user system of Django 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)

2 answers

1

People who had the same doubt ta ai the solution, just import and use normally (from Django.contrib.auth.models import User)

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

0

There is another possibility, I just don’t know if it meets what you needed.

author = models.ForeignKey('auth.User', on_delete=models.CASCADE)

Browser other questions tagged

You are not signed in. Login or sign up in order to post.