我正在开发一个包含2个应用程序的项目:帐户和博客。帐户具有所有登录,注销,密码更改,注册视图和URL等。
在博客应用程序中,我有4个视图可以列出所有帖子,帖子的详细信息,创建新帖子(@login_required)和编辑帖子(@login_required)。
虽然创建帖子视图(post_create)工作正常并允许登录用户添加带标签的新帖子(使用django-taggit app),但编辑视图根本不保存表单数据。我尝试使用管理站点编辑帖子,但令我惊讶的是,数据也没有改变。我已经尝试了很多解决方案,甚至在类似问题上阅读了很多相关论坛,但无法弄清楚到底出了什么问题。
一行中的问题:无法编辑和保存帖子表单,无法编辑管理站点上的帖子。
我在这里为模型,表单和视图提供代码。
#models.py
class PublishedManager(models.Manager):
def get_queryset(self):
return super(PublishedManager,self).get_queryset().filter(status='published')
class Post(models.Model):
STATUS_CHOICES = (
('draft','Draft'),
('published','Published'),
)
title = models.CharField(max_length=250)
slug = models.SlugField(max_length=250,unique_for_date='publish')
author = models.ForeignKey(User,related_name='blog_posts')
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=10,
choices=STATUS_CHOICES,
default='draft')
objects = models.Manager()# default manager
published = PublishedManager()# custom
tags = TaggableManager()
class Meta:
ordering =('-publish',)
def __str__(self):
return self.title
# to build canonical URL for Post objects using post_detail URL.
def get_absolute_url(self):
return reverse('blog:post_detail',
args=[self.publish.year,
self.publish.strftime('%m'),
self.publish.strftime('%d'),
self.slug])
# overide save() method to generate slug field automatically based on title
def save(self, *args, **kwargs):
if not self.slug:
self.slug = slugify(self.title)
super(Post,self).save(*args,**kwargs)
#views.py
@login_required
def post_create(request):
if request.method == 'POST':
form = PostCreateForm(request.POST)
if form.is_valid():
new_post = form.save(commit=False)
new_post.author = request.user
new_post.publish = timezone.now()
new_post.save()
form.save_m2m()
#messages.success(request,'Post added successfully')
return redirect(new_post.get_absolute_url())
else:
form = PostCreateForm()
context = {
"form": form,
}
return render(request,'blog/post/create.html',context)
@login_required
def post_edit(request,pk):
post = get_object_or_404(Post,id = pk)
if request.method == 'POST':
form = PostCreateForm(data=request.POST,instance=post)
if form.is_valid():
post = form.save(commit=False)
post.author = request.user
post.publish = timezone.now()
post.save()
form.save_m2m()
return redirect(post.get_absolute_url())
else:
form = PostCreateForm(instance=post)
return render(request,'blog/post/create.html',{'form':form})
def post_list(request,tag_slug=None):
object_list = Post.published.all()
tag = None
if tag_slug:
tag = get_object_or_404(Tag,slug=tag_slug)
object_list = object_list.filter(tags__in=[tag])
# searching posts , tag search not there
query = request.GET.get("q")
if query:
object_list = object_list.filter(
Q(title__icontains=query)|
Q(body__icontains=query)|
Q(author__first_name__icontains=query)|
Q(author__last_name__icontains=query)).distinct()
paginator = Paginator(object_list,3) # 3 posts in each page
page = request.GET.get('page') # indicates current page number
try:
posts = paginator.page(page)
except PageNotAnInteger: # if page is not an integer deliver the first page
posts = paginator.page(1)
except EmptyPage:
# If page is out of range deliver last page of results
posts = paginator.page(paginator.num_pages)
return render(request,'blog/post/list.html',
{'page':page,
'posts':posts,
'tag':tag})
def post_detail(request,year,month,day,post):
post = get_object_or_404(Post,
slug=post,
status='published',
publish__year=year,
publish__month=month,
publish__day=day)
# list of similar posts
post_tags_ids = post.tags.values_list('id',flat=True)
similar_posts = Post.published.filter(tags__in=post_tags_ids).exclude(id=post.id)
similar_posts = similar_posts.annotate(same_tags=Count('tags'))\
.order_by('-same_tags','-publish')[:4]
return render(request,
'blog/post/detail.html',
{'post':post,
'similar_posts':similar_posts})
#forms.py
class PostCreateForm(forms.ModelForm):
class Meta:
model = Post
fields = (
"title",
"body",
"status",
"tags",
)
#admin.py
from django.contrib import admin
from .models import Post
class PostAdmin(admin.ModelAdmin):
list_display = ('title','slug','author','publish','status')
list_filter = ('status','created','publish','author')
search_fields = ('title','body')
prepopulated_fields = {'slug':('title',)}
raw_id_fields = ('author',)
date_hierarchy = 'publish'
ordering = ['status','publish']
admin.site.register(Post,PostAdmin)
答案 0 :(得分:0)
如果slug为空,则只调用save(超级)方法。所以你的代码应该是这样的:(注意最后一行的意图)
class Post(models.Model):
# ...
def save(self, *args, **kwargs):
if not self.slug:
self.slug = slugify(self.title)
super(Post,self).save(*args,**kwargs)