How do you add a reference ID name/number to a form on submit?

Each user may complete multiple forms, one to many. These forms are saved to the DB, each user can view their form history. Admin can view all forms.

How can a name/number be added automatically on submit?
Ex.
Bicycle Form - Ref no. BF0123
Skateboard Form - Ref no. SF034

Any help greatly appreciated.

Thank you,
Zeb

Hello Zeb,

this will depend on where does the reference IDs come from? Do you have them in the database?

Thank you for your reply.

The forms are being saved to a Postgresql. I would like to know how to get the ID automatically generated and added to one of the form fields and saved in the form. Or perhaps there’s an ID already generated that I can pass into the field and add characters. This would preferably be in a similar format as stated above ‘BF0123’. Each form would have it’s own ID. Perhaps the same user fills out 2 Bicycle Forms. The result I would like to achieve is each form would have a Reference number/id BF023, BF45.

How do you add a reference ID name/number to a form on submit?

Thx

Sorry, I am still not really clear what you need to achieve.

If you are going to save the form to database, then you can add ID directly do the new model object and not bother adding it to the form.

What is the source of the ID you want to add?

Each Django model has automatic ID, so after you first save it, you could get its id property, modify it with any prefix you want and save it to different field on the model. But as I said, I don’t know if this is really what you want.

One side note I’ll add here to try and help avoid confusion when you’re reading the documentation.

These statements are not accurate. You do not save forms in the database.

A form submits data to a view. The view uses that data to create or update an instance of a model. The model is then saved to the database.

Now, the generic Class Based Views hide much of that - but that doesn’t mean you can ignore that those steps still exist.

So what does this have to do with your question?

When a form is submitted, the view is what’s responsible for the model instance. The view, therefore, can add, modify, or remove data from the model instance before it is saved.

So the direct answer to the question:

is that you do that step in your view that processes the form.

Thank you very much for the clarification. Now to locate a tutorial/docs for adding the logic in the view.

Instead of using class based view would you suggest using function based view?

Of all the different reasons that exist to choose between an FBV and a CBV, this isn’t one of them. Your choice between these two options don’t really depend upon your needs to update submitted data.

If you’re not familiar with how the Django CBVs work, I always recommend the Classy CBV site and the CBV diagrams pages. They helped me a lot to understand how they work.

1 Like