Skip to content
Snippets Groups Projects
Commit 26c35ea3 authored by Marc Taylor's avatar Marc Taylor
Browse files

created register func with api, and also credit score for users

parent ced4286e
No related branches found
No related tags found
1 merge request!5Backend
......@@ -19,7 +19,6 @@ BASE_DIR = Path(__file__).resolve().parent.parent
MEDIA_URL = '/media/'
MEDIA_ROOT = os.path.join(BASE_DIR, 'media')
# Quick-start development settings - unsuitable for production
# See https://docs.djangoproject.com/en/5.0/howto/deployment/checklist/
......@@ -48,6 +47,7 @@ INSTALLED_APPS = [
'corsheaders'
]
MIDDLEWARE = [
"django.middleware.security.SecurityMiddleware",
"django.contrib.sessions.middleware.SessionMiddleware",
......@@ -139,4 +139,13 @@ DEFAULT_AUTO_FIELD = "django.db.models.BigAutoField"
#]*/
CORS_ALLOW_ALL_ORIGINS = True
# but not recommended
\ No newline at end of file
# but not recommended
REST_FRAMEWORK = {
'DEFAULT_PERMISSION_CLASSES': [
'rest_framework.permissions.AllowAny',
],
'DEFAULT_AUTHENTICATION_CLASSES': [
'rest_framework.authentication.BasicAuthentication',
],
}
\ No newline at end of file
from django.contrib import admin
from .models import Product
from .models import Category
from .models import Category, Product, Profile
# Register your models here.
admin.site.register(Product)
admin.site.register(Category)
admin.site.register(Profile)
\ No newline at end of file
from django.db import models
from django.contrib.auth.models import AbstractUser
from django.contrib.auth.models import User
from django.utils.translation import gettext_lazy as _
# Create your models here.
# class CustomUser(AbstractUser):
# credits = models.IntegerField(default=0)
# phone_number = models.CharField(max_length=50)
class Profile(models.Model):
user = models.OneToOneField(User, on_delete=models.CASCADE, unique=True)
credit = models.IntegerField(default=0)
class Category(models.Model):
name = models.CharField(max_length=100)
......
# myapp/serializers.py
from rest_framework import serializers
from .models import Product
from .models import Category
from .models import Product, Profile, Category
from django.contrib.auth.models import User
class ProductSerializer(serializers.ModelSerializer):
class Meta:
......@@ -13,3 +14,31 @@ class CategorySerializer(serializers.ModelSerializer):
class Meta:
model = Category
fields = '__all__'
class ProfileSerializer(serializers.ModelSerializer):
class Meta:
model = Profile
fields = '__all__'
class UserSerializer(serializers.ModelSerializer):
password = serializers.CharField(write_only=True)
class Meta:
model = User
fields = "__all__"
def create(self, validated_data):
"""
Function to create a User, send a JSON object containing
the attributes: username, email, first_name, last_name, password.
"""
user = User.objects.create_user(
username=validated_data['username'],
email=validated_data['email'],
first_name=validated_data['first_name'],
last_name=validated_data['last_name'],
password=validated_data['password']
)
return user
......@@ -2,41 +2,3 @@ from django.contrib.auth import get_user_model
from django.test import TestCase
# Create your tests here.
class UsersManagersTests(TestCase):
def test_create_user(self):
User = get_user_model()
user = User.objects.create_user(email="normal@user.com", password="foo")
self.assertEqual(user.email, "normal@user.com")
self.assertTrue(user.is_active)
self.assertFalse(user.is_staff)
self.assertFalse(user.is_superuser)
try:
# username is None for the AbstractUser option
# username does not exist for the AbstractBaseUser option
self.assertIsNone(user.username)
except AttributeError:
pass
with self.assertRaises(TypeError):
User.objects.create_user()
with self.assertRaises(TypeError):
User.objects.create_user(email="")
with self.assertRaises(ValueError):
User.objects.create_user(email="", password="foo")
def test_create_superuser(self):
User = get_user_model()
admin_user = User.objects.create_superuser(email="super@user.com", password="foo")
self.assertEqual(admin_user.email, "super@user.com")
self.assertTrue(admin_user.is_active)
self.assertTrue(admin_user.is_staff)
self.assertTrue(admin_user.is_superuser)
try:
# username is None for the AbstractUser option
# username does not exist for the AbstractBaseUser option
self.assertIsNone(admin_user.username)
except AttributeError:
pass
with self.assertRaises(ValueError):
User.objects.create_superuser(
email="super@user.com", password="foo", is_superuser=False)
\ No newline at end of file
# myapp/urls.py
from django.urls import path, include
from rest_framework.routers import DefaultRouter
from .views import ProductViewSet
from .views import ProductViewSet, ProfileViewSet, UserViewSet, UserRegistrationView
from .views import CategoryViewSet
router = DefaultRouter()
router.register(r'products', ProductViewSet)
router.register(r'categories', CategoryViewSet)
router.register(r'profile', ProfileViewSet)
urlpatterns = [
path('', include(router.urls)),
path('register/', UserRegistrationView.as_view(), name='user-register')
]
# myapp/views.py
from rest_framework import viewsets
from .models import Product
from .serializers import ProductSerializer
from .models import Category
from .serializers import CategorySerializer
from rest_framework import viewsets, status
from rest_framework.response import Response
from rest_framework.views import APIView
from .models import Product, Category, Profile
from .serializers import ProductSerializer, CategorySerializer, ProfileSerializer, UserSerializer
from django.contrib.auth.models import User
class ProductViewSet(viewsets.ModelViewSet):
queryset = Product.objects.all()
......@@ -12,4 +13,22 @@ class ProductViewSet(viewsets.ModelViewSet):
class CategoryViewSet(viewsets.ModelViewSet):
queryset = Category.objects.all()
serializer_class = CategorySerializer
\ No newline at end of file
serializer_class = CategorySerializer
class ProfileViewSet(viewsets.ModelViewSet):
queryset = Profile.objects.all()
serializer_class = ProfileSerializer
class UserViewSet(viewsets.ModelViewSet):
queryset = User.objects.all()
serializer_class = UserSerializer
class UserRegistrationView(APIView):
def post(self, request, *args, **kwargs):
serializer = UserSerializer(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)
\ No newline at end of file
0% Loading or .
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment