<commit_before>from django import forms
from django.core.exceptions import ValidationError

import ipaddr

from cyder.base.constants import IP_TYPES, IP_TYPE_4, IP_TYPE_6
from cyder.base.eav.forms import get_eav_form
from cyder.base.eav.models import Attribute
from cyder.base.mixins import UsabilityFormMixin
from cyder.cydhcp.network.models import Network, NetworkAV
from cyder.cydhcp.site.models import Site
from cyder.cydhcp.vlan.models import Vlan
from cyder.management.commands.lib.utilities import long2ip
from cydns.ip.models import ipv6_to_longs


class NetworkForm(forms.ModelForm, UsabilityFormMixin):
    site = forms.ModelChoiceField(
        queryset=Site.objects.all(),
        empty_label="(Defaults to parent's site.)",
        required=False,
        help_text="The site the network will be put into. "
                  "Defaults to parent network's site"
    )

    routers = forms.BooleanField(label='Option "routers"', required=False,
                                 initial=False,
                                 help_text='Auto-create DHCP "routers" option')
    gateway = forms.CharField(
        label='Alternate Gateway', required=False,
        help_text=('Fill in this field to change the default gateway '
                   'in the "routers" DHCP option.'))
    subnet_mask = forms.CharField(
        label='Alternate Subnet Mask', required=False,
        help_text=('Fill in this field to change the default subnet mask '
                   'in the "routers" DHCP option.'))

    def __init__(self, *args, **kwargs):
        super(NetworkForm, self).__init__(*args, **kwargs)
        if kwargs.get('instance'):
            for fieldname in ['routers', 'gateway', 'subnet_mask']:
                field = self.fields[fieldname]
                field.widget = field.hidden_widget()
        self.fields['dhcpd_raw_include'].label = "DHCP Config Extras"
        self.fields['dhcpd_raw_include'].widget.attrs.update(
            {'cols': '80',
             'style':
             'display: none; width: 680px;'})

    class Meta:
        model = Network
        exclude = ('start_upper', 'start_lower',
                   'end_upper', 'end_lower')
        widgets = {'ip_type': forms.RadioSelect}

    def clean(self):
        cleaned_data = super(NetworkForm, self).clean()
        network_str = cleaned_data.get('network_str', '')
        try:
            ip_type = cleaned_data.get('ip_type')
            if ip_type not in IP_TYPES:
                raise ValidationError("IP type must be either IPv4 or IPv6.")
            if ip_type == IP_TYPE_4:
                network = ipaddr.IPv4Network(network_str)
                ip_upper, ip_lower = 0, int(network.network)
            elif ip_type == IP_TYPE_6:
                network = ipaddr.IPv6Network(network_str)
                ip_upper, ip_lower = ipv6_to_longs(network.network)
<commit_msg>autocreate checkbox defaults to true<commit_after>from django import forms
from django.core.exceptions import ValidationError

import ipaddr

from cyder.base.constants import IP_TYPES, IP_TYPE_4, IP_TYPE_6
from cyder.base.eav.forms import get_eav_form
from cyder.base.eav.models import Attribute
from cyder.base.mixins import UsabilityFormMixin
from cyder.cydhcp.network.models import Network, NetworkAV
from cyder.cydhcp.site.models import Site
from cyder.cydhcp.vlan.models import Vlan
from cyder.management.commands.lib.utilities import long2ip
from cydns.ip.models import ipv6_to_longs


class NetworkForm(forms.ModelForm, UsabilityFormMixin):
    site = forms.ModelChoiceField(
        queryset=Site.objects.all(),
        empty_label="(Defaults to parent's site.)",
        required=False,
        help_text="The site the network will be put into. "
                  "Defaults to parent network's site"
    )

    routers = forms.BooleanField(label='Option "routers"', required=False,
                                 initial=True,
                                 help_text='Auto-create DHCP "routers" option')
    gateway = forms.CharField(
        label='Alternate Gateway', required=False,
        help_text=('Fill in this field to change the default gateway '
                   'in the "routers" DHCP option.'))
    subnet_mask = forms.CharField(
        label='Alternate Subnet Mask', required=False,
        help_text=('Fill in this field to change the default subnet mask '
                   'in the "routers" DHCP option.'))

    def __init__(self, *args, **kwargs):
        super(NetworkForm, self).__init__(*args, **kwargs)
        if kwargs.get('instance'):
            self.fields['routers'].initial = False
            for fieldname in ['routers', 'gateway', 'subnet_mask']:
                field = self.fields[fieldname]
                field.widget = field.hidden_widget()
        self.fields['dhcpd_raw_include'].label = "DHCP Config Extras"
        self.fields['dhcpd_raw_include'].widget.attrs.update(
            {'cols': '80',
             'style':
             'display: none; width: 680px;'})

    class Meta:
        model = Network
        exclude = ('start_upper', 'start_lower',
                   'end_upper', 'end_lower')
        widgets = {'ip_type': forms.RadioSelect}

    def clean(self):
        cleaned_data = super(NetworkForm, self).clean()
        network_str = cleaned_data.get('network_str', '')
        try:
            ip_type = cleaned_data.get('ip_type')
            if ip_type not in IP_TYPES:
                raise ValidationError("IP type must be either IPv4 or IPv6.")
            if ip_type == IP_TYPE_4:
                network = ipaddr.IPv4Network(network_str)
                ip_upper, ip_lower = 0, int(network.network)
            elif ip_type == IP_TYPE_6:
                network = ipaddr.IPv6Network(network_str)
                ip_upper, ip_lower = ipv6_to_longs(network.network)

{'fraction_non_alphanumeric': 0.09912386187940217, 'fraction_numerical': 0.005840920803985569, 'mean_word_length': 2.4862275449101796, 'pattern_counts': {'":': 0, '<': 3, '<?xml version=': 0, '>': 3, 'https://': 0, 'lorem ipsum': 0, 'www.': 0, 'xml': 0}, 'pii_count': 0, 'substrings_counts': 0, 'word_list_counts': {'cursed_substrings.json': 4, 'profanity_word_list.json': 0, 'sexual_word_list.json': 0, 'zh_pornsignals.json': 0}}
{'dir': 'git-commits-cleaned', 'id': '5498908', 'n_tokens_mistral': 1740, 'n_tokens_neox': 1674, 'n_words': 418}