N
N
nurzhannogerbek2017-04-23 15:40:44
Django
nurzhannogerbek, 2017-04-23 15:40:44

How to do multiple selection?

Hello!
There is a "Requirement" data model . Can you describe the algorithm of actions or give an example of how to properly implement multiple selection? There is a model window for adding a new requirement, where I want to display the REQUIREMENTS_CHOICES list with checkboxes next to it. The user should be able to select the requirements he needs by clicking on the checkboxes he needs.
models.py:

class Requirement(models.Model):
    code = models.UUIDField(_('Code'), primary_key=True, default=uuid.uuid4, editable=False)
    symbol = models.CharField(_('Symbol'), max_length=250)
    name = models.CharField(_('Name'), max_length=250)

forms.py:
class RequirementAddForm(forms.ModelForm):
    symbol= forms.MultipleChoiceField(required=False, widget=forms.CheckboxSelectMultiple, choices=REQUIREMENTS_CHOICES,)

    class Meta:
        model = Requirement
        fields = ('symbol',)



REQUIREMENTS_CHOICES = (
    ('A', 'Название A'),
    ('B', 'Название B'),
    ('C', 'Название C'),
)

views.py:
def requirement_add(request, project_code):
    data = dict()
    if request.method == 'POST':
        form = RequirementAddForm(request.POST)
        if form.is_valid():
            symbols = form.cleaned_data.get('symbol') # Список отмеченных пользователем символов: Например ['A', 'C']
            for symbol in symbols:
                requirement = form.save(commit=False)
                requirement.symbol = symbol
                requirement.name = symbol.get_symbol_display() # КАК ЗАПИСАТЬ НАЗВАНИЕ?
                requirement.save()
            data['form_is_valid'] = True
            requirements = Requirement.objects.filter()
            context = {'requirement': requirement, 'requirements': requirements}
            data['html_requirement'] = render_to_string('project/requirement_list.html', context)
        else:
            data['form_is_valid'] = False
    else:
        form = GroupRequirementAddForm()
    context = {'form': form}
    data['html_requirement_form'] = render_to_string('project/requirement_add.html', context, request=request)
    return JsonResponse(data)

Answer the question

In order to leave comments, you need to log in

1 answer(s)
V
Vitaly F., 2018-05-20
@FuN_ViT

Perhaps you are using a library tailored for python 2.x on 3.x?

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question