Django выбор формы флажок не работает - PullRequest
0 голосов
/ 09 января 2020

У меня есть форма Django с флажком «Принять условия обслуживания», но если я проверю это или нет, мое приложение блокирует запрос с сообщением «Вы должны принять наши Условия обслуживания».


Вот мой код:

forms.py

class ProfileModelForm(ModelForm):

    class Meta:
        model = UserProfile
        fields = ['u_fullname',
              'u_job',
              'u_country',
              'u_email',
              'u_terms',
              ]

    def clean(self):
        cleaned_data = super(ProfileModelForm, self).clean()
        u_fullname = cleaned_data.get('u_fullname')
        u_job = cleaned_data.get('u_job')
        u_country = cleaned_data.get('u_country')
        u_email = cleaned_data.get('u_email')
        u_terms = cleaned_data.get('u_terms')
        if not u_terms:
            raise forms.ValidationError("Please read and accept our Terms of Service")

        if not u_fullname and not u_job and not u_country and not u_terms:
            raise forms.ValidationError('You have to write something!')

        return cleaned_data

Поле u_terms является логическим полем в моей модели.

views.py:

    if request.method == 'POST':
    if 'user_reg' in request.POST:
        form = ProfileModelForm(request.POST)
        if form.is_valid():
            instance = form.save(commit=False)
            #Create user and get the id
            n_user = User.objects.create_user(username=request.POST['u_email'],
                                            email=request.POST['u_email'],
                                            password=request.POST['u_password'])
            instance.user = User.objects.get(id=n_user.id)
            instance.u_profile = 'U'
            print("TERMS-->",request.POST['u_terms'])
            instance.save()
            return  # Put return here
        else:
            messages.error(request, "Error")
            #form = ProfileModelForm()

        return render(request, 'login.html', {'form': form})

    elif 'register' in request.POST:
        pass
    elif 'company' in request.POST:
        pass

и часть шаблона html, связанная с моим флажком:

<div class="col-lg-12 no-pdd">
    <div class="checky-sec st2">
        <div class="fgt-sec">
            <input type="checkbox" name="cc" id="c2" value={{ form.u_terms }}>
            <label for="c2">
                <span></span>
            </label>
            <small>Yes, I understand and agree to the workwise Terms & Conditions.</small>
        </div><!--fgt-sec end-->
    </div>
</div>

Я предполагаю, что проблема в моей части html, но я не знаю, как мне управлять логические поля из флажка.

Кто-то может мне помочь?

1 Ответ

2 голосов
/ 09 января 2020

Атрибут "name" вашего элемента <input> не соответствует атрибуту POST, ожидаемому вашей формой: cc! = u_terms.

Это можно решить двумя способами:

  • Используйте {{ form.u_terms }} для отображения всего тега <input>. Обратите внимание, что вы помещаете это в атрибут value, что неправильно (посмотрите на исходный код в вашем браузере, вы поймете, что я имею в виду).

    {{ form.u_terms }}
    {{ form.u_terms.label_tag }}
    
  • Если вам необходимо настройте атрибуты вашего <input> (что здесь не так), затем убедитесь, что вы по-прежнему обращаетесь к полю своей формы, чтобы различные атрибуты были правильными:

    <input type="checkbox" name="{{ form.u_terms.html_name }}" id="{{ form.u_terms.id_for_label }}" class="some-custom-class">
    <label for="{{ form.u_terms.id_for_label }}"><span></span></label>
    
...