Answer the question
In order to leave comments, you need to log in
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
. 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 = 'Группы'
class GroupsForm(ModelForm):
class Meta:
model = Groups
fields = ['id_group', 'name']
widgets = {
"id_group": TextInput(attrs={
'class': 'input100'
}),
"name": TextInput(attrs={
'class': 'input100'
}),
}
<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>
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)
<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',
});
Answer the question
In order to leave comments, you need to log in
here is the formula
city_notes_choice = forms.ModelChoiceField(
queryset=City.objects.all(),
widget=forms.RadioSelect,
to_field_name="name",
empty_label="choose",
)
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question