Способ исправить "отсутствующий QuerySet" и "переопределить QuerySet" в Django
Я пытаюсь создать блог на django, но хочу добавить заполнитель в форму при создании или редактировании статьи. У меня есть файл forms.py, потому что до этого я не использовал форму из этого файла, потому что мне нужен был только файл models.py. Я нашел способ сделать то, что я хотел, и добавить заполнитель в мой ввод из моих форм. Но есть одна проблема, когда я обновил свой сайт и зашел на свои страницы, чтобы посмотреть изменения, появилась ошибка.
Итак, я попытался решить проблему, заглянув в интернет, и увидел, что у многих людей примерно такая же проблема, но ответы сводились к тому, что я должен добавить определение get_qeryset в мои представления в файле views.py для конкретных форм. Я не нашел, что я должен установить в определении get_queryset и не очень понял, куда я должен поместить эти определения. Я буду очень благодарен, если вы сможете мне помочь. Вот мой код :
Мои представления в view.py :
class BlogHome(ListView):
model = BlogPost
context_object_name = "posts"
def get_queryset(self):
queryset = super().get_queryset()
if self.request.user.is_authenticated:
return queryset
else:
return queryset.filter(published=True)
@method_decorator(login_required, name='dispatch')
class BlogPostCreate(CreateView):
form_name = UpdatePostForm
class BlogPostEdit(UpdateView):
form_name = CreatePostForm
Мой urls.py :
urlpatterns = [
path('create/', BlogPostCreate.as_view(), name="create"),
path('edit/<str:slug>/', BlogPostEdit.as_view(), name="edit"),
Мой forms.py :
from django import forms
from posts.models import BlogPost
class UpdatePostForm(forms.Form):
model = BlogPost
template_name = 'posts/blogpost_edit.html'
fields = [
'title',
'slug',
'content',
'published',
'author',
'created_on'
]
class Meta:
title = forms.CharField(
widget = forms.TextInput(attrs={'placeholder' : 'Enter the title of the article'}),
),
slug = forms.CharField(
widget = forms.TextInput(attrs={'placeholder' : 'Enter the title of the article'}),
),
content = forms.CharField(
widget = forms.TextInput(attrs={'placeholder' : 'Enter the title of the article'}),
),
created_on = forms.CharField(
widget = forms.TextInput(attrs={'placeholder' : 'Enter the date of creation'}),
),
class CreatePostForm(forms.Form):
model = BlogPost
template_name = 'posts/blogpost_create.html'
fields = [
'title',
'slug',
'content',
'published',
'author',
'created_on'
]
class Meta:
title = forms.CharField(
widget = forms.TextInput(attrs={'placeholder' : 'Enter the title of the article'}),
),
slug = forms.CharField(
widget = forms.TextInput(attrs={'placeholder' : 'Enter the title of the article'}),
),
content = forms.CharField(
widget = forms.TextInput(attrs={'placeholder' : 'Enter the title of the article'}),
),
created_on = forms.CharField(
widget = forms.TextInput(attrs={'placeholder' : 'Enter the date of creation'}),
),
Мой models.py :
from django.contrib .auth import get_user_model
from django.template.defaultfilters import slugify
from django.db import models
from django import forms
from django.urls import reverse
User = get_user_model()
class BlogPost(models.Model):
title = models.CharField(max_length=255, unique=True, verbose_name="Titre")
slug = models.SlugField(max_length=255, unique=True, blank=True)
author = models.ForeignKey(User, on_delete=models.SET_NULL, null=True, blank=True)
last_updated = models.DateTimeField(auto_now=True)
created_on = models.DateField(blank=True, null=True)
published = models.BooleanField(default=False, verbose_name="Publié")
content = models.TextField(blank=True, verbose_name="Contenu")
thumbnail = models.ImageField(blank=True, upload_to='blog')
class Meta:
ordering = ['-created_on']
verbose_name = "Article"
def __str__(self):
return self.title
def save(self, *args, **kwargs):
if not self.slug:
self.slug = slugify(self.title)
super().save(*args, **kwargs)
@property
def author_or_default(self):
return self.author.username if self.author else "L'auteur inconnu"
def get_absolute_url(self):
return reverse('posts:home')
class BlogPostCreate(CreateView):
form_class = UpdatePostForm
template_name = 'update_post.html'
success_url = 'success'
ИЛИ
class BlogPostCreate(CreateView):
model = UpdatePost
Попробуйте сделать вышеописанное. Пожалуйста, удалите @method_decorator(login_required, name='dispatch')
из этого представления класса, потому что это представление класса, а не метод.