首页 > 解决方案 > 如何将相关数据返回到外键 django ajax

问题描述

我有一个项目,有两种型号,一种用于计算机功能,另一种用于计算机发票

class ComputerFeature(models.Model):
    car_model = models.CharField(max_length=50)
    CPU = models.CharField(max_length=30)
    RAM = models.CharField(max_length=30)
    #others

class CustomerInvoice(models.Model):
    customer = models.CharField(max_length=50)
    model = models.ForeignKey(ComputerFeature, on_delete=models.CASCADE)
    order = models.IntegerField(default=1)
    price = models.IntegerField()

这是我的模板

<form method='POST'>{% csrf_token %}
<table class="table">
  <thead>
    <tr>
      
      {{ form.customer.errors }}
      <th class="float-left" id="customer">Customer  :  {{ form.customer  }}</th>

    </tr>
  </thead>
</table>
<table class="table">
  <thead>
    <tr>
      <td><div class="form-group floating-label" id="modeling">
                            {{ form.model | add_class:'form-control select2-list ' | attr:'id:model'}}
                            
</div></td>

                
    </tr>
    <tr>
        {{ form.order.errors }}
      <td scope="col">quantity</td>
      <td scope="col" id="order">{{form.order}}</td>
                
    </tr>
    <tr>
      <td scope="col">CPU</td>
      <td scope="col" style="width: 50%" id="cpu">
      <--! i want to return CPU here before submiting the form -->
    </tr>
    <tr>

      <td scope="col">RAM</td>
      <--! i want to return CPU here before submiting the form -->
    
    </tr>
    <tr>
        {{ form.Hard.errors }}
      <td scope="col">Hard</td>
      <td scope="col" id="hard">{{form.model.Hard}}</td>
    
    </tr>
    <tr>
      <td scope="col">Graphic</td>
      <--! i want to return CPU here before submiting the form -->
    
    </tr>
    <tr>
        {{ form.price.errors }}
      <td scope="col">price/td>
      <td scope="col" id="price">{{form.price}}</td>
    
    </tr>

  </thead>

</table>

<input type="submit" name="save" value="selling" class="btn btn-primary btn-block" id="submit">

</div>
</div>

</form>

我需要在提交表单之前从 ComputerFeature 返回 CPU、RAM 和其他功能,还记得吗?

这是我的表单类

class CustomerInvoice(forms.ModelForm):
   model = forms.ModelChoiceField(queryset=ComputerFeature.objects.all().order_by('-date'),empty_label='models')
   class Meta:
      model = CustomerInvoice
      fields = ['customer','model','price','order']

我知道我应该使用 ajax 请求,但我不知道如何实现它!

谢谢你的帮助

标签: javascriptdjangoajaxasynchronous

解决方案


推荐阅读