【发布时间】:2020-07-25 22:47:12
【问题描述】:
我正在尝试为我的 django 博客项目创建更新视图,但我无法弄清楚。我有一个模型,它根据发布日期和标题创建一个 url,该标题也通过一个随机 slug 生成器给出,我无法将该 url 传递给更新视图我不断收到错误“AttributeError at /posts2020 /7/24/hello-93ej/更新/ 必须使用对象 pk 或 URLconf 中的 slug 调用通用详细视图 PostUpdateView"
这是我的代码
models.py
class Post(models.Model):
STATUS_CHOICES = (
('cleared','Cleared'),('UnderReview','Being Reviewed'),('banned','Banned'),)
title = models.CharField(max_length = 300)
slug = models.SlugField(max_length = 300, unique_for_date='publish')
author = models.ForeignKey(User, on_delete=models.SET_NULL, related_name='forum_posts',null=True)
body = models.TextField()
publish = models.DateTimeField(default=timezone.now)
created = models.DateTimeField(auto_now_add=True)
updated = models.DateTimeField(auto_now=True)
status = models.CharField(max_length=12,choices=STATUS_CHOICES,default='cleared')
objects = models.Manager()
cleared = PublishedManager()
class Meta:
ordering =('-publish',)
def __str__(self):
return self.title
def get_absolute_url(self):
return reverse('posts:post_detail', args=[self.publish.year, self.publish.month, self.publish.day, self.slug])
urls.py
from . import views
from django.urls import path, include
from django.contrib.auth import views as auth_views
from .views import PostListView, PostCreateView,PostUpdateView
app_name = 'posts'
urlpatterns = [
path('', views.PostListView.as_view(), name='post_list'),
path('<int:year>/<int:month>/<int:day>/<slug:post>/',views.post_detail,name='post_detail'),
path('post/new/',PostCreateView.as_view(), name='post-create'),
path('<int:year>/<int:month>/<int:day>/<slug:post>/update/',PostUpdateView.as_view(), name='post-update'),
views.py
class PostUpdateView(LoginRequiredMixin, UpdateView):
model = Post
fields = ['title','body']
def get_success_url(self):
return reverse('posts:post-update', args=[self.publish.year, self.publish.month, self.publish.day, self.slug])
def form_valid(self, form):
form.instance.author = self.request.user
return super().form_valid(form)
post-update.html
{% extends "Main/Base.html" %}
{% block title %} Update a post {% endblock %}
{% block content %}
{% if request.user.is_authenticated %}
<h1> Update a post <h1>
<p>You can Update your post using the following form:</p>
<form method="post">
{{ form.as_p }}
{% csrf_token %}
<p><input type="submit" value="Update"></p>
</form>
{% endif %}
{% endblock %}
【问题讨论】: