Working with forms: editing items
This episode covers :-
1) How to create an edit form Primary key and id field.
- Setup :-
Terminal
cp -fr 21-Forms-Create 22-Forms-Edit
cd 22-Forms-Edit
source ../venv/bin/activate
- Adding the path :-
Edit mysite app urls.py file and add the edit path:
mysite/urls.py
urlpatterns = [
path('admin/', admin.site.urls),
path('', myapp_views.index, name='index'),
path('flower/create/', myapp_views.create, name='create\
'),
path('flower/edit/<int:pk>/', myapp_views.edit, name='e\
dit'), # < here
]
- Creating the edit view :-
Edit myapp views.py file and add the edit view function:
myapp/views.py
from django.shortcuts import render, get_object_or_404 # < \
here
from .models import Flower
from django.http import HttpResponseRedirect
from .forms import MyForm
def index(request):
...
def create(request):
...
def edit(request, pk=None): # < here
flower = get_object_or_404(Flower, pk=pk)
if request.method == "POST":
form = MyForm(request.POST, instance=flower)
if form.is_valid():
form.save()
return HttpResponseRedirect('/')
else:
form = MyForm(instance=flower)
return render(request, 'myapp/edit.html', {'form': form\
})
- Updating the edit link :-
Edit myapp index.html file and change the edit link to this:
myapp/templates/myapp/index.html
<a href="{% url 'edit' pk=flower.pk %}" class="card-link">E\
dit</a>
You can now edit flowers by clicking the Edit links on the frontpage.
In Details :-
- Capturing the id :-
In the edit path we capture the flower id:
Edit path
path('flower/edit/<int:pk>/', myapp_views.edit, name='edit'\
),
“pk” is a shortcut to the model primary key. “id” is the name of the default primary key field. Take a look at the 0001_initial.py file in the myapp migrations folder:
Django creates the id field automatically
...
fields=[
('id', models.AutoField..), # < here
('title', models.CharFi..)],
...
Django will automatically add the id AutoField if you don’t specify primary_key=True on any of the fields.
It’s more flexible to use the flower.pk shortcut when accessing the id field. This way you can use the same code to access the id even if you change the primary key field.
- Examining the edit view :-
In myapp views.py file we add the edit view function. It is very much like the create view function but with a few changes:
Edit view is almost like the create view
def edit(request, pk=None): # < new
flower = get_object_or_404(Flower, pk=pk) # < new
if request.method == "POST":
form = MyForm(request.POST, instance=flower) # < new
if form.is_valid():
form.save()
return HttpResponseRedirect('/')
else:
form = MyForm(instance=flower) # < new
return render(request, 'myapp/edit.html', {'form': form\
})
First we pass the captured pk to the view with pk=None. None is the default value if pk argument is not provided.
get_object_or_404 raises an Http404 exception and returns a standard 404 (page not found) error page if the object matching the lookup parameters (pk=pk) is not found.
MyForm inherits from ModelForm that can accept a model instance as a keyword argument. This means that the form.save() method will now update an existing flower instead of creating a new one.
We also use it to populate the initial form with form = MyForm(instance=flower). When you visit floweredit/<pk>/ you will be able to see and edit the existing data:
Summary :-
- pk is a shortcut to the model primary key field. Django creates a default id field automatically unless you set the primary key on any field with primary_key=True.
- get_object_or_404 fetches an object or returns a page not found view if it can’t find the object matching the lookup parameters.
- instance keyword argument allows us to update an existing object with form.save() method and populate the form with an existing data for editing.



No comments:
Post a Comment
If you have any doubts. Please let me know.