3
\$\begingroup\$

i've just started to learn python /django .. im coming from php world ...i mostly struggle with None values which are new to me .. in php i mostly did my boll checking with true/false but in python None is favored .. .also collections (list , dictionary) are different here but javascript has prepped me for that !

anyway i've decided to write my own form validation code , i know django has something built in but i like to write my own to have better understanding of python

so here it goes :

def edit(request , errors = False , default = False  ):

    if default == False :
        try:
           account =  Accounts.objects.get(user=request.user.id)
        except Accounts.DoesNotExist :
            account = False
    else :
        account = default
    return render(request , 'account/edit.html' , {'cuAcc':account , 'errors':errors})

which renders this simple view :

{%  extends 'master-account.html' %}
{%  block main %}
    <form method="post" action="{%  url 'account-update' %}">
        {%  csrf_token %}

        {% if errors %}
         <ul>
          {%  for e in errors %}
           <li>  {{ e }} </li>
          {%  endfor %}
         </ul>
        {% endif %}

        <label>name </label>
        <input type="text"  name="name" value="{{cuAcc.name}}">
        <label> last name  </label>
        <input type="text"  name="lastname" value="{{cuAcc.lastname}}">
        <label> phone number   </label>
        <input type="text"  name="phone" value="{{cuAcc.phone}}">
        <label> mobile number  </label>
        <input type="text"  name="mobile" value="{{cuAcc.mobile}}">
        <label> address   </label>
        <input type="text"  name="address" value="{{cuAcc.address}}">
        <button type="submit" class="btn btn-success">edit</button>
      </form>
{% endblock %}

my update function :

def update(request):

    VALIDATIONRULES = {

        'name':{'title':'Name' ,
                 'rule':{'required':True}} ,
         'lastname':{'title':'Last name',
                     'rule':{'required':True}} ,
         'phone':{'title':'Phone number',
                  'rule':{'required':True , 'numeric':{} , 'lenmax':9 , 'lenmin':6 }} ,
         'mobile':{'title':'Mobile',
                   'rule':{'required':True , 'numeric':{} , 'lenexact':11 }} ,
     }


    data , errors   = validation(request , VALIDATIONRULES )

    if not errors:
         return HttpResponse(' the form is valid ')
    else :
        print("errors ---------------- >>>")
        return edit(request , errors , data )

and finally my validation function which i'm going to put in a separate app

def validation(request , VALIDATIONRULES):

    errors = []
    whitelist=  {}

    for k,v in VALIDATIONRULES.items():
        check  = request.POST.get(k, None)
        rule   = VALIDATIONRULES[k]['rule']
        title  = VALIDATIONRULES[k]['title']
        thiserror = None
        if check is None or check == '':
            if 'required' in rule  :
                errors.append("pleas enter the " + title )
                thiserror = True
        else :
            if 'numeric' in rule:
                if  check.isnumeric():

                    intcheck = int(check)
                    if 'max' in rule['numeric'] and intcheck > rule['numeric']['max'] :
                        errors.append(  title + ' should be smaller than  ' + str(rule['numeric']['max'] ))
                        thiserror = True
                    if 'min' in rule['numeric'] and intcheck < rule['numeric']['min'] :
                        errors.append(  title + ' should be bigger  than ' + str(rule['numeric']['min']))
                        thiserror = True

                else :
                     errors.append(  title + ' should be numeric ! ' )
                     thiserror = True

            if 'lenmax' in rule and len(str(check)) > rule['lenmax'] :
                errors.append(  title + ' length should be less than  ' + str(rule['lenmax'] ))
                thiserror = True

            if 'lenmin' in rule and len(str(check)) < rule['lenmin'] :
                errors.append(  title + ' length should be bigger than  ' + str(rule['lenmin'] ))
                thiserror = True

            if 'lenexact' in rule and len(str(check)) != rule['lenexact'] :
                errors.append(  title + ' length should be exactly  ' + str(rule['lenexact']))
                thiserror = True

            if 'email' in rule  :
                try:
                    validate_email(check)
                except :
                    errors.append(  title + ' is not a valid email   ' )
                    thiserror = True


        if(  check is not None and thiserror is None ):
            whitelist[k] = check

    return whitelist , errors

as i said i'm just starting to learn and i'm not quite comfortable with python yet , so i appreciate any suggestion

\$\endgroup\$

1 Answer 1

1
\$\begingroup\$

anyway i've decided to write my own form validation code , i know django has something built in but i like to write my own to have better understanding of python

If you want to improve your understanding of Python, I suggest to follow the official Python tutorial. In that case, don't dove into Django just yet.

If you want to improve your understanding of Django, then it's really best to follow the official Django tutorial, and use Django's built-in elements.

Following these tutorials is really the smart and time efficient way to learn. This training might not be true for all languages and frameworks, but for Python and Django I assure you it is.


Instead of this:

if default == False :

The correct way to write is this:

if not default:

And when the account is not found, instead of setting:

account = False

It would be better to set it to None.

Related to this, I recommend to read PEP8, the official Python style guide. It's more than just formatting. It explains many things about the philosophy of pythonic programming.

\$\endgroup\$
2
  • \$\begingroup\$ thanx , i'll definitl going to read PEP8 ... so if not default: works for bot none and false ? whats wrong with if default == False ? \$\endgroup\$
    – max
    May 26, 2016 at 21:46
  • \$\begingroup\$ Yes, if not default: will be true for both False and None values of default. That's because None is falsy, and btw so is 0. The problem with default == False is that it's not natural in Python. not default is natural. It's also shorter. Although default == False works, it's good to have a strong recommendation of one way, to guide all programmers to code the same way, so that they all see familiar code, which is easier to read and understand. \$\endgroup\$
    – janos
    May 26, 2016 at 21:58

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Not the answer you're looking for? Browse other questions tagged or ask your own question.