How to use the django.forms function in Django

To help you get started, we’ve selected a few Django examples, based on popular ways it is used in public projects.

Secure your code as it's written. Use Snyk Code to scan source code in minutes - no build needed - and fix issues immediately.

github Nitrate / Nitrate / tcms / testplans / forms.py View on Github external
def clean(self, data, initial=None):
        f = super(PlanFileField, self).clean(data, initial)
        if f is None:
            return None
        elif not data and initial:
            return initial

        if data.content_type not in self.VALID_CONTENT_TYPES:
            raise forms.ValidationError(
                self.error_messages['invalid_file_type'])

        if data.content_type in self.ODT_CONTENT_TYPES:
            try:
                return UploadedODTFile(data).get_content()
            except Exception:
                raise forms.ValidationError(
                    self.error_messages['unexcept_odf_error'])

        if data.content_type == MIMETYPE_HTML:
            try:
                return UploadedHTMLFile(data).get_content()
            except Exception:
                raise forms.ValidationError(
                    self.error_messages['unexpected_html_error'])
github GeotrekCE / Geotrek-admin / geotrek / common / forms.py View on Github external
pass
        elif not hasattr(self.instance, 'structure'):
            pass
        elif 'structure' in self.fields:
            pass  # The form contains the structure field. Let django use its value.
        elif self.user:
            self.instance.structure = self.user.profile.structure
        else:
            self.instance.structure = default_structure()
        return super(CommonForm, self).save(commit)


class ImportDatasetForm(forms.Form):
    parser = forms.TypedChoiceField(
        label=_('Data to import from network'),
        widget=forms.RadioSelect,
        required=True,
    )

    def __init__(self, choices=None, *args, **kwargs):
        super(ImportDatasetForm, self).__init__(*args, **kwargs)

        self.fields['parser'].choices = choices

        self.helper = FormHelper()
        self.helper.layout = Layout(
            Div(
                Div(
                    'parser',
                ),
                FormActions(
                    Submit('import-web', _("Import"), css_class='button white')
github tracon / kompassi / events / concon15 / forms.py View on Github external
self.helper = horizontal_form_helper()
        self.fields['is_public'].required = True

    class Meta:
        model = Enrollment
        fields = (
            'is_public',
            'concon_event_affiliation',
            'concon_parts',
            'special_diet',
            'special_diet_other',
        )

        widgets = dict(
            special_diet=forms.CheckboxSelectMultiple,
            concon_parts=forms.CheckboxSelectMultiple,
        )
github dellsystem / bookmarker / code / books / forms.py View on Github external
)

        return page_number


class NoteForm(forms.ModelForm, SectionChoiceForm, PageNumberForm):
    # This has to be here and not in SectionChoiceForm, otherwise the label
    # won't show up correctly (it'll default to __str__)
    section = SectionChoiceField(
        queryset=Section.objects.none(),
        required=False,
    )
    tags = forms.ModelMultipleChoiceField(
        Tag.objects.all().prefetch_related('category'),
        required=False,
        widget=forms.widgets.SelectMultiple(
            attrs={
                'class': 'ui fluid multiple search dropdown',
            }
        )
    )

    def __init__(self, book, *args, **kwargs):
        # Store the book so we can use it for populating the sections and also
        # for updating the Note in save() (but only if there isn't already a
        # book).
        self.book = book
        super(NoteForm, self).__init__(*args, **kwargs)
        self.fields['section'].queryset = book.sections.all()

        # Sections are required only for publications.
        if book.is_publication():
github dragonresearch / rpki.net / rpki / gui / cacheview / forms.py View on Github external
try:
                resource_range_as.parse_str(asn)
            except ValueError:
                raise forms.ValidationError('invalid AS range')

        if addr:
            #try:
            parse_ipaddr(addr)
            #except BadIPResource:
            #    raise forms.ValidationError('invalid IP address range/prefix')

        return self.cleaned_data


class SearchForm2(forms.Form):
    resource = forms.CharField(required=True)
github 8planes / mirosubs / apps / videos / forms.py View on Github external
return language
    
class UserTestResultForm(forms.ModelForm):
    
    class Meta:
        model = UserTestResult
        exclude = ('browser',)
        
    def save(self, request):
        obj = super(UserTestResultForm, self).save(False)
        obj.browser = request.META.get('HTTP_USER_AGENT', 'empty HTTP_USER_AGENT')
        obj.save()
        return obj

class VideoForm(forms.Form):
    video_url = forms.URLField(verify_exists=True)
    
    def __init__(self, user=None, *args, **kwargs):
        if user and not user.is_authenticated():
            user = None
        self.user = user
        super(VideoForm, self).__init__(*args, **kwargs)
        self.fields['video_url'].widget.attrs['class'] = 'main_video_form_field'
    
    def clean_video_url(self):
        video_url = self.cleaned_data['video_url']
        
        if video_url:
            try:
                video_type = video_type_registrar.video_type_for_url(video_url)
            except VideoTypeError, e:
                raise forms.ValidationError(e)
github nocproject / noc / ip / apps / reportallocated / views.py View on Github external
## Copyright (C) 2007-2010 The NOC Project
## See LICENSE for details
##----------------------------------------------------------------------

# Django Modules
from django.utils.translation import ugettext_lazy as _
from django import forms
from django.db.models import Q
# NOC Modules
from noc.lib.app.simplereport import SimpleReport, TableColumn
from noc.lib.validators import *
from noc.ip.models import VRF, Prefix
from noc.main.models import CustomField


class ReportForm(forms.Form):
    """
    Report form
    """
    vrf = forms.ModelChoiceField(
        label=_("VRF"),
        queryset=VRF.objects.filter(
            state__is_provisioned=True).order_by("name"))
    afi = forms.ChoiceField(label=_("Address Family"),
                            choices=[("4", _("IPv4")), ("6", _("IPv6"))])
    prefix = forms.CharField(label=_("Prefix"))

    def clean_prefix(self):
        vrf = self.cleaned_data["vrf"]
        afi = self.cleaned_data["afi"]
        prefix = self.cleaned_data.get("prefix", "").strip()
        if afi == "4":
github tlambert03 / FPbase / proteins / forms / microscope.py View on Github external
)
                    else:
                        if isinstance(f, list):
                            _out.append([lookup(x, n) for x in f])
                        else:
                            _out.append(lookup(f, n))
                cleaned.append(_out)
            except Exception:
                self.add_error(
                    "optical_configs",
                    "Uknown error parsing line #{}: {}".format(linenum + 1, line),
                )
        return cleaned


class MultipleFilterField(forms.ModelMultipleChoiceField):
    def __init__(self, label):
        super().__init__(
            label=label,
            queryset=Filter.objects.all(),
            required=False,
            widget=autocomplete.ModelSelect2Multiple(
                url="proteins:filter-autocomplete",
                attrs={
                    "data-theme": "bootstrap",
                    "data-width": "100%",
                    "data-placeholder": "----------",
                },
            ),
        )
github matthiask / django-cabinet / cabinet / base_admin.py View on Github external
def __init__(self, *args, **kwargs):
        super().__init__(*args, **kwargs)
        if self.instance.pk:
            self.fields["_delete_folder"] = forms.BooleanField(
                required=False, label=_("Delete this folder")
            )
github robogals / myrobogals / myrobogals / auth / forms.py View on Github external
from myrobogals.auth.models import User
from myrobogals.auth import authenticate
from myrobogals.auth.tokens import default_token_generator
from django.contrib.sites.models import Site
from django.template import Context, loader
from django import forms
from django.utils.translation import ugettext_lazy as _
from django.utils.http import int_to_base36
from myrobogals.rgmessages.models import EmailMessage, EmailRecipient


class UserCreationForm(forms.ModelForm):
    """
    A form that creates a user, with no privileges, from the given username and password.
    """
    username = forms.RegexField(label=_("Username"), max_length=30, regex=r'^\w+$',
        help_text = _("Required. 30 characters or fewer. Alphanumeric characters only (letters, digits and underscores)."),
        error_message = _("This value must contain only letters, numbers and underscores."))
    password1 = forms.CharField(label=_("Password"), widget=forms.PasswordInput)
    password2 = forms.CharField(label=_("Password confirmation"), widget=forms.PasswordInput)

    class Meta:
        model = User
        fields = ("username",)

    def clean_username(self):
        username = self.cleaned_data["username"]
        try: