menu

Questions & Answers

Django datetime TypeError: fromisoformat: argument must be str
Internal Server Error: /api/orders/add/
Traceback (most recent call last):**strong t[enter image description here][1]ext**
  File "C:\Users\kalya\OneDrive\Desktop\my app\myenv\lib\site-packages\django\core\handlers\exception.py", line 55, in inner
    response = get_response(request)
  File "C:\Users\kalya\OneDrive\Desktop\my app\myenv\lib\site-packages\django\core\handlers\base.py", line 197, in _get_response      
    response = wrapped_callback(request, *callback_args, **callback_kwargs)
  File "C:\Users\kalya\OneDrive\Desktop\my app\myenv\lib\site-packages\django\views\decorators\csrf.py", line 54, in wrapped_view     
    return view_func(*args, **kwargs)
  File "C:\Users\kalya\OneDrive\Desktop\my app\myenv\lib\site-packages\django\views\generic\base.py", line 84, in view
    return self.dispatch(request, *args, **kwargs)
  File "C:\Users\kalya\OneDrive\Desktop\my app\myenv\lib\site-packages\rest_framework\views.py", line 509, in dispatch
    response = self.handle_exception(exc)
  File "C:\Users\kalya\OneDrive\Desktop\my app\myenv\lib\site-packages\rest_framework\views.py", line 469, in handle_exception        
    self.raise_uncaught_exception(exc)
  File "C:\Users\kalya\OneDrive\Desktop\my app\myenv\lib\site-packages\rest_framework\views.py", line 480, in raise_uncaught_exception
    raise exc
  File "C:\Users\kalya\OneDrive\Desktop\my app\myenv\lib\site-packages\rest_framework\views.py", line 506, in dispatch
    response = handler(request, *args, **kwargs)
  File "C:\Users\kalya\OneDrive\Desktop\my app\myenv\lib\site-packages\rest_framework\decorators.py", line 50, in handler
    return func(*args, **kwargs)
  File "C:\Users\kalya\OneDrive\Desktop\my app\backend\base\views\order_views.py", line 31, in addOrderItems
    order = Order.objects.create(
  File "C:\Users\kalya\OneDrive\Desktop\my app\myenv\lib\site-packages\django\db\models\manager.py", line 85, in manager_method       
    return getattr(self.get_queryset(), name)(*args, **kwargs)
  File "C:\Users\kalya\OneDrive\Desktop\my app\myenv\lib\site-packages\django\db\models\query.py", line 514, in create
    obj.save(force_insert=True, using=self.db)
  File "C:\Users\kalya\OneDrive\Desktop\my app\myenv\lib\site-packages\django\db\models\base.py", line 806, in save
    self.save_base(
  File "C:\Users\kalya\OneDrive\Desktop\my app\myenv\lib\site-packages\django\db\models\base.py", line 857, in save_base
    updated = self._save_table(
  File "C:\Users\kalya\OneDrive\Desktop\my app\myenv\lib\site-packages\django\db\models\base.py", line 1000, in _save_table
    results = self._do_insert(
  File "C:\Users\kalya\OneDrive\Desktop\my app\myenv\lib\site-packages\django\db\models\base.py", line 1041, in _do_insert
    return manager._insert(
  File "C:\Users\kalya\OneDrive\Desktop\my app\myenv\lib\site-packages\django\db\models\manager.py", line 85, in manager_method       
    return getattr(self.get_queryset(), name)(*args, **kwargs)
  File "C:\Users\kalya\OneDrive\Desktop\my app\myenv\lib\site-packages\django\db\models\query.py", line 1434, in _insert
    return query.get_compiler(using=using).execute_sql(returning_fields)
  File "C:\Users\kalya\OneDrive\Desktop\my app\myenv\lib\site-packages\django\db\models\sql\compiler.py", line 1620, in execute_sql   
    for sql, params in self.as_sql():
  File "C:\Users\kalya\OneDrive\Desktop\my app\myenv\lib\site-packages\django\db\models\sql\compiler.py", line 1547, in as_sql        
    value_rows = [
  File "C:\Users\kalya\OneDrive\Desktop\my app\myenv\lib\site-packages\django\db\models\sql\compiler.py", line 1548, in <listcomp>    
    [
  File "C:\Users\kalya\OneDrive\Desktop\my app\myenv\lib\site-packages\django\db\models\sql\compiler.py", line 1549, in <listcomp>    
    self.prepare_value(field, self.pre_save_val(field, obj))
  File "C:\Users\kalya\OneDrive\Desktop\my app\myenv\lib\site-packages\django\db\models\sql\compiler.py", line 1487, in prepare_value 
    value = field.get_db_prep_save(value, connection=self.connection)
  File "C:\Users\kalya\OneDrive\Desktop\my app\myenv\lib\site-packages\django\db\models\fields\__init__.py", line 910, in get_db_prep_save
    return self.get_db_prep_value(value, connection=connection, prepared=False)
  File "C:\Users\kalya\OneDrive\Desktop\my app\myenv\lib\site-packages\django\db\models\fields\__init__.py", line 1546, in get_db_prep_value
    value = self.get_prep_value(value)
  File "C:\Users\kalya\OneDrive\Desktop\my app\myenv\lib\site-packages\django\db\models\fields\__init__.py", line 1524, in get_prep_value
    value = super().get_prep_value(value)
  File "C:\Users\kalya\OneDrive\Desktop\my app\myenv\lib\site-packages\django\db\models\fields\__init__.py", line 1403, in get_prep_value
    return self.to_python(value)
  File "C:\Users\kalya\OneDrive\Desktop\my app\myenv\lib\site-packages\django\db\models\fields\__init__.py", line 1485, in to_python  
    parsed = parse_datetime(value)
  File "C:\Users\kalya\OneDrive\Desktop\my app\myenv\lib\site-packages\django\utils\dateparse.py", line 114, in parse_datetime        
    return datetime.datetime.fromisoformat(value)

enter image description here

from django.shortcuts import render
from rest_framework.decorators import api_view, permission_classes
from rest_framework.permissions import IsAuthenticated, IsAdminUser
from rest_framework.response import Response

from base.models import Product, Order, OrderItem, ShippingAddress
from base.serializers import ProductSerializer, OrderSerializer


from rest_framework import status


@api_view(['POST'])
@permission_classes([IsAuthenticated])
def addOrderItems(request):

    user = request.user
    data = request.data

    orderItems = data['orderItems']

    if orderItems and len(orderItems) == 0:
        return Response({'detail': 'No Order Item'}, status=status.HTTP_400_BAD_REQUEST)

    else:

        # Create order

        order = Order.objects.create(
            user=user,
            paymentMethod=data['paymentMethod'],
            taxPrice=data['taxPrice'],
            shippingPrice=data['shippingPrice'],
            totalPrice=data['totalPrice'],
        )
        # Create Shipping Address

        shipping = ShippingAddress.objects.create(
            order=order,
            address=data['ShippingAddress']['address'],
            city=data['ShippingAddress']['city'],
            postalCode=data['ShippingAddress']['postalCode'],
            country=data['ShippingAddress']['country'],

        )
        # Create Order items and set order to orderItem relationship
        for i in orderItems:
            product = Product.objects.get(_id=i['product'])

            item = OrderItem.objects.create(
                product=product,
                order=order,
                name=product.name,
                qty=i['qty'],
                price=i['price'],
                image=product.image.url,

            )
            # Update stock
            product.countInStock -= item.qty
            product.save()

        serializer = OrderSerializer(order, many=False)
        return Response(serializer.data)


@api_view(['POST'])
@permission_classes([IsAuthenticated])
def getOrderById(request, pk):
    user = request.user
    try:
        order = Order.objects.get(_id=pk)
        if user.is_staff or user.user == user:
            serializer = OrderSerializer(order, many=False)
            return Response(serializer.data)
        else:
            Response({'details': 'Not authenticated to view this 
            order'},
                     status=status.HTTP_400_BAD_REQUEST)
    except:
        Response({'details': 'Order doesnot exist'},
                 status=status.HTTP_400_BAD_REQUEST)
import { useNavigate, Link} from 'react-router-dom'
import { Button, Row, Col, ListGroup, Card, Image, } from 'react-bootstrap'
import {useDispatch, useSelector} from 'react-redux'
import Message  from '../components/Message'
import CheckoutSteps  from '../components/CheckoutSteps'
import { createOrder } from '../actions/orderActions'
import { ORDER_CREATE_RESET} from '../constants/orderConstants'

function PlaceOrderScreen() {
    
    const orderCreate = useSelector( state => state.orderCreate)
    const { order, error, success } = orderCreate

    const navigate = useNavigate()
    const dispatch = useDispatch()

    const cart = useSelector( state => state.cart)
    cart.itemsPrice = cart.cartItems.reduce((acc, item) => acc + item.price * item.qty, 0).toFixed(2)
    cart.shippingPrice = (cart.itemsprice > 0 ? 0 : 10).toFixed(2)
    cart.taxPrice = Number((0.13) * cart.itemsPrice).toFixed(2)
    cart.totalPrice =(Number(cart.itemsPrice) + Number(cart.shippingPrice) + Number(cart.taxPrice)).toFixed(2)



    useEffect(() =>{ 
        
        if(!cart.paymentMethod){
            navigate('/payment')
        }
        else {
            if(success)
            {
            navigate(`/order/${order._id}`)
            dispatch({type:ORDER_CREATE_RESET})
            }
        }   
    }, [navigate, success, cart, order, dispatch])

    const placeOrder = () =>{
        dispatch(createOrder(
            {
                orderItems: cart.cartItems,
                shippingAddress: cart.shippingAddress,
                paymentMethod: cart.paymentMethod,
                itemsPrice: cart.itemsPrice,
                shippingPrice: cart.shippingPrice,
                taxPrice: cart.taxPrice,
                totalPrice: cart.totalPrice, 

            }
        ))
    }
  return (
    <div>
        <CheckoutSteps step1 step2 step3 step4 />
        <Row>
            <Col md={8}>
                <ListGroup variant='flush'>
                    <ListGroup.Item>
                        <h2>Shipping</h2>

                        <p>
                            <strong>Shipping: </strong>
                            {cart.shippingAddress.address},  {cart.shippingAddress.city}
                            {'  '}
                            {cart.shippingAddress.postalCode},
                            {'  '}
                            {cart.shippingAddress.country}
                        </p>
                    </ListGroup.Item>

                    <ListGroup.Item>
                        <h2>Payment</h2>

                        <p>
                            <strong>Method: </strong>
                            {cart.paymentMethod}
                        </p>
                    </ListGroup.Item>

                    <ListGroup.Item>
                        <h2>Order Items</h2>

                        <p>
                            <strong>Shipping: </strong>
                         </p>
                            {cart.cartItems.length === 0 ? <Message variant={'info'}>
                                Your cart is empty
                            </Message> : (
                                <ListGroup variant='flush'>
                                    {cart.cartItems.map((item , index) => (
                                        <ListGroup.Item key={index}>
                                            <Row>
                                                <Col md={1}>
                                                    <Image src={item.image} alt={item.name} fluid  rounded />
                                                </Col>
                                                <Col>
                                                 <Link to={`/product/${item.product}`}>{item.name}</Link>
                                                </Col>

                                                <Col md={4}>
                                                    {item.qty} X ${item.price} =${(item.qty * item.price).toFixed(2)}
                                                </Col>
                                            </Row>
                                        </ListGroup.Item>
                                    ))}
                                </ListGroup>
                            )}
                    </ListGroup.Item>
                </ListGroup>
            </Col>

            <Col md={4}>
                <Card>
                    <ListGroup variant='flush'>
                        <ListGroup.Item>    
                            <h2>Order Summary</h2>
                        </ListGroup.Item>
                        <ListGroup.Item>    
                            <Row>
                                <Col>Items: </Col>
                                <Col>${cart.itemsPrice}</Col>
                            </Row>
                        </ListGroup.Item>

                        <ListGroup.Item>    
                            <Row>
                                <Col>Shipping:</Col>
                                <Col>${cart.shippingPrice}</Col>
                            </Row>
                        </ListGroup.Item>
                        <ListGroup.Item>    
                            <Row>
                                <Col>Tax: </Col>
                                <Col>${cart.taxPrice}</Col>
                            </Row>
                        </ListGroup.Item>
                        <ListGroup.Item>    
                            <Row>
                                <Col>Total Price: </Col>
                                <Col>${cart.totalPrice}</Col>
                            </Row>
                        </ListGroup.Item>

                        <ListGroup.Item>
                            {error && <Message variant='danger'>{error}</Message>}
                        </ListGroup.Item>


                        <ListGroup.Item>    
                            <Button
                                type='button'
                                className='btn-block'
                                disabled={cart.cartItems === 0}
                                onClick={placeOrder}
                            >
                                Place Order
                            </Button>
                        </ListGroup.Item>

                    </ListGroup>
                </Card>
            </Col>
        </Row>
    </div>
  )
}

export default PlaceOrderScreen
from pyexpat import model
from rest_framework import serializers
from django.contrib.auth.models import User
from rest_framework_simplejwt.tokens import RefreshToken

from .models import Product, Order, OrderItem, ShippingAddress


class UserSerializer(serializers.ModelSerializer):
    name = serializers.SerializerMethodField(read_only=True)
    _id = serializers.SerializerMethodField(read_only=True)
    isAdmin = serializers.SerializerMethodField(read_only=True)

    class Meta:
        model = User
        fields = ['id', '_id', 'username', 'email', 'name', 'isAdmin']

    def get__id(self, obj):
        return obj.id

    def get_isAdmin(self, obj):
        return obj.is_staff

    def get_name(self, obj):
        name = obj.first_name
        if name == '':
            name = obj.email

        return name


class UserSerializerWithToken(UserSerializer):
    token = serializers.SerializerMethodField(read_only=True)

    class Meta:
        model = User
        fields = ['id', '_id', 'username', 'email', 'name', 'isAdmin', 'token']

    def get_token(self, obj):
        token = RefreshToken.for_user(obj)
        return str(token.access_token)


class ProductSerializer(serializers.ModelSerializer):
    class Meta:
        model = Product
        fields = '__all__'


class ShippingAddressSerializer(serializers.ModelSerializer):
    class Meta:
        model = ShippingAddress
        fields = '__all__'


class OrderItemSerializer(serializers.ModelSerializer):
    class Meta:
        model = OrderItem
        fields = '__all__'


class OrderSerializer(serializers.ModelSerializer):
    orderItems = serializers.SerializerMethodField(read_only=True)
    ShippingAddress = serializers.SerializerMethodField(read_only=True)
    user = serializers.SerializerMethodField(read_only=True)

    class Meta:
        model = Order
        fields = '__all__'

    def get_orderItems(self, obj):
        items = obj.orderitem_set.all()
        serializer = OrderItemSerializer(items, many=True)
        return serializer.data

    def get_shippingAddress(self, obj):
        try:
            address = ShippingAddressSerializer(
                obj.shippingaddress, many=False).data
        except:
            address = False
        return address

    def get_user(self, obj):
        user = obj.user
        serializer = UserSerializer(user, many=False)
        return serializer.data
Answers(2) :

You can't use str() directly for the time module

use this:

def __str__(self):
    return self.createdAt

or use:

def __str__(self):
    return f"{self.createdAt.strftime('%d-%m-%Y')}"

data formats

Comments:
2023-01-23 00:55:09
My problem is not solved i got same error. i have post my code also
2023-01-23 00:55:09
why do you want to stringify your date field?
2023-01-23 00:55:09
Sorry Bt i am learning from the video. In the video he told to stringify date so i am doing the same. Please Can you tell me why error has occured and where is my mistake?

first of all you need to delete the files inside migrations folder and and __ pycache __ foledr and you may need clear the database
after that run python manage.py makemigrations it will show you those lines on the terminal ''' It is impossible to add a non-nullable field 'created_at' to customuser without specifying a default. This is because the database needs something to populate existing rows. Please select a fix:

  1. Provide a one-off default now (will be set on all existing rows with a null value for this column)
  2. Quit and manually define a default value in models.py. ''' type 1 should ask you ''' Please enter the default value as valid Python. The datetime and django.utils.timezone modules are available, so it is possible to provide e.g. timezone.now as a value. Type 'exit' to exit this prompt ''' typetimezone.now

and run python manage.py migrate will work perfectly