как получить доступ к выбранному значению переключателя в Django - PullRequest
2 голосов
/ 20 октября 2019

Я пытаюсь получить доступ к выбранному переключателю значению в моем представлении django, но оно возвращает on вместо выбранного значения.

Форма шаблона

<form class="col-md-8 mx-auto" action="upload" method="post" enctype="multipart/form-data">
          {% csrf_token %}
    <div class="form-group" id="div_id_sample" >
        <label for="id_sample" class="col-form-label  requiredField">Select File</label><br>
        <div class="btn btn-primary">
        <input type="file" name="sample" class="clearablefileinput" required id="id_sample" accept=".exe">
         </div>
     </div>
     <div class="form-group">
         <label for="radiogroup">Enforce Timeout</label><br>
         <div class="btn-group" data-toggle="buttons" id="radiogroup">
             <label class="btn btn-secondary">
             <input type="radio" name="timeoptions" id="option60" autocomplete="off" value="60"> 60 seconds
             </label>

             <label class="btn btn-secondary">
             <input type="radio" name="timeoptions" id="option120" autocomplete="off" value="120"> 120 seconds
             </label>

             <label class="btn btn-secondary active">
             <input type="radio" name="timeoptions" id="option180" autocomplete="off" checked value="180"> 180 seconds
             </label>
         </div>
     </div>
      <div class="form-group">
         <label for="radiogroup2">Select Machine:</label><br>
            <div class="btn-group" data-toggle="buttons" id="radiogroup2">
                <label class="btn btn-secondary">
                <input type="radio" name="machineoptions" id="machine1" autocomplete="off" value="0"> Windows XP
                </label>

                <label class="btn btn-secondary active">
                <input type="radio" name="machineoptions" id="machine2" autocomplete="off" value="1" checked> Windows 7
                </label>
            </div>
       </div>
      <button type="submit" class="btn btn-primary">Submit</button>
</form>

views.py в моих представлениях я использую ModelForm, но не в своем HTML, и причина в том, чтоя скопировал и вставил код html, сгенерированный ModelForm. Причина в том, что мне нужно собрать еще два предмета, которых нет в моей МОДЕЛИ данных, поэтому почему.


def upload(request):
    if request.user.is_authenticated:
        if request.method == 'POST':
            file = request.FILES['sample']
            form = SampleForm(request.POST, request.FILES)
            if form.is_valid():
                new_sample = form.save(commit=False)
                new_sample.file_name = file.name
                new_sample.user = request.user
                print(request.POST)
                TimeOut = request.POST.get('timeoptions')
                machine = request.POST.get('machineoptions')

                print(TimeOut)
                print(machine)

                form.save()
                return redirect('reports')
            else:
                messages.info(request,'Invalid Form')
        else:
            form = SampleForm()
        if request.method == 'GET':
            return render(request, 'upload2.html', {'form': form})
    else:
        return redirect(reverse('login'))


Вывод на печать

<QueryDict: {'csrfmiddlewaretoken': ['VvAqdOp8RrpKOgwxLD2dpGartPvUrTHTg9AUbqsX6vphxdojTJqn7tsvLCkneWOm'], 'timeoptions': ['on'], 'machineoptions': ['on']}>
on
on

Я просто пытаюсь получить доступ к выбранному значению кнопки.

1 Ответ

2 голосов
/ 20 октября 2019

Полагаю, это в основном потому, что вы заключаете тег <input> в тег <label>. Также вы должны задать атрибут for for и поместить элемент ввода id в тег <label> * 1006. *

Попробуйте так:

<label class="btn btn-secondary" for="option60">60 seconds</label>
<input type="radio" name="timeoptions" id="option60" autocomplete="off" value="60"> 

Вы можете сделать это для всех переключателей. Затем, по вашему мнению, вы можете получить доступ с помощью TimeOut = request.POST.get('timeoptions')

...