Ни один из них не сохраняется в админке django

productscreate.html

<form data-bind="submit: save" method="post">  
  {% csrf_token %}
   
    <table border="1">
<tr>
    <td>Title:
    <input type="text" name="title" id="title" data-bind="value: $data.title"></td>
    <br>
</tr>
<tr>
    <td>Description:
    <textarea name="description" id="description" data-bind="value: $data.description">Description</textarea></td>
    <br>
</tr>
<tr>
    <td>Image:
    <input type="file" name="image" id="image" ></td>
    <br>
</tr>

<tr>
    <td><button type="button" id="submit" data-bind="click: save">Submit</button></td>
</tr>

</table>
</form>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.5.1/jquery.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/knockout/3.5.0/knockout-min.js"></script>
<script>
  function getCookie(name) {
      let cookieValue = null;
      if (document.cookie && document.cookie !== '') {
          const cookies = document.cookie.split(';');
          for (let i = 0; i < cookies.length; i++) {
              const cookie = cookies[i].trim();
              // Does this cookie string begin with the name we want?
              if (cookie.substring(0, name.length + 1) === (name + '=')) {
                  cookieValue = decodeURIComponent(cookie.substring(name.length + 1));
                  break;
              }
          }
      }
      return cookieValue;
  }
  const csrftoken = getCookie('csrftoken'); 
</script>
<script>

  var ViewModel = function () {

    var self = this;
    self.title = ko.observable("");
    self.description = ko.observable("");
 

    var FormData = {
        title: self.title,
        description: self.description,
  
    };
    console.log(FormData);
    self.save = function () {
       
        $.ajax({
            type: "POST",
            url: 'http://127.0.0.1:8000/productsadd',                                           
            data: FormData,
            contentType: "application/json",
            headers: {'X-CSRFToken': csrftoken},
            cache: false,
            enctype: "multipart/form-data",
            //processData: false,
            success: function (FormData) {
              alert("successfull")
              window.location = '{% url "productslist" %}'; 
            },
            error: function () {
                alert("fail");
            }
        });
    };
    };
    ko.applyBindings(new ViewModel())

    </script>

views.py

class ProductsCreate(CreateView):
   model = Products
   template_name = "productscreate.html"
   fields = ['title', 'description', 'image']
   success_url=reverse_lazy('productslist')

def productsAdd(request):
    if request.is_ajax and request.method == "POST":
        product=Products()
        product.title = request.POST.get('title')
        product.description = request.POST.get('description')
        # product.image = request.FILES['image']
        product.save()
        return render(request,'productslist.html')
    else:
        return render(request,'productscreate.html')

class ProductsDetailView(DetailView):
     template_name = "productsdetail.html"
     queryset = Products.objects.all()
     context_object_name = 'products'
     model = Products

models.py

class Products(models.Model):
    title = models.CharField(max_length=200,null=True)
    description = models.CharField(max_length=200,null=True)
    image = models.FileField(blank=True)

    def __str__(self):
         return str(self.title)

enter image description here Когда я создаю товар в форме, он сохраняется как нет в админке django Я не знаю где проблема. Я привел html с knockout js и ajax, представлениями и моделями. Я хочу отправить название, описание и изображение в django admin используя форму в createproduct html Пожалуйста, помогите мне решить эту проблему Заранее спасибо

Вернуться на верх