how to add the slugified field

╄→гoц情女王★ 提交于 2019-12-11 03:53:23

问题


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()


来源:https://stackoverflow.com/questions/4238401/how-to-add-the-slugified-field

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!