Search code examples
djangodjango-viewsdjango-forms

A form with an arbitrary number of fields in Django


I am a beginner web developer and just learning Django.

Question: I have a ListView that displays pictures (16-100 or more) on a website page. Each picture has a checkbox. The user can select multiple images and assign them a tag (from input field). How can I make a Django form for this? And how to process it correctly in my ListView?


Solution

  • Not sure if this is a good way. But I did so.

     def get_context_data(self, **kwargs: Any) -> Dict[str, Any]:
        context = super().get_context_data(**kwargs)
        if tag := self.request.GET.get('tag'):
            select_tag = Tag.objects.get_or_create(tag=tag)[0]
            for key, value in self.request.GET.items():
                if key.isdigit() and value == 'on':
                    Image.objects.get(pk=key).tags.add(select_tag.pk)
    

    and template

         <form action="" class="tm-text-primary" method="GET" id="tag_selector">
              Тег: <input name="tag" type="input">&nbsp;
            </form>         
    

    ...

    <input type="checkbox" id="{{ image.pk }}" name="{{ image.pk }}" form="tag_selector">