1👍
I would approach this the following way:
- You can use
.get()
to retrieve a single record,Page.objects.get(pk=page_id)
, instead of.filter()
which returns a queryset. There is also a shortcutget_object_or_404
that takes a common pattern of wrapping a.get()
into atry..except
block for you. If the model is not found, an HTTP 404 page is returned instead. - Use a ModelForm instead
- A
ModelForm
accepts aninstance
parameter of an existing model so you don’t need to set initial values.
With these things in mind your code would end up looking something like this:
# forms.py
from django import forms
class PageForm(forms.ModelForm):
class Meta:
model = Page
fields = ('title', 'image', 'content')
# views.py
from django.shortcuts import render, get_object_or_404
def edit_page(request, page_id):
page = get_object_or_404(Page, pk=page_id)
if request.method == 'POST':
form = PageForm(instance=page, request.POST)
if form.is_valid():
form.save()
else:
form = PageForm(instance=page)
return render(request, 'some_template.html', {'form': form})
def create_page(request):
if request.method == 'POST':
form = PageForm(request.POST)
if form.is_valid():
form.save()
else:
form = PageForm()
return render(request, 'some_template.html', {'form': form})
# urls.py
(r'^page/create/$', views.create_page, 'create_page'),
(r'^page/edit/(?P<page_id>\d+)/$', views.edit_page, 'edit_page'),
Source:stackexchange.com