How to fix 500 internal server error while using Django and React

C-Bizz

I'm trying to create a simple shopping cart with django and react. When I click on the add-to-cart button I get 500 Internal Server Error from react. The error it's displaying in django is: ValueError: Cannot assign "<django.contrib.auth.models.AnonymousUser object at 0x00000268F76AEFA0>": "order_product.user" must be a "User" instance. I have tried every means I know but I'm still not able to fix it. Below is the programme:

DJANGO
urls.py 
path('add-to-cart/', add_to_cart_view.as_view(), name='add-to-cart'),
views.py 

class add_to_cart_view(APIView):
    permission_classes = []
    def post(self, request, *args, **kwargs):
        id = request.data.get('id', None)
        if id is None:
            return Response({"message": "Invalid request"}, status=HTTP_400_BAD_REQUEST)

        product = get_object_or_404(Product, id=id)

        requested_product = order_product.objects.create(
                product=product,
                user=request.user,
                ordered=False
            )

        order_qs = Order.objects.filter(user=request.user, ordered=False)
        if order_qs.exists():
            order = order_qs[0]
            if not order.products.filter(product__id=requested_product.id).exists():
                order.products.add(requested_product)
          
                return Response(status=HTTP_200_OK)

        else:
            ordered_date = timezone.now()
            order = Order.objects.create(
            user=request.user, ordered_date=ordered_date)
            order.products.add(order_product)
            return Response(status=HTTP_200_OK)
REACT
export const AddToCartURL = "http://127.0.0.1:8000";

const handleAddToCartURL = async (id) => {
            try {
                const res = await axios.post(`${AddToCartURL}/add-to-cart/`, {id});
                setProduct(res.data);
                console.log(res.data)
            }
            catch (err) {

            }
        };


    return(
        <Box sx={{ flexGrow: 1 }} m={4}>
            <Grid container spacing={3}>
                <Grid item xs={9}>
                    <Item>
                       <img src={product.image} alt="" />
                       <div>
                           <p>{product.description}</p>
                           <p>{product.label}</p>
                           <p>{product.price}</p>

                       </div>
                       <button color='primary' onClick={() => handleAddToCartURL(product.id)}>
                            <AddShoppingCartIcon />
                        </button>  
                    </Item>                  
                </Grid>
                <Grid item xs>
                    <Item>Similar Products</Item>
                </Grid>
            </Grid>
    
      </Box>
    )
}
export default ProductDetails

I really dont't understand why it is returning anonymous user from django. Please how do I fix it?

Rvector

You have this error because the user you try to assign is not authenticated. Add a permission to your view like this :

from rest_framework import permissions

class add_to_cart_view(APIView):
    permission_classes = [permissions.IsAuthenticated]
    
    # Rest of the code here

NB : You will need to authenticate the user before make a post request.

UPDATE : If you want to test with non authenticated user. You can create a generic user for that :

# Create a user with a name unauthenticated_user in the admin

# In the view :
if request.user.is_authenticated:
    # Do something for authenticated users.
    # Your code previous code here
else:
    # retrieve the unauthenticated_user you create 
    # use your custom user here

Collected from the Internet

Please contact [email protected] to delete if infringement.

edited at
0

Comments

0 comments
Login to comment

Related

500 internal server error while using Django and React

How can i fix internal server error?HTTP ERROR:500

How to fix an unknown internal server error (500) Nginx is giving me?

How to fix " HTTP Status 500 – Internal Server Error "

Error 500 (Internal Server Error) When Submission in Django using AJAX

POST 500 (Internal Server Error) using Ajax, React and Rails

Bitnami Django Stack 500 Internal Server Error

500 (Internal Server Error) AJAX Django

500 Internal Server Error in production - Django

Django showing 500 Internal Server Error on HTTPS

How to fix 500 internal

How to fix "Internal Server Error" on using EventBus in custom AuthProvider

Handling 500 (Internal Server Error) using HttpClient

500 internal server error php, how to solve?

Internal Server Error (500)

Why am I Getting 500 internal server error in flask while connecting using MySQLdb?

Getting "500 Internal Server Error" while posting a request to the MongoDB using Mongoose transaction

500 Internal Server Error Error while creating AdminClient for Cluster Default

Getting 500 internal server error while creating invoices in xero

500 internal server error, NullPointerException while get request

500 internal server error while saving data to mongoDB

Internal Server Error 500 while accessing $GITLAB/admin/runners

Getting an 500 Internal Server Error (ActiveRecord) while iterating over posts

500 internal server error while authenticating Microsoft graph

Django on Openshift - 500 Internal Server Error - error in wsgi.py

Django - Ajax POST error 403 (Forbidden) and 500 (Internal Server Error)

POST sails server api and react client 500 (Internal Server Error)

Flask server internal error, how to fix it

How do I fix 500 Internal Error with Flask/Heroku?

TOP Ranking

  1. 1

    Failed to listen on localhost:8000 (reason: Cannot assign requested address)

  2. 2

    How to import an asset in swift using Bundle.main.path() in a react-native native module

  3. 3

    Loopback Error: connect ECONNREFUSED 127.0.0.1:3306 (MAMP)

  4. 4

    pump.io port in URL

  5. 5

    Spring Boot JPA PostgreSQL Web App - Internal Authentication Error

  6. 6

    BigQuery - concatenate ignoring NULL

  7. 7

    ngClass error (Can't bind ngClass since it isn't a known property of div) in Angular 11.0.3

  8. 8

    Do Idle Snowflake Connections Use Cloud Services Credits?

  9. 9

    maven-jaxb2-plugin cannot generate classes due to two declarations cause a collision in ObjectFactory class

  10. 10

    Compiler error CS0246 (type or namespace not found) on using Ninject in ASP.NET vNext

  11. 11

    Can't pre-populate phone number and message body in SMS link on iPhones when SMS app is not running in the background

  12. 12

    Generate random UUIDv4 with Elm

  13. 13

    Jquery different data trapped from direct mousedown event and simulation via $(this).trigger('mousedown');

  14. 14

    Is it possible to Redo commits removed by GitHub Desktop's Undo on a Mac?

  15. 15

    flutter: dropdown item programmatically unselect problem

  16. 16

    Change dd-mm-yyyy date format of dataframe date column to yyyy-mm-dd

  17. 17

    EXCEL: Find sum of values in one column with criteria from other column

  18. 18

    Pandas - check if dataframe has negative value in any column

  19. 19

    How to use merge windows unallocated space into Ubuntu using GParted?

  20. 20

    Make a B+ Tree concurrent thread safe

  21. 21

    ggplotly no applicable method for 'plotly_build' applied to an object of class "NULL" if statements

HotTag

Archive