Is it possible to print data from a previous form on a new form (without accessing database objects)?

I have a number which auto increments, in html I want to do something like:

{{ form.the_number.value }}

This is only going to seek the form field data of the current form though, is it possible to access data from a previous form? (ideallly the last submitted form).
I currently don’t know how this is possible, I just wanted to ask as I’m curious about what you think.

No. The HTTP protocol is stateless. There is no concept of “last submitted form”.

1 Like

Thanks for the reply - my knowledge on HTTP is limited. I probably should have known this however - my bad.

What I was trying to do was get the future value on the current form (that should be + 1 from the previous value). The real field name in my case is “ncr_number”.

Here was my workaround to achieve this - based on ordering the model by this auto-increment field (ncr_number), and then returning a new context.

   def get_context_data(self, **kwargs):
        context = super().get_context_data(**kwargs)
         record = DashboardModel.objects.first()
         num = 1
         if(record != None):
             num = record.ncr_number + 1
             context['context_number'] = num
             context['context_number'] = num
         return context

then on my form template page, I just use {{ context_number }} to get the “future number” that will be there (the next number it will increment to).

Note: There’s a race condition here - this is subject to random failures.

You should evaluate what your real objective is here, and whether you need to do what you’re trying to do.

Generally speaking, when I see attempted solutions like this, it strikes me as an XY Problem.

It does seem fragile, I wanted to avoid this idea of auto-increment but it was a requirement. It is just an integer field incrementing in a hacky way - it’s not a primary key or anything. I’m not sure about the most secure way to go about this, I’ve seen other solutions from people that also seemed precarious

Yes, there are many ways to do this wrong. It doesn’t matter that this isn’t a primary key.

Consider the situation where a first person goes to this page, and before they submit the form, a second person goes to the same page. Since the database has not changed as a result of the first request, the second request is going to get the same context_number. (And it doesn’t need to be a different person - it could be the same person opening up a new tab…)

You need to challenge the assumption that this type of number has any value in the system you’re trying to build - and then figure out what the real requirements are - which may not be the stated requirements.

You then need to factor in all the edge-case scenarios and identify what they are going to do to this process. What happens on concurrent usage? Abandoned pages? Invalid requests? (etc, etc, etc.)

1 Like