Не могу добавить пост на сайт, при добавлении выходит с учетной записи
Почему не работает форма, при вводе данных выходит с учетной записи
views.py
class AddPage(PermissionRequiredMixin, LoginRequiredMixin, DataMixin, CreateView):
form_class = AddPostForm
template_name = 'women/addpage.html'
title_page = 'Добавление статьи'
permission_required = 'women.add_women' # <приложение>.<действие>_<таблица>
def form_valid(self, form):
w = form.save(commit=False)
w.author = self.request.user
return super().form_valid(form)
forms.py
class AddPostForm(forms.ModelForm):
cat = forms.ModelChoiceField(queryset=Category.objects.all(), empty_label="Категория не выбрана", label="Категории")
husband = forms.ModelChoiceField(queryset=Husband.objects.all(), empty_label="Не замужем", required=False, label="Муж")
class Meta:
model = Women
fields = ['title', 'slug', 'content', 'photo', 'is_published', 'cat', 'husband', 'tags']
widgets = {
'title': forms.TextInput(attrs={'class': 'form-input'}),
'content': forms.Textarea(attrs={'cols': 50, 'rows': 5}),
}
labels = {'slug': 'URL'}
def clean_title(self):
title = self.cleaned_data['title']
if len(title) > 50:
raise ValidationError("Длина превышает 50 символов")
return title
models.py
class Women(models.Model):
class Status(models.IntegerChoices):
DRAFT = 0, 'Черновик'
PUBLISHED = 1, 'Опубликовано'
title = models.CharField(max_length=255, verbose_name="Заголовок")
slug = models.SlugField(max_length=255, unique=True, db_index=True, verbose_name="Slug", validators=[
MinLengthValidator(5, message="Минимум 5 символов"),
MaxLengthValidator(100, message="Максимум 100 символов"),
])
photo = models.ImageField(upload_to="photos/%Y/%m/%d/", default=None,
blank=True, null=True, verbose_name="Фото")
content = models.TextField(blank=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(choices=tuple(map(lambda x: (bool(x[0]), x[1]), Status.choices)),
default=Status.DRAFT, verbose_name="Статус")
cat = models.ForeignKey('Category', on_delete=models.PROTECT, related_name='posts', verbose_name="Категории")
tags = models.ManyToManyField('TagPost', blank=True, related_name='tags', verbose_name="Теги")
husband = models.OneToOneField('Husband', on_delete=models.SET_NULL,
null=True, blank=True, related_name='wuman', verbose_name="Муж")
author = models.ForeignKey(get_user_model(), on_delete=models.SET_NULL, related_name='posts', null=True, default=None)
objects = models.Manager()
published = PublishedManager()
def __str__(self):
return self.title
class Meta:
verbose_name = "Известные женщины"
verbose_name_plural = "Известные женщины"
ordering = ['-time_create']
indexes = [
models.Index(fields=['-time_create'])
]
def get_absolute_url(self):
return reverse('post', kwargs={'post_slug': self.slug})
html code
{% extends 'base.html' %}
{% block content %}
<h1>{{title}}</h1>
<form action="" method="post" enctype="multipart/form-data">
{% csrf_token %}
<div class="form-error">{{ form.non_field_errors }}</div>
{% for f in form %}
<p><label class="form-label" for="{{ f.id_for_label }}">{{ f.label }}</label>{{ f }}</p>
<div class="form-error">{{ f.errors }}</div>
{% endfor %}
<p><button type="submit">Отправить</button></p>
</form>
{% endblock %}