0

I would like to only take input of A or B from HTML Form I create... But this one did not work. I have tried if type is not 'A' or 'B' or using !=.. nothing worked. What is the right code for it?

forms.py

class YamlForm(forms.ModelForm):
class Meta:
    model = Form_info
    fields = '__all__'
    # fields = ['name', 'type', 'vlan_id', 'rdp', 'ip_master', 'ip_backup', 'vip', 'nat_ip', 'cidr', 'dns', 'dhcp', 'dhcp_pool_start', 'dhcp_pool_end']
    widgets = {
        'name': forms.TextInput(attrs={'id': 'name', 'name': 'name'}),
        'vlan_id': forms.TextInput(attrs={'id': 'vlan_id', 'name': 'vlan_id'}),
        'rdp': forms.Select(choices=BOOLEAN_CHOICES),
        'dhcp':forms.Select(choices=BOOLEAN_CHOICES)
    }
    error_messages = {
        'name': {
            'max_length': _("This writer's name is too long."),
        },
    }


def clean_type(self):
        type = self.cleaned_data['type']
        if not 'A' or 'B':
            raise forms.ValidationError("Please enter A or B")


        return type


def clean_vlan_id(self):
        vlan_id = self.cleaned_data.get('vlan_id')
        if vlan_id not in range(1300, 1899):
            raise forms.ValidationError("Pleanse enter the right # in range")

        return vlan_id

my HTML

</div>
<div class="row">
  <div class="col-25">
    <label for="type">TYPE:</label>
  </div>
  <div class="col-75">
    <span class="text-danger" small>{{ form.type.errors }}</span>
      {{ form.type }}

  </div>
2
  • 1
    if not 'A' or 'B': is this really what's in your code ? Commented Jun 12, 2018 at 18:25
  • Yeah.. the thing is I can only validate one either A or B but cant do both using or condition Commented Jun 12, 2018 at 18:27

1 Answer 1

2

Your problem is not with Django, but purely with Python.

if not 'A' or 'B':

won't evaluate to what you expect. Instead when you want to compare a variable on multiple values use this syntax:

if type not in {'A','B'}:

Note that I used a set be cause it has a faster look-up time than other data structures like list.

Sign up to request clarification or add additional context in comments.

12 Comments

Omg it worked... Thank yo so much. You saved my day :)
Can I ask you one more question? If I wanted to make the range of 1300-1899 and 2300-2649, I used range but it won't work :( sorry I will edit it. I am new here
You can, but I can't understand what you just wrote.
so i edited another def up there. so I am giving a range of 1300-1899 and 2300-2649 from my user input on HTML form.. in this case should I use separate if statement? even my first if statement wont work when I used the range syntax
Since these ranges are not a single value like 'A' or 'B'.. I am not sure if I can use set like you did before.. I don't know how to express ranges in #.
|

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.