Issue
I want to override to a record's slug field. In my view I automatically create a new record when add_post page loaded. Like:
def add_post(request):
post=Post(owner=request.user)
post.save()
post_id = post.id
if request.method == 'POST':
form = add_form(request.POST)
if form.is_valid():
form_title = form.cleaned_data['title']
#other fields
updated_post = Post.objects.get(id=post_id)
updated_post.title = form_title
#save other fields...
updated_post.save()
And I have slug_field in my models.py as:
class Post(models.Model):
owner = models.ForeignKey(User)
title = models.CharField(max_length=100, blank=True)
#other fields...
slug = AutoSlugField(populate_form='title', unique=True)
In my views.py after post = Post(owner=request.user)
line; it creates a record with a default slug field name because there is no title value yet.
But then, as you see, I updated that post(adding title and other fields). But slug field doesn't update itself. It is still that default slug name.
How can I fix this? If it is not possible I am gonna remove AutoSlugField from my projects and use just post id.
Solution
From AutoSlugField documentation:
always_update – boolean: if True, the slug is updated each time the model instance is saved. Use with care because cool URIs don’t change (and the slug is usually a part of object’s URI). Note that even if the field is editable, any manual changes will be lost when this option is activated.
So this should work:
slug = AutoSlugField(populate_form='title', always_update=True, unique=True)
Answered By - relekang
0 comments:
Post a Comment
Note: Only a member of this blog may post a comment.