Home > Back-end >  Django Rest APi Authentication credentials
Django Rest APi Authentication credentials

Time:08-10

i am working on a project using Django as backed server and flutter as fronted framework , i faced a problem today when i try to POST a data from the flutter UI app into the Django server data base using the the REST API i keep getting this error
"detail": "Authentication credentials were not provided." the problem is when i make a POST request from the web browser it works fine i guess i need to provide more information to the Django server to from the flutter App to authenticate then i can POST data here is the flutter method

Future<CreateProduct> submitProduct(String name , String price , String brand , String countinstock , String category , String description) async {

  String createProductUri = "http://127.0.0.1:8000/api/products/create/";
  final response = await http.post(Uri.parse(createProductUri),body: {
    "name": name,
    "price": price,
    "brand": brand,
    "countInStock": countinstock,
    "category": category,
    "description": description
  });
  if (response.statusCode == 201){
      final responseString = response.body;
      return createProductFromJson(responseString);
  }
}

and the Django request

@api_view(['POST'])
@permission_classes([IsAdminUser])
def createProduct(request):
    user = request.user
    data = request.data
    product = Product.objects.create(
        user=user,
        name=data['name'],
        price=data['price'],
        brand=data['brand'],
        countInStock=data['countInStock'],
        category=data['category'],
        description=data['description'],
    )
    serializer = ProductSerializer(product, many=False)
    return Response(serializer.data)

CodePudding user response:

try this:

  final response = await http.post(Uri.parse(createProductUri),
    headers:{"Accept": "application/json",
             'Content-Type': 'application/json'},
    body: {
        "name": name,
        "price": price,
        "brand": brand,
        "countInStock": countinstock,
        "category": category,
        "description": description
      });

CodePudding user response:

using this

headers: {
    "Authorization": 'Bearer token'
  }

solved the problem

  • Related