Sunteți pe pagina 1din 62

Python Preparation

MOD

7%3=4

2**3=8

type(a) ##shows type of variable

String

print(“hello \n World”)

result:

hello

World

print(“hellow \t world”)

Result:

Hellow world

len(“I am”)
Reuslt:

Syntax of string

[start:stop:step]

a[2:3:4] # in this example it will start to count from 2 till 3 and jumping 4

a=”Hi Kamran”

print(a[2:]) ##shows from 2 till end

Result: Kamran

a[::] ##shows everything

a[::2] ## it will jump from every 2 character

'H arn'

a[::-1] ## changes the string to the reverse

'narmaK iH’

Input and format

Input(“bir sayi girin”) Input almaq ucun isdifade edilir

print("{} {} {}".format("Salam","Kamran","Necesen"))

Result:Salam Kamran Necesen

print("{0} {0} {0}".format("Salam","Kamran","Necesen"))

Result:Salam Salam Salam

print("{s} {n} {k}".format(s="salam", k="Kamran", n="Necesen"))

Result: salam Necesen Kamran

result=101.214

print("{r:1.2f}".format(r=result))

101.21
name="Xose"

>>> print(f'his name is {name}')

his name is Xose

>>>

List in Python

my_list=[1,2,3,4]

my_list1=[5,6,7,8]

my_list+mylist1=[1.2.3.4.5.6.7.8]

list(range(0,10,2) ##shows all even numbers

-------------

my_list[0]=999

result: my_list=[999.2.3.4]

------------

my_list.append(121)

result: my_list=[999, 2, 3, 4, 'List', 121]

---------------

my_list.pop() ##removes last character in list

result: my_list=[999, 2, 3, 4, 'List']

my_list.pop(0)

result:my_list=[2,3,4,’List’]

------------------

my_file=['d','t','b','a','k']

>>> my_file.sort()

>>> my_file

['a', 'b', 'd', 'k', 't']

---------------------

my_list=[1,4,2,3]

my_list.reverse()
Result: 4.3.2.1

Dictionary in python

prices={'orange':2.25,'banana':1.23,'grape':2.01}

>>> prices

{'orange': 2.25, 'banana': 1.23, 'grape': 2.01}

>>> prices[‘banana’]

1.23

We can insert list and other dictionary inside one dictionary

prices

{'orange': 2.25, 'banana': 1.23, 'grape': 2.01}

>>> prices["banana"]

1.23

>>>

>>> prices1={'k1':[0,2,3,4]}

>>> prices1

{'k1': [0, 2, 3, 4]}

>>> prices1['k1'][1]

2
prices1={'k1':[0,2,3,4],'k2':{'insideKey':100}}
print(prices1['k2']['insideKey'])

prices1={'k1':[0,2,3,4],'k2':{'insideKey':100},'k3':['a','b','c']}
print(prices1['k2']['insideKey'])
print(prices1['k3'][2].upper())
C

>>> prices1.keys()

dict_keys(['k1', 'k3', 'k2']) (shows key values of dictionary)

------------------------------

>>> prices.values()

dict_values([2.25, 1.23, 2.01]) (Shows values of dic)

-----------------------

>>> prices.items()

dict_items([('orange', 2.25), ('banana', 1.23), ('grape', 2.01)]) (shows all dic tree)

>>>

Tulpe (it does not support reassignmnent)

t=('a','b',1,2,3,4)

print(type(t))

Result: <class 'tuple'>

------------------

print(t[0])

Result:a

SET in python. In set all elemnts must be unique and one character can be added at one time

st=set()

st.add(1)

Result: {1}

Booleans

It has value True False and None


Working with files:

myfile=open('myfile.txt')

myexcellfile=open('Gi_SGi_20200320_152800.csv')

print(myexcellfile.read()) (it will show all file context)

print(myfile.read()) (it will show all file context)

When we want to read the file for the second time, need to seek the cursor at the begging of
the line

myfile.seek(0)

print(myfile.read())

--------------------

myexcellfile.readlines() (is used to read file line by line)

print(myexcellfile.readlines())

------------------------------

myfile.close() ( its used to close the file)


In windows 10, it works like this

mytestfile=open("C:/Users/k80044720/Desktop/x.txt")

we can open the file as briefly and later no need to close it back

with open('myfile.txt') as mynewfile:

context=mynewfile.read()

print(context)

-------------------------------

with open ('myfile.txt', mode='r') as f:

context=f.read()

print(context)
with open('myfile.txt', mode='a') as f:

f.write('Hello papa almanyadan geldi saban')

Comparation operators

2==2 and ‘hello’=’xhello’

2==2 and ‘hello’=’xhello’

not 2==2

Statements in python
if loc=="Auto Shop" :

print(" i love cars")

elif loc=="Shops" :

print("Welcome to our shop")

elif loc=="Supermarket" :
print("Supermarjet is cool!")

else:

print("i dont know much")

Loops in Pyhton

mylist=[1,2,3,4,5,6,7,8,9,10]

for num in mylist:

if num % 2 == 0:

print(f'Even Number: {num}')

else:

print(f' Odd Number: {num}')


for number in mylist:

print("Hello the world ")

mylist1=[(1,2), (3,4), (5,6), (7,8), (9,10)]

for a,b in mylist1:

print(a)

print(b)

dic={'k1':1,'k2':2,'k3':3,'k4':4}

for key,value in dic.items():

print(key,":",value)

While in Python
x=0.0

print(type(x))

while x<=5:

if x!=3:

print(f'X number is: {x}')

x=x+1

else:

x=x+1

else:

print("count is stopped")

-----------------------------

mylist=[1,2,3,4,5]

for num in range(5, 10):

print(f'{num}')

Result:

------------------------

for num in range(5, 10,2):

print(f'{num}')
Result:

----------------------------

Generate numbers

x=list(range(0,10,1))

print(x)

Result: [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]

---------------------------

for item,index in enumerate(word):

print(item,"-:-",index)

Result:

0 -:- a

1 -:- b

2 -:- c

3 -:- d

4 -:- e

5 -:- f

6 -:- g

7 -:- h

8 -:- l

-------------------------------

If we have multiple lists, we can cast them with zip function

list1=[1,2,3,]

list2=['a','b','c']

list3=[100,200,300]

for item in zip(list1,list2,list3):

print(item)
Result:

(1, 'a', 100)

(2, 'b', 200)

(3, 'c', 300)

Another example which shows zip is used to cast lists as tuples

x= list(zip(list1,list2,list3))

print(x)

Result:

[(1, 'a', 100), (2, 'b', 200), (3, 'c', 300)]

-----------------------------------

Great method of checking if the letter exist in list, dictionaries and for others

word='abcdefghlmnopqrstwxzaaa'

if 'y' in word:

print("the letter exist")

else:

print("the letter does not exist:")

-----------------------------------

We can find minimum and max number in the list

min(list4)

max(list4)

---------------------------------------

One of the most important topic is to import library

Firstly lets import python built in library. In this example we imported shuffle library

from random import shuffle

list1=[1,2,3,4,5,6,7,8,9,10]

shuffle(list1)

print(list1)

-----------------------------------------

(
string1='hello'

list1=[]

for letter in string1:

list1.append(letter)

Is the same as this

string1='hello'

list1=[letter for letter in string1]

list2=[num**2 for num in range(0,100) if num%2==0 and num%4==0]

print(list2)

celcius=[50,100,30.40,12,3.5,10]

faranheyt=[((9/5)*temp+32) for temp in celcius]

print(faranheyt)

faranheyt1=[]

for temp1 in celcius:

faranheyt1.append((9/5)*temp1+32)

print(faranheyt1)

--------------------------------------

Functions
Some examples:

def test_function():

'''

DOCSTRING:THis is just test function which shows hellow

NO input

-------

output:hello.

'''

print("Hello")

test_function()

def say_fuc(name):
print("hello", name)

say_fuc('Kamran')

def say_func1(name='David'):

print("hello",name)

say_func1("Kamran By")

def add(n1=0,n2=0):

return n1+n2

print(add(123,321))

def dog_check(mystring):

return 'dog' in mystring

print(dog_check(' dog run away'))

------------------------------------------

Args accepts all input without limit. And it shows the result as tuple

def sumup(*args):

return sum(args)

print(sumup(1,2,3,4,5,6,7,8,9,0,0,9,8,7,6,5,4,3,2,1,))

spam also do the same thing

def sumup(*spam):
return sum(spam)

print(sumup(1,2,3,4,5,6,7,8,9,0,0,9,8,7,6,5,4,3,2,1))

--------------------------------

def sumup(*args):

result=[]

for items in args:

result.append(items)

return result

print(sumup(1,2,3,4,5))

------------------------------

kwargs is like args but it show result as dicrionary

def veg(**kwargs):

print(kwargs)

if "fruit" in kwargs:

print("I am going to by they package of fruit")

else:

print("i will try another time")

veg(fruit="apple")

dic={'fruit':'qeni'}

print(dic['fruit'])

----------------------------------
Lets combine args and kwargs together.

dic={'fruit':'qeni'}

print(dic['fruit'])

def myfunc(*args,**kwargs):

print(args)

print(kwargs)

print(myfunc(1,2,3,4,56,fruit="apple",food="bread"))

Result:

(1, 2, 3, 4, 56)

{'fruit': 'apple', 'food': 'bread'}

None

-------------------------------------

.join is used to join some parameters and it changes the format of list to the string

l2=['hello', 'Kamran','From','Zaqatala']

l3=" ".join(l2)

print(l3)

print(type(l2))

Result: hello Kamran From Zaqatala

--------------------------------

abs(100-200)=100 (returns actual number )

--------------------------------------

map function is used to map operations

def square(num):

return num**2

mystring=[1,3,5,9,11,13]
for items in map(square,mystring):

print(items)

print(list(map(square,mystring))) Result:

Result:

25

81

121

169

[1, 9, 25, 81, 121, 169]

-----------------------

def myfunc(a, b):

return a + b

x = map(myfunc, ('apple', 'banana', 'cherry'), ('orange', 'lemon', 'pineapple'))

print(x)

#convert the map into a list, for readability:

print(list(x))

---------------------------

Filter does the same thing but it returns value if the result of function is true(Boolean)

def funnkc1(num):

return num%2==0

print(res1=list(filter(funnkc1,mystring)))
Result: [2, 4, 6, 8, 10, 12, 14, 16, 18, 20]

-----------------------------

Mysting=[1,2,3,4]

Very interesting Lambda. It the same as result is x*x

list1=list(map(lambda num:num**2,mystring))

print(list1)

Result: [1,4,9,16]

OOP in python

class Calculation():

def __init__(self,num1,num2):

self.add=num1+num2

self.minus=num1-num2

self.devide=num1/num2

self.multiply=num1*num2
multi=Calculation(num1=12, num2=2)

print(multi.multiply)

Result:24

------------------------

Class Object attribute

class Calculation():

names="they are numbers"

def __init__(self,num1,num2):

self.add=num1+num2

self.minus=num1-num2

self.multi=num1*num2

self.devide=num1/num2

res=Calculation(12, 3)

print(res.names)

Result: they are numbers

---------------------------

Method inside the class

class Calculation():

names="they are numbers"

def __init__(self,num1,num2):

self.add=num1+num2

self.minus=num1-num2

self.multi=num1*num2

self.devide=num1/num2
def description(self):

print("Method inside the class")

res=Calculation(12, 3)

res.description()

Result: Method inside the class

------------------------

We can execute method inside of the class

class Calculation():

names="they are numbers"

def __init__(self,num1,num2):

self.add=num1+num2

self.minus=num1-num2

self.multi=num1*num2

self.devide=num1/num2

def description(self):

result1=self.add+self.minus+self.multi+self.devide

return result1

res=Calculation(12, 3)

print(res.names)

print(res.description())

Result=64.0

-------------------------

Methods in the class can accept external input


class Calculation():

names="they are numbers"

def __init__(self,num1,num2):

self.add=num1+num2

self.minus=num1-num2

self.multi=num1*num2

self.devide=num1/num2

def description(self,a):

result1=(self.add+self.minus+self.multi+self.devide)*a

return result1

res=Calculation(12, 3)

print(res.names)

print(res.description(10))

Result:640

------------------------------------

Another example

class circle():

pi=3.14

def __init__(self,radius):

self.radius=radius

def cal(self):

return self.radius*self.radius*circle.pi*2

myres=circle(10)
print(myres.cal())

Result:628

------------------------------

Inheritance

class Animal():

def __init__(self):

print("Animal is created")

def who_am_i(self):

print("I am animal")

def eat(self):

print("I am eating")

class Dog(Animal):

def __init__(self):

Animal.__init__(self)

print("Dog is created")

def color(self):

Animal.who_am_i(self)

print("and my color is black")

mydog=Dog()

mydog.eat()

mydog.color()

Result:

Animal is created

Dog is created
I am eating

I am animal

and my color is black

-------------------

Polymorpysim in pyhton

class Dog():

def __init__(self,name):

self.name=name

def speak(self):

return self.name+" Says Woof!"

class Cat():

def __init__(self,name):

self.name=name

def speak(self):

return self.name+" Says mouw"

reks=Dog("Reks")

tom=Cat("Tom")

def pet_speak(pet):

print(pet.speak())

pet_speak(reks)
pet_speak(tom)

Result:

Reks Says Woof!

Tom Says mouw

----------------------

another example

class India():

def capital(self):

print("New Delhi is the capital of India.")

def language(self):

print("Hindi is the most widely spoken language of India.")

def type(self):

print("India is a developing country.")

class USA():

def capital(self):

print("Washington, D.C. is the capital of USA.")

def language(self):

print("English is the primary language of USA.")

def type(self):

print("USA is a developed country.")

obj_ind = India()

obj_usa = USA()

for country in (obj_ind, obj_usa):


country.capital()

country.language()

country.type()

------------------------------

Magic function

mylist=[1,2,3,4,5]

class Book():

def __init__(self,title,author,page):

self.title=title

self.author=author

self.page=page

def __str__(self):

return f"{self.title} is written by {self.author} and has {self.page} pages"

def __len__(self):

return self.page

def __del__(self):

print("THe book has been deleted")

b=Book("Python","Kamran Carayev",500)

print(b) #represent __str__

print(len(b)) #represent __len__

del(b) #represent __del__


print(b)

Result:

Python is written by Kamran Carayev and has 500 pages

500

THe book has been deleted

Traceback (most recent call last):

File "C:\Users\k80044720\Desktop\phyton\untitled5.py", line 30, in <module>

print(b)

NameError: name 'b' is not defined

----------------------------------------------------

How to import modules to the pyton script

C:\Users\k80044720\Desktop\phyton\sub\sub1

main file myprogram.py is created in C:\Users\k80044720\Desktop\phyton

sub.py is created in C:\Users\k80044720\Desktop\phyton\sub

sub1py is created in C:\Users\k80044720\Desktop\phyton\sub\sub1

mymodule.py is created in in C:\Users\k80044720\Desktop\phyton

mymodule.by file:

def myfunc():

print("Hey i am in mymodule.py file")

myprogram.py file:

from mymodule import myfunc

myfunc()

from sub import sub

sub.funksub()
from sub.sub1 import sub1

sub1.subfunc1()

sub.py file:

def funksub():

print("I am in subdirector")

sub1.py file:

def subfunc1():

print("i am in sub1 directory")

-------------------------------------------------

Error Handling

try:

#This block execits script

def add(n1,n2):

return n1+n2

num1=10

num2=int(input("enter NUM2:"))
result=add(num1,num2)

except:

#block executes when error occurs

print("it did not work. check again")

else:

#this block executes when error not occurs

print("Succesfuly executed")

print(result)

-------------------------------

try:

f=open("test1234",'r')

f.write=("THis is the new line")

except TypeError:

print("You have type error")

except OSError:

print("You have OS related error")

finally:

#This bloch runs always

print("I always run")

----------------------------------------

Another example

def ask():

tr=0

while True:

try:

result=int(input("Please enter number: "))

except:
if tr>=5:

print("you have reached max number attempts")

break

else:

print("THis is not the number, plz try again")

tr+=1

continue

else:

print("THank you for entering the number")

break

finally:

print("Tranzaction has finished")

ask()

---------------------------------------------

Python decoration

def hello(name="Kamran"):

print('Hello has been executed')

def greet():

return "\t \t\t\t\t THis is the geet funch which is executed"

def Welcome():

return "\t \t\t\t\t Welcome to this function bey buddy"

#it will return function inside the function

if name=="Kamran":

return greet

else:
return Welcome

myfunk=hello("Kamran")

print(myfunk())

----------------------

Lets input function into the function as argument

def hello():

return 'Hi i am hello()'

def other(some_def_func):

# print("Other code runs here")

print(some_def_func())

print(other(hello))

Result:

Hi i am hello()

-----------------------------------------

Another decoration example

def new_decerater(original_funck):

def wrap_funck():

print("some scripts before decoration")

original_funck()

print("Some scripts after decoration")

return wrap_funck
def i_need_decoration():

print("decorate me")

my_value=new_decerater(i_need_decoration)

print(my_value())

Result:

some scripts before decoration

decorate me

Some scripts after decoration

None

--------------------------------

Decoration with @

def new_decerater(original_funck):

def wrap_funck():

print("some scripts before decoration")

original_funck()

print("Some scripts after decoration")

return wrap_funck

@new_decerater

def i_need_decoration():

print("decorate me")

print(i_need_decoration())

Result:

some scripts before decoration

decorate me

Some scripts after decoration


None

--------------------------------

Yield function is used to make the calculation without storing in memory

def create_cubs(n):

for i in range(n):

yield i**3

for x in create_cubs(10):

print(x)

Result:

27

64

125

216

343

512

729

--------------------

When we use yield, we can use next() to query the value

def create_cubs(n):

for i in range(n):

yield i**3
g=create_cubs(4)

print(g)

print(next(g))

print(next(g))

print(next(g))

print(next(g))

Result:

<generator object create_cubs at 0x000002C74982BCC8>

27

-------------------------

Iteration of string

s='hello'

s_iter=iter(s)

print(next(s_iter))

Result:

Djange Web

pip install Django==3.0.5

pip install Django==3.0.5


django-admin startproject django_app

2.1 Djang o 2
Che at She e t .p d f.p d f

URLS:

Everything about URLS are processed in urls.py file. Basically the url syntax is like below

urlpatterns = [
    path('admin/', admin.site.urls),
]

Lets create one example for this URL: in this case we need to create options.py and import it to urls.py

from . import options

urlpatterns = [
    path('', options.home),
]

It means that when user firstly enter the web page the request is coming to urls.py file. Then it will
redirect the request to the home() function which is located in options.py file

In home() function example we will return one string as the web page

from django.http import HttpResponse

def home(request):
    return HttpResponse("THis the home Page function")

Using templates:

First thing we should do is that create one folder which allows to insert all web page documentations. So
in this case we need to create one folder (for example 'folderdir' on root directory and then create
index.html file.

Then we need to input below line in settings.py file

'DIRS': ['folderdir'],
Then we need to input render into the options.py file end redirect request in home function

from django.shortcuts import render

def home(request):
    
    return render(request, "index.html")

In addition we can pass any argument in with render to the next page

def kamran(request):
    
    return render(request,"kamran.html", {'key1':"THis is the Value of key
1"})

in Kamran.html file:

{{key1}}

IN THE NEXT STEP LETS REDIRECT TO ANOTHER WEB PAGE

Firstly need to create form and input area for text

<html>
<body>
    
<h1>Index.htlm file is activated</h1>

<form action="{% url 'count' %}">
<textarea cols="40" rows="8" name="full_text"></textarea>
<br/>
<input type="submit" value="TEXT"></input>
</form>

</body>

</html>

Need to add one more path for count and redirect it to options.py

path('count/', options.count, name='count'),

Then create count function and render to count.html and forward the text
def count(request):
    fulltext=request.GET['full_text']
    return render(request,'count.html', {'KEY1':fulltext})

index.html

<html>

<h1>Count web page</h1>
{{KEY1}}

</html>

Working with GIT

First enter the project directory and start git there from command line

#git init

Then run below command from CMD

#git add –A

You can check status by below command

#git status

Then confirm changes or new created project by below command

#git commit –m “My first git project”

Then enter the github.com web site and create new repository. After that enter your project to the new
repository by below commands

echo "# tst" >> README.md


git init
git add README.md
git commit -m "first commit"
git remote add origin https://github.com/carayev/tst.git
git push -u origin master

or

git remote add origin https://github.com/carayev/tst.git


git push -u origin master

Lets start creating new Web site:


In first place we need to install visrtual environment

#pip3 install virtualenv

Then enter the directory and create virtual environment

#vurtualenv env1

In linux need to activate virtualenvironment like below command

#source env1/bin/activate

In Windows:

#env\bin\Scripts\activate

We can simple exit from envisonment by below command

#deactivate

After entering new environment lets create new peoject

#django-admin startproject portfolio

Even we have installed djnago on PC, we need to download and install Django after entering new
envisonment

pip install Django==3.0.5

after creating new web site we may want to stop uploading some important files to GIT

to do that need to create .gitignore file and specify all required files to omit

for more information visit https://www.gitignore.io/

APPs in python

When we initially add app in python, it will create new directory

#python manage.py startapp blog

MODELS in Django
In first step lets go to jobs/models.py and add below lines. It will be
used for working with images
from django.db import models
class jobs(models.Model):
    image=models.ImageField(upload_to='images/')
    summary=models.CharField(max_length=200)

then lets update models in python database


#python manage.py migrate
Then run below command to update special models
#python manage.py makemigrations
As a result it will not show any changes
To make it visible by Django we need to add this jobs app in
portfolio/settings.py
INSTALLED_APPS = [
    'jobs.apps.JobsConfig',
    
]

At the end of the portfolio/settings.py we need to add media path and


media url
MEDIA_ROOT = os.path.join(BASE_DIR, 'media')
MEDIA_URL = '/media/'

Then form the command line we will make migration


#python manage.py makemigrations
If we find some error regarding image codes are not recognized, we
need to install Pillow
#pip install Pillow

Then we can run migration to update


#python manage.py migrate
If we want to make some changes in image directory or image
variable, after changes need to update by below commands in CMD
#python manage.py makemigrations
#python manage.py migrate

Admin in Django
First we need to create superuser from CMD
#python manage.py createsuperuser
Then we will be able to login admin web page
Its time to see the jobs in admin panel. To do that we need to imports
jobs from models.py in jobs directory
jobs/admin.py
from .models import jobs

then we need to enter below parameter so the jobs models will be


registered in admin panel
jobs/admin.py
admin.site.register(jobs)
The jobs main function is to upload image. After we upload the image
we need to enter it and see that picture
For that we need to add it urls.py in portfolio project
urlpatterns = [
    path('admin/', admin.site.urls),
] + static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT)

Then add below importing function in url.py


from django.conf import settings
from django.conf.urls.static import static

PostgreSQL
Firstly need to install PostgreSQL db on server or computer then need
to open shell t login to the DB
then type below command to see current user
#\du
by fefault postgres user dont have password. lets set pasword
#\password postgres
then lets create database
#CREATE DATABASE portfoliodb

thats all for confiruation in DB. the next section we will go to change
DB settings in django prject

need to enter /portfolio/settings.py and change database settings

DATABASES = {
'default': {
'ENGINE': 'django.db.backends.postgresql',
'NAME': 'portfoliodb',
'USER': 'postgres',
'PASSWORD': 'admin',
'HOST': '127.0.0.1',
'PORT': '5432',
}
}

then we need to migrate apps to new db adn create super user


#pyhton manage.py migrate
#python manage.py createsuperuser

Add model in blog app


Steps
1) Create a Blog model in models.py in blog app
a) give a title
b) give publication date
c) give body
d) give image

2) add Blog app to the settings


3) Create migration
4) Migrate
5) add to the admin (register in admin page)

Lets start:
1)Create class in blogs/models.py
class Blog(models.Model):
    title=models.CharField(max_length=255)
    pub_date=models.DateTimeField()
    body=models.TextField()
    image=models.ImageField(upload_to='images/')

2) add blogs app to portfolio/settings.py


'blog.apps.BlogConfig',

3) Create migration
#python manage.py makemigrations
4) migrate
#python manage.py migrate
5) add to the admin (register in admin page) in blods/admin.py
from .models import Blog

admin.site.register(Blog)

Use Bootstrap and query from DB

As you know we do modification on /jobs/ directory and lets get data


from DB
Need to add below script to get data from DB
from .models import jobs

def home(request):
    jobs1=jobs.objects
    return render(request, 'jobs/index.html',  {'KEY1':jobs1})

Then need to query them from index.html

        {% for i in KEY1.all %}
        <div class="col-md-4">
          <div class="card mb-4 shadow-sm">
            <img class="bd-placeholder-img card-img-top" width="100%" heig
ht="225" src="{{ i.image.url }}" preserveAspectRatio="xMidYMid slice" focu
sable="false" role="img" aria-label="Placeholder: Thumbnail
"><title>Placeholder</title><rect width="100%" height="100%" fill="#55595c
"/><text x="50%" y="50%" fill="#eceeef" dy=".3em"></text>
            <div class="card-body">
              <p class="card-text">{{i.summary}}</p>
            </div>
          </div>
        </div>
        {% endfor %}
        

Create blog page and query all data in separate blog page

as you know when we enter one page it coms to directly to the


/portfolio/urls.py file.
in this stage we will redirect from /portfolio/urls to /blogs/urls.py and
will strart procees the date. we can do this by the help of include()
function

/portfolio/urls.py
from django.urls import path, include

path('blog/', include('blog.urls')),

then we will start working in /blogs/urls.py

from django.urls import path


from . import views

urlpatterns = [
path('', views.allblogs, name='allblogs'),

then we need to add allblogs function in /blog/views.py


from django.shortcuts import render
from .models import Blog

def allblogs(request):
blogs=Blog.objects

return render(request,'blogs/allblogs.html', {'KEY2':blogs})

After that we will create /blog/templates/blog/allblogs.html file

then we can query data in allblogs.html

{% for y in KEY2.all %}
<a href=""><h3>{{y.title}}</h3> </a>
<h5>{{y.pub_date}}</h5>
<img src="{{ y.image.url }}" class="img-fluid" height="200"
width="250" >
<p>{{ y.body }}</p>

{% endfor %}

Its better not to query all data in summary page. So we will create
additional function def summary(self) in /blog/models.py to limit the
number of symbols

/blog/modules.py

class Blog(models.Model):
    title=models.CharField(max_length=255)
    pub_date=models.DateTimeField()
    body=models.TextField()
    image=models.ImageField(upload_to='images/')

    def summary(self):
        return self.body[:100]

then we will query it from allblogs.html

<p>{{ y.summary }}......</p>

In allblogs.html the publication date shown very detail. So we will sort


it by writing additional function in /blog/models.py
def pub_date_summary(self):
        return self.pub_date.strftime('%b %e %Y')

st rft im e .d o cx

then lets change query method in allblogs.html


 <h5>{{y.pub_date_summary}}</h5>

One very interesting method in admin page. If we add below script


in /blog/views.py it will chow tile in the admin blog page
def __str__(self):
        return self.title

in the next step lets query all detail information when enter blog detail
page.
Firstly need to create new url in blog/urls.py
urlpatterns = [
    path('', views.allblogs, name='allblogs'),
    path('<int:blog_id>/', views.detail, name='detail'),
    

Firstly it will take blog_id and retdirect request to views.detail function


In blog/views.py we will create below function and import one more
function
from django.shortcuts import render, get_object_or_404

def detail(request, blog_id):
    detailblog=get_object_or_404(Blog, pk=blog_id)
    return render(request,'blogs/detail.html', {'KEY4':detailblog})

then we need to create file in blog/templates/blogs/detail.html and


enter below key so it will query the result
{{ KEY4.title }}

In the index.html we need to send id so it will be able to query data in


the next page based on id
 </div class="text-muted">  

        {% for y in KEY2.all %}

       <a href="{% url 'detail' y.id %}"><h3>{{y.title}}</h3> </a>

       <h5>{{y.pub_date_summary}}</h5>

       <img src="{{ y.image.url }}"  class="img-fluid" height="200" widt
h="250" >

       <p>{{ y.summary }}......</p>

        
        {% endfor %}
      </div>

     

Lets create new static files in Django. This files are never changed.
We create one static folder in portfolio/static and put two files there.
One is resume in pdf format and another one is jpeg file
Then we need to add below scripts in portfolio/settings.py

STATICFILES_DIRS = [
    os.path.join(BASE_DIR, 'portfolio/static/')

]
STATIC_ROOT = os.path.join(BASE_DIR, 'static')
STATIC_URL = '/static/'

Then we need to type below command in CMD so it will create


additional static folder on top level and copy all static files into there
#python manage.py collectstatic

Then we need to load static files into the directory where we need
them. In this example we will load them in index.html file
 {% load static %}

Then query them where we need


<img src="{% static '540c0af4d612a.jpg' %}" height="150">

   link" href="{% static 'Kamran_JarayevCV.pdf' %}">Resume</a>
Adding HTML header or as separate entity in Django
Firstly lets create base.html under
projecthunt/templates/base.html
(projecthunt is the project name)
Then add below scripts. It means that this html file is
the header or footer html where all other templates
will use it

Hello this is the header

{% block content %}

{% endblock %}

Hello this is the this is the footer

Then we need to add this in the settings in templates


section
'DIRS': ['producthunt/templates'],
Then we need to query it in from main home.html
file

{% extends 'base.html' %}

{% block content %}
<br>
THis it the home.html file

<br>
{% endblock %}

The result will be like this

Sign Up function
Based on our design we will redirect all accounts
request to the accounts/urls.py page from main
urls.py
path('accounts/', include('accounts.urls')),
Then we will enter below script in accounts/urls.py
urlpatterns = [
   path('signup', views.signup, name='signup'),
]

Then import below library in accounts/views.py


from django.shortcuts import render, redirect
from django.contrib.auth.models import User
from django.contrib import auth

Then create below function in accounts/views.py for


signup
def signup(request):
    if request.method=='POST':
        if request.POST['password1']==request.POST['password2']:
            try:
                user=User.objects.get(username=request.POST['username'])
                return render(request, 'accounts/signup.html', {'error':'U
sername has already taken'})
            except User.DoesNotExist:
                user=User.objects.create_user(
                    
                    username=request.POST['username'],
                    password=request.POST['password1'],
                    first_name=request.POST['firstname'],
                    last_name=request.POST['lastname'],
                    email=request.POST['email'],
                    )
                auth.login(request,user)
                return redirect('home')
        else:
            return render(request, 'accounts/signup.html', {'error':'Passw
ord must match'})
        
    else:
        #user wants to enter info
        return render(request, 'accounts/signup.html')

the lets design and configure signup.html in


producthunt-project\accounts\templates\accounts

{% extends 'base.html' %}

{% block content %}
<br>
{% if error %}
{{ error }}
{% endif %}

<h1>Signup</h1>

<form method="POST" action="{% url 'signup' %}">
    {% csrf_token %}
Username:
<br/>
<input type="text" name="username">
<br/>
Firstname:
<br/>
<input type="text" name="firstname">
<br/>

Last name:
<br/>
<input type="text" name="lastname">
<br/>
E-mail:
<br/>
<input type="email" name="email">
<br/>
<!--
-->
Password:
<br/>
<input type="password" name="password1"/>
<br/>
Confirm Password:
<br/>
<input type="password" name="password2"/>

<br/>
<br/>
<input class="btn btn-primary "  type="submit" value="Sign UP!"/>

</form>

<br>
{% endblock %}

Log IN
Firstly need to work on login.html
{% extends 'base.html' %}

{% block content %}
<br>
{% if error %}
{{ error }}
{% endif %}
<h1>Log-in page</h1>

<form method="POST" action="{% url 'login' %}">
    {% csrf_token %}
Username:
<br/>
<input type="text" name="username">
<br/>

Password:
<br/>
<input type="password" name="password"/>
<br/>

<br/>
<br/>
<input class="btn btn-primary "  type="submit" value="Login"/>

</form>

<br>
{% endblock %}

Then need to create login path in accounts/urls.py


path('login', views.login, name='login'),

Then need to work on login function in


accounts/views.py

def login(request):
    if request.method=='POST':
        user = auth.authenticate(username=request.POST['username'], passwo
rd=request.POST['password'])
        if user is not None:
            auth.login(request, user)
            return redirect('home')
        else:
            return render(request, 'accounts/login.html', {'error':'Userna
me or password does not exsit, or account does not exist '})
    else:
        return render(request, 'accounts/login.html')

Then need to work on login.html


{% if user.is_authenticated %}
                    <li class="nav-item active">
                        <a class="nav-link enable" href="javascript:
{document.getElementById('logout').submit()}" onclick="">Log Out</a>
                        <form id="logout" method="POST" action="{% url 'lo
gout' %}">
                            {% csrf_token %}
                            <input type="hidden"/>
                        </form>
                    </li>
                    {% else %}
                    <li class="nav-item active">
                        <a class="nav-link enable" href="{% url 'signup' %
}">Sign UP</a>
                    </li>
                    <li class="nav-item active">
                        <a class="nav-link enable" href="{% url 'login' %}
">Sign in</a>
                    </li>

                    {% endif %}

Logout page
Need to create logout path in /accounts/urls.py
 path('logout', views.logout, name='logout'),

then need to create logout function in


accounts/views.py

def logout(request):
    if request.method=='POST':
        auth.logout(request)
        return redirect('home')

then lets work on base.html

                    {% if user.is_authenticated %}
                    <li class="nav-item active">
                        <a class="nav-link enable" href="javascript:
{document.getElementById('logout').submit()}" onclick="">Log Out</a>
                        <form id="logout" method="POST" action="{% url 'lo
gout' %}">
                            {% csrf_token %}
                            <input type="hidden"/>
                        </form>
                    </li>
                    {% else %}
                    <li class="nav-item active">
                        <a class="nav-link enable" href="{% url 'signup' %
}">Sign UP</a>
                    </li>
                    <li class="nav-item active">
                        <a class="nav-link enable" href="{% url 'login' %}
">Sign in</a>
                    </li>

                    {% endif %}
Customization of admin
site when adding model
class Post(models.Model):
    title=models.CharField(max_length=120, blank=True)
    content=models.CharField(max_length=500)
    created_date=models.DateTimeField(auto_now_add=True)
    update_date=models.DateTimeField(auto_now=True)
    
    def __str__(self):
        return (self.title)
    
    class Meta:
        verbose_name="Post Model control panel"
        #verbose_name_plural="Main Control Unit"
        ordering=['created_date']

When we create class in models.py we can create


additional class and refer it in main class
class Category(models.Model):
    category_name=models.CharField(max_length=120)

    def __str__(self):
        return self.category_name
    
    class Meta:
        verbose_name='Categories'
    

class Post(models.Model):
    post_category=models.ManyToManyField(Category)
    title=models.CharField(max_length=120, blank=True)
    content=models.CharField(max_length=500)
    created_date=models.DateTimeField(auto_now_add=True)
    update_date=models.DateTimeField(auto_now=True)
    
    def __str__(self):
        return (self.title)
    
    class Meta:
        verbose_name="Post Model control panel"
        #verbose_name_plural="Main Control Unit"
        ordering=['created_date']

Then need register category class in admin page


from .models import Post, Category

admin.site.register(Post)
admin.site.register(Category)

Simple POST method example


In urls.py
from .views import post_create, post_update, post_list, post_delete, one_e
xample
  path('form/', view=one_example),

In views.py
def one_example(request):
    
    if request.method=='POST':
        data={}
        received_message=request.POST.get('test_message',None)
        data={'received_message':received_message}
        return render(request, 'posts/form.html',data)
        print(data)
    return render(request, 'posts/form.html')

in form.html
<html>

<form action="" method="POST">
 {% csrf_token %} 
<input type="text" name="test_message">
<input type="submit" value="send">

</form>

<br>
{% if received_message%}

<h1>{{ received_message }}</h1>
{% endif %}

</html>

S-ar putea să vă placă și