我让表单呈现得很好,数据保存得很好,它只是不会像在管理员中那样创建 slug。我希望在提交表单时会自动创建 slug。谢谢你的帮助。
代码:
Models.py:
class Post(TimeStampActivate):
title = models.CharField(max_length=255,
help_text="Title of the post. Can be anything up to 255 characters.")
slug = models.SlugField()
excerpt = models.TextField(blank=True,
help_text="A small teaser of your content")
body = models.TextField()
publish_at= models.DateTimeField(default=datetime.datetime.now(),
help_text="Date and time post should become visible.")
blog = models.ForeignKey(Blog, related_name="posts")
tags = TaggableManager()
objects = PostManager()
def __unicode__(self):
return self.title
@models.permalink
def get_absolute_url(self):
return ('post', (), {
'blog': self.blog.slug,
'slug': self.slug
})
class Meta:
ordering = ['-publish_at','-modified', '-created']
Views.py:
def add2(request):
if request.method == "POST":
form = BlogPostForm(request.POST)
if(form.is_valid()):
message = "thank you for your feedback"
form.save()
return render_to_response('add.html',
{'success':message},
context_instance=RequestContext(request))
else:
return render_to_response('add.html',
{'form':BlogPostForm},
context_instance=RequestContext(request))
Forms.py:
class BlogPostForm(forms.ModelForm):
class Meta:
model = Post
exclude = ('id', 'user', 'slug')
Admin.py:
class PostAdmin(admin.ModelAdmin):
prepopulated_fields = {"slug": ("title",)}
list_display =('active', 'title', 'excerpt', 'publish_at')
list_display_links=('title',)
list_editable = ('active',)
list_filter = ('modified', 'publish_at', 'active')
date_hierarchy = 'publish_at'
search_fields = ['title', 'excerpt', 'body', 'blog__name', 'blog__user__username']
fieldsets = (
(None, {
'fields': ('title', 'blog'),
}),
('Publication', {
'fields': ('active', 'publish_at'),
'description': "Control <strong>whether</strong> or not and when a post is visual to the world",
}),
('Content', {
'fields': ('excerpt', 'body', 'tags',),
}),
('Optional', {
'fields': ('slug',),
'classes': ('collapse',)
})
)
admin.site.register(Post, PostAdmin)