skip to Main Content

I have a web project what back-end is coded with django and front-end is coded with react.

In my project, i want to create an order to a special user so this part of project needs to know the user but when i used request.user it returned AnonymousUser.

here are the react, axios code and views.py with rest_framework:

react code

    // Hook to save game id and price
    const [all, setAll] = useState({'game': 0, 'price': 0});
    
    // get state
    const location = useLocation();
    const state = location.state;
    
    useEffect(() => {
        setAll({'game': state[0]}, 'price': suggestion);
    }, [])
    
        // To check user confirm suggestion and make order api.
    const orderApi = async (e) => {
        e.preventDefault();
        try {
            // console.log({'state': state[0], 'suggestion': suggestion});
            console.log(all);
            const {status} = await axios.post('http://127.0.0.1:8000/api-1/order/create/', all);
            if (status === 201) {
                console.log('created');
            }
        } catch (err) {
            console.log(err)
        }
    }

views.py

from rest_framework import status
from rest_framework.response import Response
from . import serializer
from rest_framework.decorators import api_view
from . import models
from game.models import Game

@api_view(['GET', 'POST'])
def orderCreate(request):
    
    # Here my program return AnonymousUser
    print(str(request.user) + 'n')
    
    if request.method == 'POST':
            .......
            
    orders = models.Order.objects.all()
    serialized = serializer.OrderSerializer(orders, many=True)

    return Response(serialized.data, status=status.HTTP_200_OK)
  • To write a clean code i didn’t write the front-end code and post method codes in my question.
  • Please help to retrieve the user object and create order.

2

Answers


  1. REST API’s are stateless, not in a user session.
    So there’s no user logged on, and Django returns you the Anonymous user.
    You will have to pass the user in the post parameters

    Login or Signup to reply.
  2. As @stefano mentioned, REST is stateless. By default request.user will be AnonymousUser because Django isn’t implicitly aware of the user making the request.
    If this special user is constant you can probably create a small helper function to return it.

    def get_special_user():
        special_user_id = 1
        return User.objects.get(id=special_user_id)
    

    Then call this function in your view. Otherwise, you will have to set up authentication. I recommend django rest auth

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search