daily pastebin goal
58%
SHARE
TWEET

Untitled

a guest Jan 18th, 2019 62 Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
  1. from django.db import models
  2. from django.conf import settings
  3. from django.contrib.auth.models import User
  4. from django.db.models.signals import post_save
  5. from django.dispatch import receiver
  6.  
  7.  
  8. class Puppy(models.Model):
  9.     name = models.CharField(max_length=30)
  10.     price = models.DecimalField(max_digits=6, decimal_places=2)
  11.     image_url = models.CharField(max_length=200)
  12.     age = models.IntegerField(null=True)
  13.     weight = models.IntegerField(null=True)
  14.     description_de = models.CharField(max_length=500, null=True)
  15.     description_en = models.CharField(max_length=500, null=True)
  16.  
  17.     def __str__(self):
  18.         return self.name
  19.  
  20.  
  21. class Order(models.Model):
  22.     total_price = models.DecimalField(max_digits=9, decimal_places=2)
  23.     puppies = models.ManyToManyField(Puppy, through='PuppyOrder')
  24.     date = models.DateTimeField(auto_now_add=True, blank=True)
  25.     user = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.CASCADE, related_name='orders')
  26.  
  27.     def __str__(self):
  28.         return str(self.id)
  29.  
  30.  
  31. class PuppyOrder(models.Model):
  32.     order = models.ForeignKey(Order, on_delete=models.CASCADE)
  33.     puppy = models.ForeignKey(Puppy, on_delete=models.CASCADE)
  34.     amount = models.IntegerField()
  35.  
  36.     def __str__(self):
  37.         return str(self.id)
  38.  
  39.  
  40. class Address(models.Model):
  41.     user = models.OneToOneField(User, on_delete=models.CASCADE)
  42.     country = models.CharField(max_length=30, blank=True)
  43.     street = models.CharField(max_length=30, blank=True)
  44.     zip = models.CharField(max_length=10, blank=True)
  45.     city = models.CharField(max_length=30, blank=True)
  46.  
  47.  
  48. @receiver(post_save, sender=User)
  49. def create_user_address(sender, instance, created, **kwargs):
  50.     if created:
  51.         Address.objects.create(user=instance)
  52.  
  53.  
  54. @receiver(post_save, sender=User)
  55. def save_user_address(sender, instance, **kwargs):
  56.     instance.address.save()
  57.    
  58. async function createOrder(order) {
  59.   order = order.map(element =>
  60.     element = {'puppy' : element.puppy.id, 'amount': element.amount}
  61.   )
  62.   let orderReq = {"total_price": "500.00", "puppies": order}
  63.   console.log(JSON.stringify(orderReq))
  64.   const res = await fetch(REACT_APP_BACKEND_URL + `/shop/orders/`, {
  65.       method: 'POST',
  66.       headers: {
  67.         "Content-Type": "application/json",
  68.       },
  69.       body: JSON.stringify({ orderReq })
  70.     })
  71.   return res.json()
  72. }
  73.    
  74. from shop.models import Puppy, Order
  75. from django.contrib.auth.models import User
  76. from rest_framework import permissions, status, viewsets, generics
  77. from rest_framework.decorators import api_view
  78. from rest_framework.response import Response
  79. from rest_framework.reverse import reverse
  80. from rest_framework.exceptions import ValidationError
  81. from rest_framework_jwt.serializers import VerifyJSONWebTokenSerializer
  82. from .serializers import UserSerializer, UserSerializerWithToken, OrderSerializer, PuppySerializer
  83.  
  84.  
  85. @api_view(['GET'])
  86. def api_root(request, format=None):
  87.     return Response({
  88.         'users': reverse('user-list', request=request, format=format),
  89.         'orders': reverse('order-list', request=request, format=format),
  90.         'puppies': reverse('puppy-list', request=request, format=format),
  91.     })
  92.  
  93.  
  94. class OrderList(generics.ListCreateAPIView):
  95.     print("Test")
  96.     queryset = Order.objects.all()
  97.     permission_classes = (permissions.AllowAny,)
  98.     serializer_class = OrderSerializer
  99.  
  100.     def get_queryset(self):
  101.         if self.request.user is None or self.request.user.is_anonymous:
  102.             self.request.user = get_request_user_and_validate_token(self)
  103.         return Order.objects.all().filter(user=self.request.user)
  104.  
  105.     def perform_create(self, serializer):
  106.         print(self.request.data)
  107.         if self.request.user is None or self.request.user.is_anonymous:
  108.             self.reqest.user = get_request_user_and_validate_token(self)
  109.         if serializer.is_valid():
  110.             print('Creating new order...')
  111.             serializer.create(user=self.request.user, puppies=self.request.data)
  112.             return Response(serializer.data)
  113.         return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST)
  114.  
  115.  
  116. class OrderDetail(generics.RetrieveAPIView):
  117.     permission_classes = (permissions.AllowAny,)
  118.     queryset = Order.objects.all()
  119.     serializer_class = OrderSerializer
  120.  
  121.     def get_queryset(self):
  122.         if self.request.user is None or self.request.user.is_anonymous:
  123.             self.request.user = get_request_user_and_validate_token(self)
  124.         return Order.objects.all().filter(user=self.request.user)
  125.  
  126.  
  127. class UserList(generics.ListAPIView):
  128.     queryset = User.objects.all().select_related('address')
  129.     serializer_class = UserSerializer
  130.  
  131.  
  132. class UserDetail(generics.RetrieveAPIView):
  133.     queryset = User.objects.all().select_related('address')
  134.     serializer_class = UserSerializer
  135.  
  136.  
  137. class PuppyList(generics.ListAPIView):
  138.     permission_classes = (permissions.AllowAny,)
  139.     queryset = Puppy.objects.all()
  140.     serializer_class = PuppySerializer
  141.  
  142.  
  143. class PuppyDetail(generics.RetrieveAPIView):
  144.     permission_classes = (permissions.AllowAny,)
  145.     queryset = Puppy.objects.all()
  146.     serializer_class = PuppySerializer
  147.  
  148.  
  149. def get_request_user_and_validate_token(self):
  150.     print(self.request.user)
  151.     token = self.request.META.get('HTTP_AUTHORIZATION', " ").split(' ')[1]
  152.     data = {'token': token}
  153.     try:
  154.         valid_data = VerifyJSONWebTokenSerializer().validate(data)
  155.         print(valid_data['user'])
  156.         return valid_data['user']
  157.     except ValidationError as v:
  158.         print("validation error", v)
  159.    
  160. from rest_framework import serializers
  161. from rest_framework_jwt.settings import api_settings
  162. from django.contrib.auth.models import User
  163. from django.db import models
  164. from .models import Order, Puppy, PuppyOrder
  165.  
  166.  
  167. class UserSerializer(serializers.ModelSerializer):
  168.     orders = serializers.PrimaryKeyRelatedField(many=True, read_only=True)
  169.  
  170.     class Meta:
  171.         model = User
  172.         fields = ('id', 'username', 'orders')
  173.  
  174.  
  175. class UserSerializerWithToken(serializers.ModelSerializer):
  176.     # Code dealing with JWT token creation ...
  177.  
  178.  
  179. class PuppySerializer(serializers.ModelSerializer):
  180.     description = serializers.SerializerMethodField()
  181.  
  182.     def get_description(self, puppy):
  183.         return {'DE': puppy.description_de, 'EN': puppy.description_en}
  184.  
  185.     class Meta:
  186.         model = Puppy
  187.         fields = ('id', 'name', 'price', 'image_url', 'age', 'weight', 'description')
  188.  
  189.  
  190. class PuppyOrderSerializer(serializers.ModelSerializer):
  191.     puppy = serializers.ReadOnlyField(source='puppy.id')
  192.  
  193.     class Meta:
  194.         model = PuppyOrder
  195.         fields = ('puppy', 'amount')
  196.  
  197.  
  198. class OrderSerializer(serializers.ModelSerializer):
  199.     puppies = PuppyOrderSerializer(source='puppyorder_set', many=True)
  200.     user = serializers.ReadOnlyField(source='user.username')
  201.     total_price = "100.00"
  202.  
  203.     class Meta:
  204.         model = Order
  205.         fields = ('id', 'total_price', 'puppies', 'date', 'user')
RAW Paste Data
We use cookies for various purposes including analytics. By continuing to use Pastebin, you agree to our use of cookies as described in the Cookies Policy. OK, I Understand
 
Top