Skip to content

Instantly share code, notes, and snippets.

@semicolom
semicolom / view.py
Created March 8, 2021 16:07
Django Rest Framework API view with Basic Auth
from rest_framework import status
from rest_framework.authentication import BasicAuthentication
from rest_framework.permissions import IsAuthenticated
from rest_framework.response import Response
from rest_framework.views import APIView
class BasicAuthView(APIView):
authentication_classes = [BasicAuthentication]
permission_classes = [IsAuthenticated]
@semicolom
semicolom / test_basic_auth.py
Created March 8, 2021 16:04
Django Rest Framework unit test API with Basic Auth
import base64
from rest_framework import HTTP_HEADER_ENCODING, status
from rest_framework.test import APITestCase
from user.models import User
class EndpointViewTest(APITestCase):
def test_basic_auth(self):
username = "test_username"
from django import forms
from .models import Player
class PlayerForm(forms.Form):
name = forms.CharField(widget=forms.HiddenInput())
from django import forms
from .models import Player
class PlayerForm(forms.ModelForm):
class Meta:
model = Player
fields = ['name']
widgets = {'name': forms.HiddenInput()}
from django.db import models
class Player(models.Model):
name = models.CharField(max_length=255)
from django.core.files import File
from django.test import TestCase
import mock
from forms import FileForm
from models import FileModel
from views import FileModelCreateView
from django.views.generic import CreateView
from .forms import FileForm
from .models import FileModel
class FileModelCreateView(CreateView):
model = FileModel # we keep this line to avoid the template_name attribute
form_class = FileForm
fields = ['field']
from django import forms
from .models import FileModel
class FileForm(forms.ModelForm):
class Meta:
model = FileModel
fields = ['file']
from django.views.generic import CreateView
from .models import FileModel
class FileModelCreateView(CreateView):
model = FileModel
fields = ['field']
success_url = '/'
from django.core.files import File
from django.test import TestCase
import mock
from models import FileModel
class FileModelTestCase(TestCase):
def test_file_field(self):