Ticket #1703: forms.txt.2.diff

File forms.txt.2.diff, 8.6 KB (added by Malcolm Tredinnick <malcolm@…>, 18 years ago)

Updated patch to work after Adrian's changes in [2765]

  • docs/forms.txt

     
    5353
    5454    >>> from mysite.myapp.models import Place
    5555    >>> Place.AddManipulator
    56     <class Place.ManipulatorAdd at 0x4c1540>
     56    <class 'django.models.manipulators.AddManipulator'>
    5757    >>> Place.ChangeManipulator
    58     <class Place.ManipulatorChange at 0x4c1630>
     58    <class 'django.models.manipulators.ChangeManipulator'>
    5959
    6060Using the ``AddManipulator``
    6161----------------------------
     
    6565
    6666    from django.shortcuts import render_to_response
    6767    from django.http import Http404, HttpResponse, HttpResponseRedirect
     68    from django import forms
    6869    from mysite.myapp.models import Place
    69     from django import forms
    7070
    7171    def naive_create_place(request):
    7272        """A naive approach to creating places; don't actually use this!"""
     
    162162        if errors:
    163163            return render_to_response('places/errors.html', {'errors': errors})
    164164        else:
    165             manipulator.do_html2python(request.POST)
    166             new_place = manipulator.save(request.POST)
     165            manipulator.do_html2python(new_data)
     166            new_place = manipulator.save(new_data)
    167167            return HttpResponse("Place created: %s" % new_place)
    168168
    169169In this new version, errors will be found -- ``manipulator.get_validation_errors``
     
    198198both be available on the same page, so errors with fields can be presented in
    199199context.
    200200
    201 .. admonition:: Philosophy::
     201.. admonition:: Philosophy:
    202202
    203203    Finally, for the HTTP purists in the audience (and the authorship), this
    204204    nicely matches the "true" meanings of HTTP GET and HTTP POST: GET fetches
     
    408408One useful feature of manipulators is the automatic validation. Validation is
    409409done using a simple validation API: A validator is a callable that raises a
    410410``ValidationError`` if there's something wrong with the data.
    411 ``django.core.validators`` defines a host of validator functions, but defining
    412 your own couldn't be easier::
     411``django.core.validators`` defines a host of validator functions (see below),
     412but defining your own couldn't be easier::
    413413
    414414    from django.core import validators
    415415    from django import forms
     
    431431
    432432The arguments to a validator function take a little explanation.  ``field_data``
    433433is the value of the field in question, and ``all_data`` is a dictionary of all
    434 the data being validated.  Note that at the point validators are called all
    435 data will still be strings (as ``do_html2python`` hasn't been called yet).
     434the data being validated.
    436435
     436.. admonition:: Note::
     437
     438    At the point validators are called all data will still be
     439    strings (as ``do_html2python`` hasn't been called yet).
     440
    437441Also, because consistency in user interfaces is important, we strongly urge you
    438442to put punctuation at the end of your validation messages.
    439443
     444Ready-made Validators
     445---------------------
     446
     447Writing your own validator is not difficult, but there are some situations
     448that come up over and over again. Django comes with a number of validators
     449that can be used directly in your code. All of these functions and classes
     450reside in ``django/core/validators.py``.
     451
     452The following validators should all be self-explanatory. Each one provides a
     453check for the given property:
     454
     455    * isAlphaNumeric
     456    * isAlphaNumericURL
     457    * isSlug
     458    * isLowerCase
     459    * isUpperCase
     460    * isCommaSeparatedIntegerList
     461    * isCommaSeparatedEmailList
     462    * isValidIPAddress4
     463    * isNotEmpty
     464    * isOnlyDigits
     465    * isNotOnlyDigits
     466    * isInteger
     467    * isOnlyLetters
     468    * isValidANSIDate
     469    * isValidANSITime
     470    * isValidEmail
     471    * isValidImage
     472    * isValidImageURL
     473    * isValidPhone
     474    * isValidQuicktimeVideoURL
     475    * isValidURL
     476    * isValidHTML
     477    * isWellFormedXml
     478    * isWellFormedXmlFragment
     479    * isExistingURL
     480    * isValidUSState
     481    * hasNoProfanities
     482
     483There are also a group of validators that are slightly more flexible. For
     484these validators, you create a validator instance, passing in the parameters
     485described below. The returned object is a callable that can be used as a
     486validator.
     487
     488For example::
     489
     490    from django.core import validators
     491    from django import forms
     492
     493    power_validator = validators.IsAPowerOf(2)
     494
     495    class InstallationManipulator(forms.Manipulator)
     496        def __init__(self):
     497            self.fields = (
     498                ...
     499                forms.IntegerField(field_name = "size",i
     500                        validator_list=[power_validator])
     501            )
     502
     503Here, ``validators.IsAPowerOf(...)`` returned something that could be used as
     504a validator (in this case, a check that a number was a power of 2).
     505
     506Each of the standard validators that take parameters have an optional final
     507argument (``error_message``) that is the message returned when validation
     508fails. If no message is passed in, a default message is used.
     509
     510``AlwaysMatchesOtherField``
     511    Takes a field name and the current field is valid if and only if its value
     512    matches the contents of the other field.
     513
     514``ValidateIfOtherFieldEquals``
     515    Takes three parameters: ``other_field``, ``other_value`` and
     516    ``validator_list``, in that order. If ``other_field`` has a value of
     517    ``other_vaue``, then the validators in ``validator_list`` are all run
     518    against the current field.
     519
     520``RequiredIfOtherFieldNotGiven``
     521    Takes the name of the other field and this field is only required if the
     522    other field has no value.
     523
     524``RequiredIfOtherFieldsNotGiven``
     525    Similar to ``RequiredIfOtherFieldNotGiven``, except that it takes a list
     526    of field names and if any one of the supplied fields does not have a value
     527    provided, the field being validated is required.
     528
     529``RequiredIfOtherFieldEquals`` and ``RequiredIfOtherFieldDoesNotEqual``
     530    Each of these validator classes takes a field name and a value (in that
     531    order). If the given field does (or does not have, in the latter case) the
     532    given value, then the current field being validated is required.
     533
     534    Note that because validators are called before any ``do_html2python()``
     535    functions, the value being compared against is a string. So
     536    ``RequiredIfOtherFieldEquals('choice', '1')`` is correct, whilst
     537    ``RequiredIfOtherFieldEquals('choice', 1)`` will never result in the
     538    equality test succeeding.
     539
     540``IsLessThanOtherField``
     541    Takes a field name and validates that the current field being validated
     542    has a value that is less than (or equal to) the other field's value.
     543    Again, comparisons are done using strings, so be cautious about using
     544    this function to compare data that should be treated as another type. The
     545    string "123" is less than the string "2", for example. If you don't want
     546    string comparison here, you will need to write your own validator.
     547
     548``IsAPowerOf``
     549    Takes an integer argument and when called as a validator, checks that the
     550    field being validated is a power of the integer.
     551
     552``IsValidFloat``
     553    Takes a maximum number of digits and number of decimal places (in that
     554    order) and validates whether the field is a float with less than the
     555    maximum number of digits and decimal place.
     556
     557``MatchesRegularExpression``
     558    Takes a regular expression (a string) as a parameter and validates the
     559    field value against it.
     560
     561``AnyValidator``
     562    Takes a list of validators as a parameter. At validation time, if the
     563    field successfully validates against any one of the validators, it passes
     564    validation. The validators are tested in the order specified in the
     565    original list.
     566
     567``URLMimeTypeCheck``
     568    Used to validate URL fields. Takes a list of MIME types (such as
     569    ``text/plain``) at creation time. At validation time, it verifies that the
     570    field is indeed a URL and then tries to retrieve the content at the URL.
     571    Validation succeeds if the content could be retrieved and it has a content
     572    type from the list used to create the validator.
     573
     574``RelaxNGCompact``
     575    Used to validate an XML document against a Relax NG compact schema. Takes
     576    a file path to the location of the schema and an optional root element
     577    (which is wrapped around the XML fragment before validation, if supplied).
     578    At validation time, the XML fragment is validated against the schema using
     579    the executable specified in the ``JING_PATH`` setting (see the settings_
     580    document for more details).
     581
    440582.. _`generic views`: http://www.djangoproject.com/documentation/generic_views/
     583.. _`models API`: http://www.djangoproject.com/documentation/model_api/
     584.. _settings: http://www.djangoproject.com/documentation/settings/
Back to Top