Friday, May 31, 2024

Django

pip install djangorestframework django-cors-headers 


--------------------------------------------------------------
# after creating/changing models.py execute below commands in terminal project folder 

python manage.py makemigrations
python manage.py migrate 

-------------------------------------------------------------------------------------------------
views.py 

from rest_framework.decorators import api_view
from rest_framework.response import Response
from rest_framework import status
from .models import Item
from .serializers import ItemSerializer
from django.views.decorators.csrf import csrf_exempt 

@csrf_exempt
@api_view(['GET', 'POST'])
def item_list(request):
    if request.method == 'GET':
        items = Item.objects.all()
        serializer = ItemSerializer(items, many=True)
        return Response(serializer.data)

    elif request.method == 'POST':
        serializer = ItemSerializer(data=request.data)
        if serializer.is_valid():
            serializer.save()
            return Response(serializer.data, status=status.HTTP_201_CREATED)
        return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST)

@csrf_exempt
@api_view(['GET', 'PUT', 'DELETE'])
def item_detail(request, pk):
    try:
        item = Item.objects.get(pk=pk)
    except Item.DoesNotExist:
        return Response(status=status.HTTP_404_NOT_FOUND)

    if request.method == 'GET':
        serializer = ItemSerializer(item)
        return Response(serializer.data)

    elif request.method == 'PUT':
        serializer = ItemSerializer(item, data=request.data)
        if serializer.is_valid():
            serializer.save()
            return Response(serializer.data)
        return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST)

    elif request.method == 'DELETE':
        item.delete()
        return Response(status=status.HTTP_204_NO_CONTENT)
------------------------------------------------------------------------------------
# urls.py 

# myapp/urls.py

from django.urls import path
from .views import item_list, item_detail

urlpatterns = [
    path('items/', item_list, name='item_list'),
    path('items/<int:pk>/', item_detail, name='item_detail'),
]

----------------------------------------------------------------------
models.py 

from django.db import models 

class item(models.Model):
    id = models.AutoField(primary_key=True)
    name = models.CharField(max_length=500)
    price = models.CharField(max_length=500)

    def __str__(self) -> str :
        return super().__str__() 
---------------------------------------------------------------------
serializers.py 

from rest_framework import serializers 
from .models import item 

class itemSerializer(serializers.ModelSerializer):
    class Meta:
        model = item 
        fields = "__all__"
---------------------------------------------------------------------
settings.py 

INSTALLED_APPS = [
'rest_framework',
'corsheaders',
'your_app_name'
]

MIDDLEWARE = [
#
# add below line 
'corsheaders.middleware.CorsMiddleware',
# add above line just above below line
'django.middleware.common.CommMiddleware',
]

# add this line here so you  can integrate with frontend like 'REACT JS / ANGULAR' 
# below is for all domain/servers can access django app
CORS_ORIGIN_ALLOW_ALL = True 
# if you want to specify domains/servers
CORS_ORIGIN_WHITELIST = (
'http://localhost:3000'
)

MEDIA_URL = "/media/"
MEDIA_ROOT = BASE_DIR / "templates"

# to prevent 'CSRF error' while performing post,put operation through 'postman or react js'

CSRF_TRUSTED_ORIGINS = [
    'http://127.0.0.1:8000/post_cities'
]

# or add @csrf_exempt or @api_view(['POST','PUT','DELETE']) above views in views.py  
--------------------------------------------------------------
# don't forget to create "media and templates" directories in your main project folder otherwise 
it'll give you error 
--------------------------------------------------------------

main project urls.py 

from django.contrib import admin
from django.urls import path,include
from django.conf.urls.static import static
from django.conf import settings 

urlpatterns = [
path("admin/", admin.site.urls),
path("",include("your_app_name.urls")
]+ static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT)

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

No comments:

Post a Comment

virtual environment on python on Ubuntu

 # 1. Update system and install Python tools sudo apt update && sudo apt install python3-pip python3-venv -y # 2. Setup Django in a ...