Problem statement
Reading an article and writing one used to be the same function, branching on the request method and assembling both pages by hand. Two generic views replace it - but a generic view only fills in what it can work out for itself. The detail view can manage on its model alone. The create view cannot: it does not know which form to build, and when the article is saved it has nowhere to send the browser, because the model cannot say where one of its own instances lives.
Requirements
Implement:
- get_absolute_url on Article in app/models.py
- ArticleDetailView in app/views.py
- the form wiring on ArticleCreateView in app/views.py
The following files are already implemented and provided: app/forms.py, app/urls.py and both templates. Article holds title, slug (unique), body and published_on. The routes are given: /articles/new/ is ArticleCreateView under the name article-create, and /articles/<slug>/ is ArticleDetailView under the name article-detail. ArticleForm is a model-backed form over title, slug, body and published_on. Both templates already exist at the names Django's conventions expect, app/article_detail.html and app/article_form.html, so neither view needs a template_name.
1. The article's own address
- Article.get_absolute_url() returns the URL of that instance's detail page, so the stored first-light answers /articles/first-light/ and an article saved with another slug answers its own.
- Build it from the article-detail route name and the instance's own slug with reverse, never by writing the path out. A named route survives a change of path; a typed string does not.
- This is also what the create view redirects to: CreateView asks the saved object where it lives, and raises instead of redirecting when the model cannot answer.
2. ArticleCreateView and its form
- The view builds ArticleForm, so the form in the context is an instance of it rather than one the view invents from a field list.
- GET /articles/new/ answers 200 with that form unbound.
- A valid POST /articles/new/ saves the article and answers 302, redirecting to the new article's own detail page.
- An invalid POST comes back as a rendered 200 page with the errors on their fields - a missing title reported under title - and nothing saved, including a slug that is already taken, which leaves exactly one row holding it.
3. ArticleDetailView
- GET /articles/<slug>/ renders the article whose slug the URL captures, in the context as article.
- A slug that matches no article answers 404.
- A generic DetailView does all of this on its own once it knows its model.
Notes
- Only app/views.py and app/models.py change.
- Build URLs with reverse and the route name rather than writing paths as strings. A typed path works today and breaks the day the route changes, so it is the habit worth having even when both give the same URL today.
- Do not set success_url, template_name or fields, and do not override form_valid or get_success_url.
- Do not touch ArticleForm.
