Reputation: 391
I get the form to renders fine, the data is saved fine, it just doesn't create the slug like it does in the Admin. I'm hoping that when a form is submitted the slug will be created automatically. Thanks for your help.
Code:
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)
Upvotes: 0
Views: 1439
Reputation: 3240
The slug in your admin is prepopulated by javascript (clientside). If want this in your form too, youll have to use some javascript too (clientside), or write a custom save function for your Post Model which could use djangos slugify filter (serverside).
For example:
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)
Upvotes: 2