我遇到错误dispatch() missing 1 required positional argument: 'slug'
。我试过了
def dispatch(self, request, slug=none, *args, **kwargs):
和def dispatch(self, request, slug=title, *args, **kwargs):
。我希望人们能够在帖子中添加评论。我尝试了各种实验(包括上面列出的几个实验),每个实验都导致我无法解决的错误消息。
ListView现在无法正常工作
在尝试解决我的问题时,我设法阻止ListView工作。
class PostListView(ListView):
model = Post
template_name = 'blog/home.html' # <app>/<model>_<viewtype>.html
context_object_name = 'posts'
ordering = ['-date_posted']
我将这些代码行添加到导致问题的模型中。
url= models.SlugField(max_length=500, unique=True, blank=True)
def save(self, *args, **kwargs):
self.url= slugify(self.title)
super(UserPost, self).save(*args, **kwargs)
views.py
class PostDetailView(DetailView):
model = Post
def dispatch(self, request, slug, *args, **kwargs):
post = get_object_or_404(Post)
comments = post.comments.filter(active=True, slug=slug)
new_comment = None
if request.method == 'POST':
abc
else:
xyz
models.py
更新-我试图基于Pedros注释添加一个SlugField。
class Post(models.Model):
title = models.CharField(max_length=20)
content = models.TextField()
date_posted = models.DateTimeField(default=timezone.now())
author = models.ForeignKey(User, on_delete=models.CASCADE)
url= models.SlugField(max_length=500, unique=True, blank=True)
def save(self, *args, **kwargs):
self.url= slugify(self.title)
super(UserPost, self).save(*args, **kwargs)
def __str__(self):
return self.title
def get_absolute_url(self):
return reverse('article_detail', kwargs={'slug': self.slug})
class Comment(models.Model):
post = models.ForeignKey(Post,on_delete=models.CASCADE,related_name='comments')
name = models.CharField(max_length=30)
email = models.EmailField()
body = models.TextField()
created_on = models.DateTimeField(auto_now_add=True)
active = models.BooleanField(default=True)
urls.py
from django.urls import path
from .views import (
PostListView,
PostDetailView,
PostCreateView,
PostUpdateView,
PostDeleteView
)
from. import views
from django.views.generic import TemplateView
urlpatterns = [
path('', PostListView.as_view(), name='blog-home'),
path('post/<int:pk>/', PostDetailView.as_view(), name='post-detail'),
path('post/new/', PostCreateView.as_view(), name='post-create'),
path('post/<int:pk>/update/', PostUpdateView.as_view(), name='post-update'),
path('post/<int:pk>/delete/', PostDeleteView.as_view(), name='post-delete'),
path('about/', views.about, name='blog-about'),
path('facebook/',TemplateView.as_view(template_name='blog/index.html'), name="facebook")
]