Required field modification if checkbox is selected in Django

Asked

Viewed 892 times

0

I need to check if a "checkbox" button, called yes_no, was selected in my html page and modify the "name" field to mandatory when this checkbox is triggered. My code is this:

In the models.py file:

from django.db import models

# Create your models here.


class RandomModel(models.Model):
    name = models.CharField(max_length=200)
    shirt_size = models.IntegerField()
    yes_no = models.BooleanField()

In the file Forms.py:

from django import forms
from .models import RandomModel


class RandomForm(forms.ModelForm):
    name = forms.CharField(required=False)

    class Meta:
        model = RandomModel
        fields = ['name', 'shirt_size', 'yes_no']

In file views.py:

from django.shortcuts import render
from .forms import *
from django.shortcuts import redirect

# Create your views here.


def random_view(request):
    if request.method == 'POST':
        form = RandomForm(request.POST)
        if form.is_valid():
            form.save()
            return redirect('learn:random')

    else:
        form = RandomForm()
    return render(request, 'learn/index.html', {'form': form})

In the index.html file:

{% load staticfiles %}
<form action="{% url 'learn:random' %}" method="post">
    {% csrf_token %}
    {{ form.name }}
    {{ form.shirt_size }}
    {{ form.yes_no }}
    <input type="submit" value="Enviar">
</form>

3 answers

1


In your form the field name is not required but your model will not allow you to be saved with the field name blank, if you want to allow this set in the field name of your model blank=True.

When you inherit from forms.Form or of forms.ModelForm as it is in your case, this allows you to define some methods in your form that will make a validation let’s say more "personalizada" than those that the Django already does in the defined fields, as if the input is valid or its size.

To do this simply define methods in your form with the following signature:

def clean_<field_name>(self):
    field = self.cleaned_data['<field_name'>]
    ... # Faça aqui sua validações
    return field

Where <field_name> is the name of your form field, you have a few steps to follow in your validation which is take the field you want to validate, make your validations in case of failure raise an exception forms.ValidationError in case of success returns the field referring to the method in question (This is necessary so that the Django continue validating the other data. In your case you want to check whether the field yes_no is selected the name field becomes mandatory so we can do something like this:

from django import forms
from .models import RandomModel


class RandomForm(forms.ModelForm):

    name = forms.CharField(required=False)

    def clean_yes_no(self):
        yes_no = self.cleaned_data['yes_no']
        if yes_no:
            if not self.cleaned_data['name']:
                raise forms.ValidationError('O campo nome é obrigatório')
        return yes_no

    class Meta:
        model = RandomModel
        fields = ['name', 'shirt_size', 'yes_no']

Basic form template example:

<form action="{% learn:random %}" method="post" novalidate>{% csrf_token %}
    {% for error in form.non_field_errors %}
        <div>
            {{ error }}
        </div>
    {% endfor %}
    {% for field in form %}
        {% for error in field.errors %}
            <div>
                {{ error }}
            </div>
        {% endfor %}
        <div>
            {{ field.label_tag }}
            {{ field }}
        </div>
    {% endfor %}
</form> 
  • It worked correctly, however the validation error 'The name field is required' did not appear when I applied my form.

  • Your template is not rendering field errors.

  • All right now!

  • Managed to render errors ??

  • I did, just by including the code {{ form.yes_no.errors }} in my template the error appeared! Thanks for the help!

  • I just did a test with another code, I’m getting an error like Keyerror at /profile/config. I did the exact same thing, you would know why?

  • You could post the whole mistake for me to look at ?

  • Keyerror at /profile/config 'b2c_active'

Show 3 more comments

0

Now I have the following Forms.py file:

class SellsForm(forms.ModelForm):
    client = forms.CharField(widget=forms.TextInput(
        attrs={'type': 'hidden'}))
    yn_choices = (('Sim', 'Sim'),
                  ('Não, emissão fiscal sem ERP', 'Não, emissão ERP'))
    yn = forms.CharField(widget=forms.RadioSelect(choices=required=False)

def clean_b2c_active(self):
    b2c_active = self.cleaned_data['b2c_active']
    b2c_platform = self.cleaned_data['b2c_platform']
    print(b2c_platform)
    if b2c_active:
        if not b2c_platform:
            raise forms.ValidationError('O campo é obrigatório')
    return b2c_active

class Meta:
    model = Sells
    fields = '__all__'

def __init__(self, *args, **kwargs):
    super(SellsForm, self).__init__(*args, **kwargs)
    self.fields['b2c_platform'].required = False
    self.fields['b2b_platform'].required = False
    self.fields['b2b_platform2'].required = False
    self.fields['market_platform_1'].required = False
    self.fields['market_platform_2'].required = False

With the associated error:

KeyError at /profile/config
'b2c_active'
Request Method: POST
Request URL:    http://192.168.25.192:8000/profile/config
Django Version: 2.0.7
Exception Type: KeyError
Exception Value:    
'b2c_active'
Exception Location: C:\Users\checkstore\Desktop\Checkstore\Clientes\forms.py 
in 
clean, line 62
Python Executable:  C:\Python36\python.exe
Python Version: 3.6.5
Python Path:    
['C:\\Users\\checkstore\\Desktop\\Checkstore',
 'C:\\Users\\checkstore\\Desktop\\Checkstore',
 'C:\\Python36\\python36.zip',
 'C:\\Python36\\DLLs',
 'C:\\Python36\\lib',
 'C:\\Python36',
 'C:\\Users\\checkstore\\AppData\\Roaming\\Python\\Python36\\site-packages',
 'C:\\Python36\\lib\\site-packages',
 'c:\\users\\checkstore\\src\\django-extra-views',
 'C:\\Program Files\\JetBrains\\PyCharm '
 '2018.1.4\\helpers\\pycharm_matplotlib_backend']
Server time:    Seg, 30 Jul 2018 17:06:07 +0000
  • Error says there is no key b2c_active where you defined the same ?

  • It was defined in the models.py file as follows: b2c_active = models.Booleanfield()

  • You’re saying the error is in the method clean and the same is called when we do form.is_valid() I would like to see your view if you can.

0

The views.py file is like this:

def config_view(request):
    if request.method == "POST":
        form = SellsForm(request.POST, initial={'client': request.user.username})
        if form.is_valid():
            form.save()
            return redirect('/profile')
    else:
        form = SellsForm(initial={'client': request.user.username})
    return render(request, 'Clientes/config.html', {'form': form})

Browser other questions tagged

You are not signed in. Login or sign up in order to post.