The issue is caused here:
def preview(request):
form = MyModelForm()
date = MyModel.objects.order_by('date')[0]
name = MyModel.objects.order_by('name')[0]
You are querying objects, sorting and taking the first item. However, if there are no items it is not possible to do this. Instead use .first()
, e.g.
date = MyModel.objects.order_by('date').first()
name = MyModel.objects.order_by('name').first()
This will return the first item, if there is one, or None
if not. See the documentation for more info. There are also some other examples in this question for alternative ways to handle this.
However, I would recommend that you do not use this approach. When you save the new object (form01.save()
) this returns the newly created object. You can then access this directly for your preview. For example:
preview_model = form01.save()
Using MyModel.objects.order_by('date').first()
to get the 'latest record' opens you to a race condition when another user edits another object between the .save()
and the select.
I'm not sure of the purpose of name = MyModel.objects.order_by('name').first()
as this is going to return a completely different object to the previous bit (the first object sorted alphabetically) - and I cannot imagine why you would want that. Try something like the following in views.py
:
def form1(request):
form = MyModelForm()
if request.method == 'POST':
form01 = MyModelForm(request.POST, request.FILES)
if form01.is_valid():
preview = form01.save()
date = preview.date
return render(request, 'WebMamOffice/en/preview.html', {'form': form01, 'date': date, 'name': name})
return render(request, 'WebMamOffice/en/form1.html', {'form': form})