我想为我的django post应用程序创建一个“ update post”功能。但是我得到一个错误。
AttributeError位于/ post / 106 /
“发布”对象没有属性“子弹”
views.py
def post_update(request, slug):
if not request.user.is_authenticated():
return Http404()
post = get_object_or_404(Post, slug=slug)
form = PostForm(request.POST or None, request.FILES or None, instance=post)
if form.is_valid():
form.save()
messages.success(request, "updated")
return HttpResponseRedirect(post.get_absolute_url())
context = {
'form': form
}
return render(request, "blog/post_edit.html", context)
models.py
class Post(models.Model):
author = models.ForeignKey('auth.User', on_delete=models.CASCADE)
title = models.CharField(max_length=200)
text = RichTextField()
created_date = models.DateTimeField(
default=timezone.now)
published_date = models.DateTimeField(
blank=True, null=True)
def publish(self):
self.published_date = timezone.now()
self.save()
def __str__(self):
return self.title
def get_update_url(self):
return reverse('post:update', kwargs={'slug': self.slug})
post_detail.html
<a href="{{ post.get_update_url }}" class="btn btn-default" role="button">update</a>
urls.py
...
url(r'^(?P<slug>[\w-]+)/update/$', post_update, name="update"),
我该怎么办? 谢谢。
答案 0 :(得分:1)
您需要创建一个SlugField
,然后编写一个save()
函数以基于某个字段创建slug
,然后它应该可以正常工作。
from django.utils.text import slugify
class Post(models.Model):
author = models.ForeignKey('auth.User', on_delete=models.CASCADE)
title = models.CharField(max_length=200)
slug = models.SlugField(max_length=40)
text = RichTextField()
created_date = models.DateTimeField(
default=timezone.now)
published_date = models.DateTimeField(
blank=True, null=True)
def publish(self):
self.published_date = timezone.now()
self.save()
def __str__(self):
return self.title
# Write the save() method
def save(self):
if not self.id:
self.slug = slugify(self.title)
super(Post, self).save()
def get_update_url(self):
return reverse('post:update', kwargs={'slug': self.slug})