# fetch data

{% file src="https://664948176-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2FdX27l90MHtjXhtBupXys%2Fuploads%2FjYqZaEmEuIqNmhWdQsVU%2Fmyapp.zip?alt=media&token=fa254789-a631-4f7b-b0a2-dad1fb303aac" %}



models.py

```
from django.db import models
from django.utils import timezone

class SalesOrderInfo(models.Model):
    order_number = models.PositiveIntegerField(default=1, unique=True)
    customername = models.CharField(max_length=50)
    address = models.CharField(max_length=50)
    created = models.DateTimeField(default=timezone.now)


    def __str__(self):
        return f"SalesOrderInfo: {self.order_number}"

class SalesOrderDelivery(models.Model):
    order_info = models.ForeignKey(SalesOrderInfo, on_delete=models.CASCADE, null=True, default=None)
    item = models.CharField(max_length=50)
    quantity = models.PositiveIntegerField(default=0)
    price = models.DecimalField(max_digits=10, decimal_places=2)
  

    def __str__(self):
        return f"SalesOrderDelivery: {self.item} - {self.quantity}"

class DeliveryOrderInfo(models.Model):
    sales_order_number = models.PositiveIntegerField()
    customername = models.CharField(max_length=50)
    address = models.CharField(max_length=50)

    def __str__(self):
        return f"DeliveryOrderInfo: {self.sales_order_number}"

class DeliveryOrderItem(models.Model):
    delivery_order_info = models.ForeignKey(DeliveryOrderInfo, on_delete=models.CASCADE)
    item = models.CharField(max_length=50)
    quantity = models.PositiveIntegerField(default=0)

    def __str__(self):
        return f"DeliveryOrderItem: {self.item} - {self.quantity}"

```

**set static file configuration**&#x20;

```
STATIC_URL = 'static/'
STATICFILES_DIRS = [
    BASE_DIR / 'static',
]
STATIC_ROOT=(BASE_DIR/ "assets/")

MEDIA_URL = '/media/'
MEDIA_ROOT = os.path.join(BASE_DIR, 'assets/media/')
```

admin.py

```
from django.contrib import admin
from django.forms import inlineformset_factory
from .models import (
    SalesOrderInfo,
    SalesOrderDelivery,
    DeliveryOrderInfo,
    DeliveryOrderItem,
)

class SalesOrderDeliveryInline(admin.TabularInline):
    model = SalesOrderDelivery

class SalesOrderInfoAdmin(admin.ModelAdmin):
    inlines = [SalesOrderDeliveryInline]

class DeliveryOrderItemInline(admin.TabularInline):
    model = DeliveryOrderItem

class DeliveryOrderInfoAdmin(admin.ModelAdmin):
    inlines = [DeliveryOrderItemInline]

    class Media:
        js = ('js/fetch_sales_order_info.js',)
        defer = True  # Add the defer attribute

admin.site.register(SalesOrderInfo, SalesOrderInfoAdmin)
admin.site.register(DeliveryOrderInfo, DeliveryOrderInfoAdmin)

```

**views.py**

```
from django.shortcuts import render
from django.http import HttpResponse

# Create your views here.


def index (request):
    return HttpResponse('h')

from django.http import JsonResponse
from django.views.decorators.csrf import csrf_exempt
from .models import SalesOrderInfo, SalesOrderDelivery

@csrf_exempt
def get_sales_order_info(request):
    if request.method == 'POST':
        sales_order_number = request.POST.get('sales_order_number')
        try:
            sales_order_info = SalesOrderInfo.objects.get(order_number=sales_order_number)
            data = {
                'customername': sales_order_info.customername,
                'address': sales_order_info.address,
            }
            return JsonResponse(data)
        except SalesOrderInfo.DoesNotExist:
            return JsonResponse({})
@csrf_exempt
def get_sales_order_info(request):
    if request.method == 'POST':
        sales_order_number = request.POST.get('sales_order_number')
        try:
            sales_order_info = SalesOrderInfo.objects.get(order_number=sales_order_number)
            data = {
                'customername': sales_order_info.customername,
                'address': sales_order_info.address,
            }
            return JsonResponse(data)
        except SalesOrderInfo.DoesNotExist:
            return JsonResponse({})



@csrf_exempt
def fetch_sales_order_delivery(request):
    order_number = request.GET.get('order_number')
    sales_order_info = SalesOrderInfo.objects.filter(order_number=order_number).first()

    if not sales_order_info:
        raise Http404("Sales order not found")

    sales_order_delivery_items = SalesOrderDelivery.objects.filter(order_info=sales_order_info)
    unique_items = sales_order_delivery_items.values('item').distinct()
    items = [{'item': item['item'], 'quantity': sales_order_delivery_items.filter(item=item['item']).values('quantity').first()['quantity']} for item in unique_items]

    return JsonResponse(items, safe=False)
```

urls.py

```
from django.urls import path
from . import views

urlpatterns = [
    path('',views.index,name='index'),
    path('get_sales_order_info/', views.get_sales_order_info, name='get_sales_order_info'),
    
    path('fetch_sales_order_delivery/', views.fetch_sales_order_delivery, name='fetch_sales_order_delivery'),

]
```

static/js/fetch\_sales\_order\_info.js

```
(function($) {
    $(document).ready(function() {
      $('#id_sales_order_number').on('change', function() {
        var orderno = $(this).val();
        if (orderno) {
          $.ajax({
            type: 'POST',
            url: '/myapp/get_sales_order_info/',
            data: {
              'sales_order_number': orderno,
              'csrfmiddlewaretoken': '{{ csrf_token }}'
            },
            success: function(data) {
              if (data.customername) {
                $('#id_customername').val(data.customername);
                $('#id_address').val(data.address);
              } else {
                $('#id_customername').val('');
                $('#id_address').val('');
              }
            },
            error: function() {
              // Handle error case
            }
          });
        } else {
          $('#id_customername').val('');
          $('#id_address').val('');
        }
      });
    });
  })(jQuery);
  
  
  
  (function($) {
  $(document).ready(function() {
    $('#id_sales_order_number').on('change', function() {
      var orderno = $(this).val();
      if (orderno) {
        fetchSalesOrderDelivery(orderno); // Call the function to fetch delivery items
      }
    });

    // Function to fetch sales order delivery items
    function fetchSalesOrderDelivery(orderno) {
      $.ajax({
        type: 'GET',
        url: '/myapp/fetch_sales_order_delivery/',
        data: {
          'order_number': orderno
        },
        success: function(data) {
          populateSelectBoxes(data);
        },
        error: function() {
          // Handle error case
        }
      });
    }

    // Function to populate select boxes with fetched data
    function populateSelectBoxes(data) {
      $('.dynamic-deliveryorderitem_set select[id^="id_deliveryorderitem_set-"][id$="-item"]').each(function() {
        var selectBox = $(this);
        selectBox.empty(); // Clear existing options

        $.each(data, function(index, item) {
          selectBox.append($('<option></option>').attr('value', item.item).text(item.item));
        });
      });
    }
  });
})(jQuery);













  
```

\












\
