Home > database >  Django cannot find data that I'm sure exists in the database
Django cannot find data that I'm sure exists in the database

Time:10-31

basically my app receives a serial number through an AJAX POST request from the front end, and it has to find the product who's serial number matches the given serial number and return it's details.

here is my view , I have confirmed that the data is being received correctly and that a product with the exact serial number exists in the database but i still get a 404 not found response.

i am using Mariadb as my app's database. here is my code: ``

```
from django.http import HttpResponse
from django.shortcuts import render
from django.views.decorators.csrf import csrf_exempt
from products.models import Products 
from django.shortcuts import get_object_or_404


``
# Create your views here.
@csrf_exempt
def products(request):
    if request.method == 'POST':
        query = request.body.decode('utf-8')
        products = Products.objects.all()
        for i in products:
        print(f"item{i} : {i.serial_number}")
        print(f"request : {query}")
        context = {
            'products' : products,
        }
        get_object_or_404(products,serial_number = query)
        return render(request,"products/products.html",context)
    else:
        return render(request,"products/products.html")
```



here is the terminal output:

`
`[31/Oct/2022 10:29:48] "GET / HTTP/1.1" 200 2459
itemProducts object (1) : https://blog.minhazav.dev/research/html5-qrcode.html
itemProducts object (3) : 123
itemProducts object (4) :
itemProducts object (5) : http://shooka.com
request : "http://shooka.com"
Not Found: /`
``

and here is my models code:

`from django.db import models 

# Create your models here.
class Products(models.Model):
    pub_date = models.DateTimeField('date published',null=False)
    prod_name = models.CharField(max_length=255 , null=False)
    serial_number = models.CharField(max_length=255 , null 
=False,unique=True)
    comments = models.TextField()`

as you can see, serial_number is a string and my query is also a string so there should be no problem comparing those two

i tried casting query to str before searching for it in the db, i also checked my db charset , uts utf8mb4

CodePudding user response:

I would try to filter it first manually like this:

query = request.body.decode('utf-8')
obj = Products.objects.all()
first_obj = obj.filter(serial_number=query)
print(first_obj)

Make sure you really get query from the Ajax, I would get it like this:

query = request.POST.get('serial_numeber')

CodePudding user response:

so if you read Abdul Aziz Barkat's comment, the problem was that the query was sent incorrectly from the front end, the problem was that i was using the stringify method on data which was ALERADY a string so i was looking for "data" instead of data which is why i was getting error 404 from the server

  • Related