I'd like to use the same form for both adding new records to the database and editing existing ones. The id of the record to be edited is passed via the URL (is this how I should do it?):
urlpatterns = [
path('add-or-edit/<int:id>/', add-or-edit_view, name='edit'),
path('add-or-edit/', add-or-edit_view, name='create'),
[...]
views.py:
def add-or-edit_view(request, id):
if id is not there: # pseudocode, of course :)
form = MyForm(request.POST or None)
elif request.method == "POST":
obj = get_object_or_404(Event, id=id)
form = MyForm(request.POST or None, instance=obj)
if form.is_valid():
form.save()
context = {
'form':form
}
return render(request, "templates/add-or-edit.html", context)
I other words: if I go to add-or-edit/ then I want my empty form, if I go to add-or-edit/1 I want the form populated with data from the object with id 1. I am already doing this with two different views, one edit_view(request, id)
and the other add-or-edit_view(request)
, which of course is not DRY.
PS
If I use:
def event_edit_view(request, id='None'):
obj = get_object_or_404(Model, id=id)
form = MyForm(request.POST or None, instance=obj)
then Django will complain if I access the URL with no parameters:
ValueError at /add-or-create/
Field 'id' expected a number but got 'None'.
PS 2
If I use:
def add-or-edit_view(request, id='None'):
if id =='None':
[unbound form]
else:
[bound form]
then I get:
AttributeError at /add-or-edit/
'NoneType' object has no attribute 'has_header'