class

http://www.adilwaseem.com/

Definition
The class is method which can execute any operation defined within it.

Syntax
class Name(): arguments

Example

Through the QuerySet, the db is diplay through view.py. Only latest object is query in this this example.

mysite/settings
INSTALLED_APPS = (
    'django.contrib.admin',
    'django.contrib.auth',
    'django.contrib.contenttypes',
    'django.contrib.sessions',
    'django.contrib.messages',
    'django.contrib.staticfiles', 'myapp', 
)

models.py

from django.db import models

class ModelUrl(models.Model):
    url=models.URLField()

    def __str__(self):
        return self.url

myapp/views.py

from .models import ModelUrl
def URL_List(request):
    model = ModelUrl
    context_object_name = 'Url'
    url=ModelUrl.objects.latest('id')
    string=str(url)
    return HttpResponse(string)

mysite/ulrs.py

from django.conf.urls import include, url

from myapp.views import URL_List

urlpatterns = [
    url(r'^', URL_List),
]

python manage.py runserver

 




The registration form is created using models in which user is allowed to register for news letter. model.py fields are import into the forms.py using class Meta.

Window CMD  commands 

  • virtualenv pythonlake
  • cd  pythonlake
  • .\Scripts\activate
  • pip install django
  • python .\Scripts\django-admin.py startproject mysite
  • cd mysite
  • python manage.py startapp myapp
  • python manage.py syncdb
  • python manage.py runserver

Files


mysite/settings.py

INSTALLED_APPS = (
    'django.contrib.admin',
    'django.contrib.auth',
    'django.contrib.contenttypes',
    'django.contrib.sessions',
    'django.contrib.messages',
    'django.contrib.staticfiles','myapp',
) 

mysite/urls.py

from django.contrib import admin
admin.autodiscover()
from myapp.views import Register, Response

urlpatterns = patterns('',
    # Examples:
    url(r'^$', Register),
     url(r'^thanks/$', Response),

    url(r'^admin/', include(admin.site.urls)),
)

myapp/admin.py

from django.contrib import admin

from .models import Reg

    class Meta:
        model=Reg

admin.site.register(Reg,RegAdmin)

myapp/models.py

from django.db import models
class Reg(models.Model):
    first_name=models.CharField(max_length=100)
    last_name=models.CharField(max_length=100)
    email=models.EmailField()
    

myapp/forms

from django import forms
from .models import Reg

class RegForm(forms.ModelForm):
    class Meta:
        model=Reg

myapp/views.py

from django.shortcuts import render
from .forms import RegForm
from django.http import HttpResponse

def Register(request):

    form=RegForm(request.POST)
    if form.is_valid():
        save_form=form.save(commit=False)
        save_form.save()
        return HttpResponseRedirect('/thanks/')
    else:
        form=RegForm()

    return render(request, 'myapp\index.html', {'form':form})

def Response(request):
    return HttpResponse('Thanks for registering with us')

myapp/index.html

<!DOCTYPE html>
<html>
<head lang="en">
    <meta charset="UTF-8">
    <title></title>
</head>
<body>

<h1> Register for latest news</h1>

<form  action="" method="post">

    {%csrf_token%}

    {{form.as_p}}

    <input type="submit">

</form>

</body>
</html>









URLField is created through models and  viewed through index.html. 

Window CMD  commands 

  • virtualenv djangoschool
  • cd  djangoschool
  • .\Scripts\activate
  • pip install django
  • python .\Scripts\django-admin.py startproject mysite
  • cd mysite
  • python manage.py startapp myapp
  • python manage.py syncdb
  • python manage.py runserver




mysite/setting.py

INSTALLED_APPS = (
    'django.contrib.admin',
    'django.contrib.auth',
    'django.contrib.contenttypes',
    'django.contrib.sessions',
    'django.contrib.messages',
    'django.contrib.staticfiles', 'myapp',
)

mysite/urls.py

from django.conf.urls import include, url

from myapp.views import ViewUrl
urlpatterns = [
    url(r'^', ViewUrl)
]


myapp/models.py

from django.db import models

class ModelUrl(models.Model):
    url=models.URLField()

    def __str__(self):
        return self.url


myapp/forms.py

from django import forms
from .models import ModelUrl

class FormUrl(forms.ModelForm):
    class Meta:
        model=ModelUrl
        fields=['url']


myapp/views.py

from django.shortcuts import render

from django.shortcuts import HttpResponseRedirectHttpResponse
from .forms import FormUrl

def ViewUrl(request):
    form=FormUrl(request.POST)
    if form.is_valid():
        form.save(commit=False)
        form.save()
        return HttpResponseRedirect('/thanks/')
    else:
        form=FormUrl
    return render(request, 'myapp/index.html',{'form':form})

def response(request):
    return HttpResponse("Thanks")

myapp/index.html

<!DOCTYPE html>
<html>
<head lang="en">
    <meta charset="UTF-8">
    <title></title>
</head>
<body>

<form  action="/thanks/" method="post">

    {%csrf_token%}

    {{form}}

    <input type="submit">

</form>

</body>
</html>

Localhost:8000



Database Query






Examples
Here in this example, the CharField  is used to store the data into the field.  The data is recorded and saved in models.py and retrieved and displayed through the views.py. 
 Steps for creating virtual environment, startproject, startapp, creating database, and migrating the data, and running server to check the app.
  • virtualenenv djangoschool
  • cd djangoschool
  • .\Scripts\activate
  • pip install django
  • python .\Scripts\django-admin.py startproject mysite
  • python manage.py migrate
  • python manage.py startapp dbapp
  • python manage.py makemigrations dbapp


mysite/settings,py

INSTALLED_APPS = (
    'django.contrib.admin',
    'django.contrib.auth',
    'django.contrib.contenttypes',
    'django.contrib.sessions',
    'django.contrib.messages',
    'django.contrib.staticfiles','dbapp',
)

mysite/urls.py

from django.conf.urls import include, url

from dbapp.views import Display

urlpatterns = [
    url(r'^', Display),
]

dbapp/models.py


    groups=(('male','0-40'),('female','0-40'))
    genderfield=models.CharField(max_length=50,choices=groups)

v=LongLife(genderfield="Casey")
v.save()

dbapp/views.py



from . models import LongLife

def Display (request):
    return HttpResponse(LongLife.objects.filter(genderfield="Casey").values())









Here, in this example, the IntegerField validated number entered should be in record and before the Field vale is passed on HttpResponseRedirect in views.py and index.html files.
Steps for creating virtual environment, startproject, startapps, & running server:
  • virtualenv myvirtualenv
  • cd  mysite
  • .\Scripts\activate
  • pip install django
  • python .\Scripts\django-admin.py startproject mysite
  • cd mysite
  • python manage.py startapp myapphttp
  • python manage.py runserver 



setting.py

INSTALLED_APPS = (
    'django.contrib.admin',
    'django.contrib.auth',
    'django.contrib.contenttypes',
    'django.contrib.sessions',
    'django.contrib.messages',
    'django.contrib.staticfiles','myapphttp',
)

urls.py

from django.conf.urls import include, url

from myapphttp.views import response

urlpatterns = [
      url(r'^', response),
]

myapphttp/forms.py

from django import forms



def Validate(value):
    pin=[1101,2945,3635,5550,3334,5553,2822,4624,3221,6453,2223,4456,5462]
    if value not in pin:
        raise ValidationError('%s : The pin number is not in our record.'% value)

class IntegerField(forms.Form):
    number=forms.IntegerField(label='Number' ,validators=[Validate])

myapphttp/views.py

from django.shortcuts import render

from .forms import IntegerField

def response(request):
    if request.method == 'POST':
        form=IntegerField(request.POST)
        if form.is_valid():
            return HttpResponseRedirect('/Thanks-for-submitting-your-request/')
    else:
        form = IntegerField()

    return render(request, 'myapphttp\index.html', {'form':form})


myapphttp/index.html

<!DOCTYPE html>
<html>
<title> </title>
<body>

<form action="/pin-not-found/" method="post">
    {% csrf_token %}
    {{ form }}
    <input type="submit" value="Submit" />
</form>

</body>
</html>






The class executed the loop inheriting the values from the class url.
 
class url():
    x=10
    y=15

class loop(url):
    y=3
    if y==3:
        for i in range(0,url.x):
            print(i)
            if i==9:
                print("Start of h loop")
            
        for h in range(0,url.y):
            print(h)

>>> 
0
1
2
3
4
5
6
7
8
9
Start of h loop
0
1
2
3
4
5
6
7
8
9
10
11
12
13
14
>>> 


The function find the number of vowels in the name through input() through str.count().
 class string_methods:
    def __init__(self,a,b):

         
        va=a.count("a")
        ve=a.count("e")
        vi=a.count("i")
        vo=a.count("o")
        vu=a.count("u")
        

        count_a=va+ve+vi+vo+vu

        print("Total vowels in your first name are:",count_a) 

        va=b.count("a")
        ve=b.count("e")
        vi=b.count("i")
        vo=b.count("o")
        vu=b.count("u")
        

        count_b=va+ve+vi+vo+vu

        print("Total vowels  in your last name :",count_b)


        print("Total vowels in your full name:", count_a+count_b)
        
        
first_name=input("Please enter your first name: ")
second_name=input("Please enter your second name: ")


string_methods(first_name,second_name)


>>> 
Please enter your first name: adil
Please enter your second name: waseem
Total vowels in your first name are: 2
Total vowels in your last name : 3
Total vowels in your full name: 5
>>>


class....: def....: str.find()...str.count
The function allow the user to find word in their text.
 class method_text_finder():
    def __init__(self, a,b):

        self.a=str(a)
        find1=a.find(b)
        print("The word found in your text at position:",find1+1)

        count1=a.count(b)
        print("The total word found in your text:",count1)

text=input("Please enter your text: ")
find_word=input("Please enter your text:")

method_text_finder(text,find_word)

>>> 
Please enter your text: Python Research Centre is located at Woodbridge Va
Please enter your text:Woodbridge
The word found in your text at position: 38
The total word found in your text: 1
>>> 

class.....: def......:....str.isidentifier().....str.lower()....str.isapha()
The function tested whether the string value is single word, or contain non-string values through input().
 class str_methods():
    def __init__(self, a,b,c):

        identifier=str.isidentifier(a)

        if str.isidentifier(a).__eq__(True):
            print("Full name should not contain special characters or numbers")
            
        else:
            print("Your full not name accepted")

        
      
        alpha=str.isalpha(b)
        
        if alpha.__ne__(False):
            print("Full name accepted")

            lower=str.lower(c)
            if lower.__eq__(str.lower(c)):
                 str.upper(c)
                 print("System convert your name to uppercase:", str.upper(c))
            else:
                 print("Your name accepted")

        else:
            print("Full name can't be one word")

                    

input_text=input("Please enter  your full name: ")

str_methods(input_text, input_text,input_text)
    
          

>>> 
Please enter your full name: Adil22
Full name should not contain special characters or numbers
Full name can't be one word
>>>        


The method return with the value of box.
 class box:
    def __init__(self, h, w):
        self.x = h
        self.y = w
z = box(3.0, -4.5)
z.x*z.y
print(z.x*z.y)

>>> 
-13.5
>>> 

The method return with the value of box.
 class box:
    def __init__(self, h, w):
        self.x = h
        self.y = w
z = box(3.0, -4.5)
z.x*z.y
print(z.x*z.y)

>>> 
-13.5
>>> 


The method return with the round() value of the parameter.
class round_value:
    def __init__(self,a):
        self.x = round(a)
        
value=33.22
z=round_value(value)
output=z.x

print(output)

>>> 
33
>>> 


class...if statement
The class method executed the if statement.
import operator
class add_value:
    def __init__(self, a):
        self.a=a
        if self.a==float(a):
            print("The value:",self.a, ",is float:")
        else:
            print("Value accepted: ", self.a)
                  
                
value=3.134

add_value(value)

>>> 
The value: 3.134 ,is float:
>>>

class method executed the if statement about accumulated value of value1 and value2.
 import operator
class add_value:
    def __init__(self,a,b):
        self.a=a
        self.b=b
        self.c=a+b
        if self.c.__lt__(20):
            print("The values added are more than required parameters:",self.c)
        else:
            print("Values added: ", self.c)
                  
                
value1=33
value2=33.1

add_value(value1, value2)

>>> 
Values accepted: 66.1
>>>

The class method return the complex values and tested the equality of the values.
 class complex_value:
    def __init__(self, a,b,c):

        self.a=complex(a).conjugate()
        self.b=complex(b).imag
        self.c=complex(c).real

        print("The comlex conjugate value of a is: ",self.a)
        print("The complex imag value of b is: ",self.b)
        print("The complex  real value of c is: ",self.c)
        
        if self.a.__eq__(complex(a).conjugate()):
            print("The value of a is equal to complex(a) conjugate")
        else:
             print("The value of a is NOT equal to complex(a) conjugate")
            

        if self.b.__eq__(complex(b).imag):
            print("The value of b is equal to complex(b) imag")
        else:
            print("The value of b is NOT equal to complex(b) imag")


        if self.c.__eq__(complex(c).real):
            print("The value of c is equal to complex(c) imag")
        else:
            print("The value of c is NOT equal to complex(c) imag")

           
value1=81
value2=222
value3=33
complex_value(value1,value2, value3)

>>> 
The comlex conjugate value of a is: (81-0j)
The complex imag value of b is: 0.0
The complex real value of c is: 33.0
The value of a is equal to complex(a) conjugate
The value of b is equal to complex(b) imag
The value of c is equal to complex(c) imag
>>>


class...: def:.....:str.capitalize()
The class return after capitalizing the strings.
 class string_capitalize:
    def __init__(self,a,b):
          print(str.upper(a), str.upper(b))

        
x="python"
y="lake"

string_capitalize(x,y)



>>> 
Python Lake
>>> 

There simple mainloop widget(). 
import tkinter
class maintloop1():
    def __init__(self,a):
        self.a=a
        a.mainloop()

x=tkinter.Tk()
maintloop1(x)




Comments