emmett-framework / emmett

The web framework for inventors
BSD 3-Clause "New" or "Revised" License
1.06k stars 71 forks source link

I would like to add slug titles in Bloggy, but redirects are forced on form.params.id #269

Closed vegax87 closed 4 years ago

vegax87 commented 4 years ago

I have tried to use python-slugify>=4.0.0 in order to create SEO-friendly urls in bloggy (for example /post/<str:slug> instead of /post/<int:pid> ) and I've also added slug = slugify(title) under Post Model, but I noticed some issues: 1) slug doesn't appear as column in the database because it recognizes only Fields such as Field.text() and so on 2) when I replaced all pid references to slug and when I created a /new post, it forces me to redirect on form.params.id otherwise it doesn't work

gi0baro commented 4 years ago

@vegax87 ok, let's try to have some order:

Practically speaking, update the Post model:

from emmett.orm import compute

class Post(Model):
    slug = Field.string()

    @compute('slug')
    def compute_slug(self, row):
        return your_slug_method(row.title)

update the creation form:

async def new_post():
    form = await Post.form()
    if form.accepted:
        redirect(url('one', Post.get(form.params.id).slug))
    return dict(form=form)

update the get route:

@app.route("/post/<str:slug>")
async def one(slug):
    post = Post.get(slug=slug)

Hope is intelligible :)