how to add the slugified field

2019-07-09 08:35发布

问题:

while creating a blog i am using the following model class and form .but since i don't want the user to add the url(slugified field) himself i am stuck how can i add the slugified url before saving the model,should it be done in the view if i am correct. PS: i am using app engine where i heard that the slug fields aren't available.

  class Post(db.Model):
          title=db.StringProperty(required=True)
            url=db.StringProperty(required=True)
            content_html=db.TextProperty(required=True)
            dateTime=db.DateTimeProperty(auto_now_add=True,required=True)
            tags=db.StringListProperty()


class PostForm(djangoforms.ModelForm): 
 class Meta:
  model=Post
  exclude=['url']

回答1:

You could either do this in your view or override your form's save method. If you do it in your view it will look something like this:

#views.py
from django.template.defaultfilters import slugify

def post_create(request, ...):
    ...
    if request.method == 'POST':
        form = PostForm(request.POST)
        if form.is_valid():
            post = form.save(commit=False)
            title = form.cleaned_data['title']
            slugified_title = str(slugify(title))
            post.url = [modify the slugified_title however you want...]
            post.save()
    ...

Alternatively, you can override your form's save method which would look something like:

#forms.py
class PostForm(django.forms.ModelForm):
    class Meta:
        model=Post
        exclude=['url']
    def save(self, commit=True, force_insert=False, force_update=False):
        post = super(PostForm, self).save(commit=False)
        slugified_title = str(slugify(post.title))
        post.url = [modify the slugfield_title however you want...]
        post.save()