Hello everyone I need the authorship to be automatically assigned to the user when creating an article and only he could change it. But so far, nothing is working out for me. I ask for your help. models.py
class Author(models.Model):
author_user = models.OneToOneField(User, verbose_name='Author name', on_delete=models.CASCADE)
ratting_author = models.SmallIntegerField(default=0, verbose_name='Ratting author')
class Post(models.Model):
author = models.ForeignKey(Author, on_delete=models.CASCADE, verbose_name='Author')
NEWS = 'NW'
ARTICLE = 'AR'
CATEGORY_CHOICES = (
(NEWS, 'News'),
(ARTICLE, 'Article'),
)
category_type = models.CharField(max_length=2, choices=CATEGORY_CHOICES, default=NEWS, verbose_name='Тип')
date_time_create = models.DateTimeField(auto_now_add=True, verbose_name='Date created')
categoryPost = models.ManyToManyField(Category, through='PostCategory', related_name='category', verbose_name='Category')
heading = models.CharField(max_length=255, verbose_name='Title')
content = models.TextField(verbose_name='Текст')
ratting_post = models.SmallIntegerField(default=0, verbose_name='Ratting post')
view.py
class NewsCreate(PermissionRequiredMixin, CreateView):
permission_required = ('news.add_post',)
form_class = NewsForm
model = Post
template_name = 'news_create.html'
def form_valid(self, form):
post = form.save(commit=False)
post.category_type = 'NW'
form.instance.author = self.request.user.author
post.save()
send_email_task.delay(post.pk)
return super().form_valid(form)
forms.py
class NewsForm(forms.ModelForm):
heading = forms.CharField(max_length=40)
content = forms.CharField(min_length=20)
class Meta:
model = Post
fields = [
'heading',
'categoryPost',
'content',
]
I tried everything I could. Apparently there is still little knowledge, I'm just learning.
views.py
In the
form_validmethod, make the following changes:Another thing, in your
NewsFormclass, you are overriding fields that you have already defined in yourPostmodel. TheModelFormclass does the work of rendering the fields.