Answer the question
In order to leave comments, you need to log in
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='Категория'
)
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
class AddPostForm(ModelForm):
class Meta:
model = Post
fields = ['title', 'slug', 'photo', 'cat', 'content']
{% extends 'forum/base.html' %}
{% block content %}
<form method="post">{% csrf_token %}
{{ form.as_p }}
<input type="submit" value="Send message">
</form>
{% endblock %}
Answer the question
In order to leave comments, you need to log in
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question