1

How I can go about adding multiple objects from a single form with Django?

For example: if I have a sales form which stores sold products' register.

Imagine the form:

datetime: [_____________]
customer: [_____________]
product: [______________] ---> How should I implement adding multiple products
                               in the same form?
cost: [_________________] 

Save (button)

Hint: it is just a question, if you have some ideas tell me please because I don't know how to do it.

thanks

1 Answer 1

2

One way is to use a Formset. Formsets you may have seen, for example, in Django admin for displaying multiple related objects as inlines.

Another way could involve AJAX, example solution:

  • “Added products” is a simple <ul> list with products added to order
  • “Search product” is a plain text field, where user enters product name or SKU
  • User input is sent via AJAX to the server, which returns a list of relevant products
  • These product suggestions are displayed to user
  • When user clicks on a product name, another AJAX request is made to associate given product with the order
  • After request completes, the “Added products” list is refreshed via AJAX, and newly added product appears there

This would require that you first create a temporary order to which you could later attach products via separate requests. Formsets don't have this requirement, but personally I haven't used them a lot, they look a bit cumbersome.

Sign up to request clarification or add additional context in comments.

2 Comments

first I want to thank you for fixing my question :) ....OH that interesting, honestly I was thinking about implement ajax in my project.. Do you know about some tutorial about it???
I can't remember any, but it's simple, you just write a regular view and request its URL via e.g. jQuery's $.ajax(). View can return partial HTML that you add to your page and display to user, or it can return JSON that you process in your JS (e.g. creating necessary DOM elements to display product suggestions).

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.