E
E
EnotShow2022-03-21 14:10:01
Django
EnotShow, 2022-03-21 14:10:01

How to automatically select a user as the author of an article?

I'm learning to write websites in django based on a training project.
There is a model:

class Post(models.Model):
    title = models.CharField(max_length=255, verbose_name="Заголовок")
    content = models.TextField(blank=True, verbose_name="Текст статьи")
    photo = models.ImageField(upload_to="photos/%Y/%m/%d/", blank=True, verbose_name="Фото")
    user = models.ForeignKey(
        User,
        on_delete=models.CASCADE,
        verbose_name='Пользователь')
    slug = models.SlugField(unique=True, verbose_name='Слаг')
    time_create = models.DateTimeField(auto_now_add=True, verbose_name="Время создания")
    time_update = models.DateTimeField(auto_now=True, verbose_name="Время изменения")
    is_published = models.BooleanField(default=True, verbose_name="Статус публикация")
    cat = models.ForeignKey(
        'Category',
        on_delete=models.CASCADE,
        verbose_name='Категория'
    )

V'yushka:
class PostCreateView(LoginRequiredMixin, CreateView):
    model = Post
    form_class = AddPostForm

    template_name = "forum/addpost.html"
    context_object_name = 'form'

    login_url = 'login'

    def get_context_data(self, *, object_list=None, **kwargs):
        context = super().get_context_data(**kwargs)
        context['menu'] = menu
        context['auth'] = no_auth
        context['title'] = 'MyForum'
        return context

The form:
class AddPostForm(ModelForm):
    class Meta:
        model = Post
        fields = ['title', 'slug', 'photo', 'cat', 'content']

And finally the template:
{% extends 'forum/base.html' %}
{% block content %}

    <form method="post">{% csrf_token %}
    {{ form.as_p }}
    <input type="submit" value="Send message">
    </form>

{% endblock %}

How to make it so that when creating a post, an authorized user becomes the author of the post (user field)?

Answer the question

In order to leave comments, you need to log in

1 answer(s)
D
Dr. Bacon, 2022-03-21
@EnotShow

learning to read docs https://docs.djangoproject.com/en/4.0/topics/class...

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question