P
P
PTaHHHa2020-07-15 23:59:50
Django
PTaHHHa, 2020-07-15 23:59:50

How to implement ArrayField as a list in Django forms?

In my project, there was a need to collect an array of charms. But the standard widget for an array in python does not suit me (I need to display the elements of the array as a list, and not separated by commas + the ability to dynamically add / remove elements) (attached a screenshot of an example). For the admin panel, I found such a solution , but I don’t know how to deal with forms for templates. I looked at form sets, but in all the examples, new model objects are created, and I need to create / delete array elements. Has anyone encountered such a problem? after.png

Answer the question

In order to leave comments, you need to log in

2 answer(s)
N
Nuchimik, 2020-07-17
@PTaHHHa

Because you use ArrayField, so postgres most likely. You can try to look django.contrib.postgres.forms.SimpleArrayField, but most likely there is not the widget that you need.
I would suggest that you write your own custom widget with your own template. Next, write several endpoints for adding/removing/editing array elements (if you want to do it in the background, if not, then one is enough, or save it together with the main form). In the same widget, you can write value parsing to bring it to a form that the database will understand. If you update the background, you will have to write a couple more scripts for js / jQuery (or whatever you have on your project).
Well, or a simpler option, just take the widget that is used in the solution that you found.
Of course, you can make a table, as suggestedDr. Bacon , and maybe, in your case, it will be more correct, faster, and less hemorrhoids, but these are extra database queries and it is quite possible redundancy

D
Dr. Bacon, 2020-07-16
@bacon

Well, make a separate table for email with ForeignKey for the current one.

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question