Thursday, 27 October 2022

Django rest framework Project tutorials part 4

A django Application


Users

Authetication

search

list

select

cart/wishlist

booking/order

payment

notification



Users

email

mobile

password

otp

Authentication

API

register

login

generate_otp

verify_otp

forgot password

change password


Search

name

location

category


list

name

price

rate


order/booking

Payment


django application

model

serializers

views

urls


Model

class Basemodel(models.Model):

    created=datetimstamp

    updated=datetimstamp


class TableName(models.Model,User,Basemodel):

    field_name=Type

    name=models.CharField

    price=models.FloatField

    count=models.PositiveIntegerField

    is_customer=BooleanFiled

    model_name=Relation

    booking=models.Foreinkey    one to many  on_delete=models.SET_NULL ,PROTECT,

                    =models.OntoOne one to one

                    =models.ManyToMany many to many


example

class Student(models.Model)

    name=models.CharField(max_lenght=100)

    age=models.PositiveIntegerField()


class Mark(models.Model):

    subject=models.CharField(max....)

    grade=models.PositiveIntegerField()

Student and Mark

student table

id name age

1 lulu 15

2 sulu 14


mark

id subject grade student

1    maths 10        1

2    arabic    9        1

3     maths   9        2

       arabic  15     2


class Mark(models.Model):

    subject=models.CharField(max....)

    grade=models.PositiveIntegerField()

    student=models.Foreinkey(Student,)


Serializer

from rest_framework import serializers


class StudentSerializer(serializers.ModelSerailzers):

    class Meta:

        model = Student

         exclude=('created','updated') or  fieleds=('name','age') or fields= '__all__'

      


class StudentSerializer(serializers.ModelSerailzers):

    class Meta:

        model = Student

         exclude=('created','updated') or  fieleds=('name','age') or fields= '__all__'


    def to_internal_value(self, data):

            #input data manipulation

            return data


   def to_representation(self, instance);

        data= super()

        #output data manipulation

        return data

    def validate(self, attrs):

    def create(

    def update(


views

from rest_framework import viewsets


class StudentViewset(viewsets.ModelViewSet):

    queryset.Student.objects.all()

    serializer_class=StudentSerializer


    urls

    from rest_framwork.routers import SimpleRouter

    #main_url/function_name/

    http://localhost:8000/student/


    student is function name mapped to viewset function or class


    obj=SimpleRouter()

    obj.register(r'student',StudentViewset)

    urlpatterns=obj.urls



class StudentViewset(viewsets.ModelViewSet):

    queryset.Student.objects.all()

    serializer_class=StudentSerializer

    authetication_class=

    permission_class


inbuild methods with model viewset

    def create()  ===>POST

    def update()    ==>PUT,PATCH

    def retrieve()    ==>GET

    def list() ===>GET

    def destroy() ==>DELETE

   

 @action(methods=['post'],detail=True)

   def custom_function()

    eg 

        @action(methods=['POST'],detail=False,authentication_classes=[],permission_classes=[])

def login(self,request):

                pass


    

urls

    from rest_framwork.routers import SimpleRouter

    #main_url/function_name/

    http://localhost:8000/student/


    student is function name mapped to viewset function or class

student ===>StudentViewset

    router=SimpleRouter()

    router.register(r'student',StudentViewset)

    urlpatterns=router.urls



ModelViewSet

class ModelViewSet(mixins.CreateModelMixin,==>POST create

                   mixins.RetrieveModelMixin, ==>GET, retrieve

                   mixins.UpdateModelMixin, ==>PUT,PATCH update

                   mixins.DestroyModelMixin,==>DELETE destroy

                   mixins.ListModelMixin, =====>GET, list

                   GenericViewSet)


class ProfileViewset(viewsets.ModelViewSet)

create

update

list retrieve

delete



class ProfileViewsets(mixins.CreateModelMixin,GenericViewSet)

    def create() ===>POST


Admin


admin.site.register(Student)


or we can customize with adminModel


example to disable delete option from admin


class StudentModel(admin.ModelAdmin):

def get_actions(self, request):

actions = super(StudentModel, self).get_actions(request)

if 'delete_selected' in actions:

del actions['delete_selected']

return actions

def delete_model(self, request, obj):

return 0

def message_user(self, request, message, level = 30, extra_tags, fail_silently) :

message='delete not allowed'#you can give whatever messeage you want

return super().message_user(request, message, 40, extra_tags, fail_silently)

so then we can resgist Student model like 

admin.site.register(Student,StudentModel)

to get more about this overiding functions alt+click on admin.ModelAdmin


Saturday, 15 October 2022

Django tutorial part 2

step 1

 create an environment

open 'cmd ' from address bar











python -m venv myenv -> enter

step 2

activate by 


PS E:\project> .\myenv\Scripts\activate


step 3

Install django library


step 4

Install djangorestframework


step 5

Show installed libraries in current environment


step 6 

listing installed libraries in current environment


step 7

After installing django we can see a django-admin.exe file is created in myenv ->Scripts-
>

step 8

listing django admiṇ command

django-admin


Step 9

create project using django admin


step 10

create app 



step 11

open vs code



step 12

project file structure












step 13

register app 

add myapp in INSTALLED_APPS list variable 


INSTALLED_APPS = [
    'django.contrib.admin',
    'django.contrib.auth',
    'django.contrib.contenttypes',
    'django.contrib.sessions',
    'django.contrib.messages',
    'django.contrib.staticfiles',
    'myapp',
]


step 14

create urls.py in myapp











STEP 15

Create a funtion home in views.py of myapp

from django.http import HttpResponse

def home(request):
    return HttpResponse("HELLO WORLD")


step 16

myproject-> urls.py

from django.contrib import admin
from django.urls import path,include

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

step 17

create routing for home

from django.urls import path
from myapp.views import home
urlpatterns = [
    path('index',home)
]

step 18

runserver

(myenv) PS E:\project> python manage.py runserver

Watching for file changes with StatReloader

Performing system checks...


System check identified no issues (0 silenced).


You have 18 unapplied migration(s). Your project may not work properly until you apply the migrations for app(s): admin, auth, contenttypes, 

sessions.

Run 'python manage.py migrate' to apply them.

October 16, 2022 - 12:03:14

Django version 4.1.2, using settings 'myproject.settings'

Starting development server at http://127.0.0.1:8000/    

Quit the server with CTRL-BREAK.


step 19

goto browser and type url

http://127.0.0.1:8000/index









































Django rest framework Project tutorials part 3

psc project

psc_project

-pscproject

--settiṇgs.py

--urls.py

-questionapp

--models.py

--urls.py

--serializers.py

--views.py

-userapp

--models.py

--urls.py

--serializers.py

--views.py

-manage.py

  settings.py

INSTALLED_APPS = [
    'django.contrib.admin',
    'django.contrib.auth',
    'django.contrib.contenttypes',
    'django.contrib.sessions',
    'django.contrib.messages',
    'django.contrib.staticfiles',
    'userapp',
    'questionapp',
]

  urls.py

from django.contrib import admin
from django.urls import path,include

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

Question app

-models.py

-serilizers.py

-urls.py

-views.py

-models.py

from django.db import models

# Create your models here.
class Question(models.Model):
    question=models.CharField(max_length=255)
    ans1=models.CharField(max_length=255)
    ans2=models.CharField(max_length=255)
    ans3=models.CharField(max_length=255,blank=True,null=True)
    ans4=models.CharField(max_length=255,blank=True,null=True)
    ans5=models.CharField(max_length=255,blank=True,null=True)
    ans6=models.CharField(max_length=255,blank=True,null=True)
    original_ans=models.PositiveIntegerField(default=0)
    grade=models.FloatField
    class Meta:
        db_table='questions'

serilizers.py

from questionapp.models import Question
from rest_framework import serializers

class QuestionSerilizer(serializers.ModelSerializer):

    class Meta:
        model =Question
        fields = '__all__'
class QuestionDetailSerilizer(serializers.ModelSerializer):
   
    class Meta:
        model =Question
        fields = ('id','question')

views.py

from questionapp.models import Question
from rest_framework.response import Response
from rest_framework import viewsets
from questionapp.serilizers import QuestionDetailSerilizer, QuestionSerilizer

class QuestionViewset(viewsets.ModelViewSet):
    queryset =Question.objects.all()
    serializer_class = QuestionSerilizer
   
    def list(self, request, *args, **kwargs):
        queryset=self.queryset
        data= QuestionDetailSerilizer(queryset,many=True).data
        return Response(data)

urls.py

from questionapp.views import QuestionViewset
from rest_framework import routers
router=routers.SimpleRouter()
router.register("question",QuestionViewset)
urlpatterns=router.urls


USERAPP

-models.py

-serilizers.py

-urls.py

-views.py


models.py

from django.db import models
from django.contrib.auth.models import User

class Profile(User):
    qualification= models.CharField(max_length=255,blank= True,null=True)
    location= models.CharField(max_length=255,blank=True,null=True)
    address= models.TextField(blank= True,null=True)
    country= models.CharField(max_length=100,blank=True,null=True)
    district= models.CharField(max_length= 100,blank=True,null=True)
    photo= models.ImageField(blank=True,null=True)
   
    class Meta:
        db_table='profiles'


serilizers.py

from userapp.models import Profile
from rest_framework import serializers

class ProfileSerilizer(serializers.ModelSerializer):
   
    class Meta:
        model =Profile
        fields = '__all__'
class ProfileDetailSerilizer(serializers.ModelSerializer):
   
    class Meta:
        model =Profile
        fields = ('id','username')

views.py

from userapp.models import Profile
from rest_framework.response import Response
from rest_framework import viewsets
from userapp.serializers import ProfileDetailSerilizer, ProfileSerilizer

class ProfileViewset(viewsets.ModelViewSet):
    queryset =Profile.objects.all()
    serializer_class = ProfileSerilizer
   
    def list(self, request, *args, **kwargs):
        queryset=self.queryset
        data= ProfileDetailSerilizer(queryset,many=True).data
        return Response(data)

urls.py

from userapp.views import ProfileViewset

from rest_framework import routers
router=routers.SimpleRouter()
router.register("profile",ProfileViewset)
urlpatterns=router.urls













Friday, 14 October 2022

Django rest framework Project tutorials part 1

 Create a django project

1.create a environment 

python -m venv myenv

2.activate environment

myenv/Scripts/activate


refer python environment tutorial for more information

https://mamspython.blogspot.com/2022/10/creating-python-envirnment-in-5-ways.html

3.pip install Django

4. pip install djangorestframework

5.  django-admin startproject myproject .

6. python manage.py startapp myapp


7. register installed myapp

go to myproj folder

open settings.py

goto varaible list INSTALLED_APPS = [

add 'myapp', to the list

example

INSTALLED_APPS = [

  'django_crontab',
    'widget_tweaks',

.........

'myapp',

]

8. create urls.py in myapp folder

9. add line in myproj->urls.py 

path('',include('myapp.urls')),

10.add serializers.py file in myapp







Creating python environment in 5 ways

 python environment are created several ways

before creating environment install python software on os level

https://www.python.org/ftp/python/3.10.8/python-3.10.8-amd64.exe

environment are used to separate corresponding projects requirement libraries independent with another projects ,it will also helps to versioning your projects like , one environment may be using python 3.7 version another will be python version 3.8 version


lets create a envirnment myenv

1.python -m venv myenv 

myenv folder is created after executing this comment

inside myenv you can see activate file by opening scripts or bin


there are lots of ways creating environment





to activate the environment,use the below comment

find the path of activate file in my case activate file is located D:\projects\test13\testproj\myenv\Scripts\

so I can activate myenv like 

myenv\Scripts\activate

because i am already in  D:\projects\test13\testproj\ so i need only go from testproj folder "myenv\Scripts\"

or 

by full path

 D:\projects\test13\testproj\myenv\Scripts\activate 



I usually use this method and recommend using this simple way , you can try other methods also

2. python -m virtualenv .

. (the dot is used to create env on the current folder)

for this, you may need to install

pip install virtualenv


3.mkvirtualenv myenv 

using python wrapper

pip install virtualenv
pip install virtualenvwrapper-win ( do not use pip install virtualenvwrapper)

4. you can use pycharm software (download and install pycharm)

5. using anaconda 

Please note:-

Now onwards i will use env for environment