N
N
Nadia2021-01-29 23:35:30
Django
Nadia, 2021-01-29 23:35:30

How to get list of selected elements on html page in action?

Hello, I had such a problem.
The bottom line is that a list of groups will be displayed on my page, approximately in this way
60146c9245ccc377626124.png

. And it will also be possible to select this group and then the id of the selected groups is processed in the action.

Here is my code:

Model

class Groups(models.Model):
    id_group = models.IntegerField() {#это дополнительное нужное поле, не то, которое является ключевым в таблице бд#}
    name = models.CharField('Название группы', max_length=50)

    def __str__(self):
        return self.name

    class Meta:
        verbose_name = 'Группа'
        verbose_name_plural = 'Группы'


The form
class GroupsForm(ModelForm):
    class Meta:
        model = Groups
        fields = ['id_group', 'name']

        widgets = {
            "id_group": TextInput(attrs={
                'class': 'input100'
            }),
            "name": TextInput(attrs={
                'class': 'input100'
            }),
        }


form on html page
<form method="post" class="contact_form" name="contact_form" id="contact">
        {% csrf_token %}
        <div>
  <div style="margin: 5%;" class="btn-group" id="group_main">
            {% for el in list_info %} {# здесь отображение групп, в list_info хранятся id групп #}
<div style="position: relative; width: 200px; height: 100px">
                    <button id="{{ el.id_group }}" class="btn_check_group">
                        <div style="position: absolute; top: 0; left: 0; width: 200px">
                            <img src="{% static 'main/images/pr.png' %}" alt="..."/>
                        </div>
                        <div>
                            {{ el.name }}
                        </div>
                    </button>
                </div>
            {% endfor %}
        </div>
    </form>


view
def send_message(request):
    all_info = Groups.get_id_groups()
    list_info = list(all_info)
    if request.method == 'POST':
        form = MessageForm(request.POST)
...
 form = MessageForm()

    data = {
        'form': form,
        'list_info': list_info,
    }
    return render(request, 'main/send_message.html', data)


I tried via ajax (I created a handler when the button is clicked, in which the id is added to the array, and then the array is sent via ajax)
<script>
        var selected_groups = [];
...
$("#contact").submit(function (e) {
            e.preventDefault();
            e.stopPropagation();
            const data = $('form').serializeArray();
            $.ajax({
                type: 'POST',
                url: 'http://127.0.0.1:8000/main/', {# я также еще не разобралась как правильно указывать url #}
                data: {'data': data, 'selected_groups': selected_groups},
                dataType: 'json',
            });


But in this case, the list itself is not sent, + there is a problem with csrf_token

In general, please tell me how to get the list of selected groups in action, at least in which direction to go, I am creating a project in Python for the first time and using Django for the first time, so a lot is possible what is wrong
I would be grateful for any hint, thanks in advance)))

Answer the question

In order to leave comments, you need to log in

1 answer(s)
S
siarheisiarhei, 2021-02-04
@siarheisiarhei

here is the formula

city_notes_choice = forms.ModelChoiceField(
        queryset=City.objects.all(),
        widget=forms.RadioSelect,
        to_field_name="name",
        empty_label="choose",
    )

on it convert the form (html) and do with it what you need

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question