0

我让表单呈现得很好,数据保存得很好,它只是不会像在管理员中那样创建 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)
4

1 回答 1

2

管理员中的 slug 由 javascript(客户端)预填充。如果你也想在你的表单中使用这个,你也必须使用一些 javascript(客户端),或者为你的 Post 模型编写一个自定义保存函数,它可以使用 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)
于 2012-08-23T19:30:24.500 回答