我让表单渲染得很好,数据保存得很好,它只是不像管理员那样创建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)
答案 0 :(得分:1)
管理员中的slu is由javascript(clientside)预先填充。如果你想在你的表单中使用它,你也必须使用一些javascript(clientside),或者为你的Post Model编写一个自定义保存函数,它可以使用djangos slugify过滤器(服务器端)。
例如:
from django.template.defaultfilters import slugify
class Post(models.Model):
#### define fields and other functions here ###
def save(self, *args, ***kwargs):
self.slug = slugify(self.title)
super(Post, self).save(*args, **kwargs)