Handle situation where Django UpdateView does not have any data to update
I have created a forms wizard where a user will be able to create and update data for the models after which I will calculate the result by gathering all the data from all the forms and present them with an output.
My user has the freedom to pick up where they left off and continue filling in data when they revisit.
Each CreateView
is linked to the next CreateView
using the success_urls
.
So each UpdateView
goes to the next UpdateView in the series of Views using the success_urls.
So when a user updates data for a form and click next, they might arrive at a form which does not have any data to update because they have not filled in that data in thier previous visit.
So get_object() returns an error as there is no data in the database for that form of that project.
How to handle this situation ?
class UserUseUpdateView(UpdateView):
model = UserUse
form_class = UserUseForm
template_name = 'user_use.html'
success_url = reverse_lazy('controller', kwargs={'step': 10, 'action': 'update'})
def get_object(self, queryset=None):
try:
project_instance = get_project(self.request)
return UserUse.objects.get(project=project_instance)
except Project.DoesNotExist:
return redirect('step-9-create')
# raise Http404(f'Project not found.')
except UserUse.DoesNotExist:
raise Http404(f'UserUse for project not found.')
def form_valid(self, form):
try:
existing_project = get_project(request=self.request)
if existing_project is not None:
form.instance.project = existing_project
log.info(f'Saving UserUse with project ID {existing_project.id} for user {self.request.user}')
return super().form_valid(form)
else:
error_msg = f"Existing project with SESSION_PROJECT_ID {self.request.session.get(SESSION_PROJECT_ID, None)} not found"
log.error(f'request user : {self.request.user} {error_msg}')
messages.error(self.request, 'Existing project not found.')
return redirect('step-1-create')
except PermissionDenied as e:
log.error(f'request user : {self.request.user} does not have permission to modify this project | {e}')
messages.error(self.request, 'You do not have permission to modify this project.')
return redirect('projects')
except Exception as e:
log.error(f'request user : {self.request.user} Unexpected error occurred | {e}')
messages.error(self.request, 'An unexpected error occurred.')
return redirect('projects')
def form_invalid(self, form):
log.error(f'request user : {self.request.user} Form invalid: {form.errors}')
messages.error(self.request, 'There were errors in your form submission.')
return super().form_invalid(form)