Skip to main content

Posts

Showing posts from May 20, 2024

Pytest with Django

  Steps and code to set up Django Rest Framework (DRF) test cases with database mocking.  1. Set up Django and DRF Install Django and DRF: ```sh pip install django djangorestframework ``` Create a Django project and app: ```sh django-admin startproject projectname cd projectname python manage.py startapp appname ``` 2. Define Models, Serializers, and Views models.py (appname/models.py): ```python from django.db import models class Item(models.Model):     name = models.CharField(max_length=100)     description = models.TextField() ``` serializers.py (appname/serializers.py): ```python from rest_framework import serializers from .models import Item class ItemSerializer(serializers.ModelSerializer):     class Meta:         model = Item         fields = '__all__' ``` views.py (appname/views.py): ```python from rest_framework import viewsets from .models import Item from .serializers import ItemSerializer class I...