如何使用JavaScript(jQuery)提交Django表单

时间:2017-06-15 19:39:32

标签: javascript jquery django submit form-submit

我正在开发一个网络应用项目。我的文件上传有问题。然后我意识到我的队友改变了 create_form.html 中的默认提交按钮。它的工作方式类似于 5。 6。,我也需要收集文件数据。

我应该在.js文件中添加什么来提交和保存文件?

  1. forms.py

    class DocumentUpload(forms.ModelForm):
        class Meta:
            model = Form
            fields = ('file',)
    
  2. models.py

    class Form(TimeStampedModel, TitleSlugDescriptionModel):
        author = models.ForeignKey(User, on_delete=models.CASCADE)
        title = models.CharField(max_length=512)
        is_final = models.BooleanField(default=False)
        is_public = models.BooleanField(default=False)
        is_result_public = models.BooleanField(default=False)
        file = models.FileField(null=True, blank=True)
    
        def __str__(self):
            return self.title
    
        def get_absolute_url(self):
            return reverse('form-detail', kwargs={'slug': self.slug})
    
  3. views.py

    def create_form(request):
        if request.method == 'POST':
            user = request.user
            data = ParseRequest(request.POST)
            print(data.questions())
            print(data.form())
            parsed_form = data.form()
            parsed_questions = data.questions()
    
            # tworzy formularz o podanych parametrach
            formfile = DocumentUpload(request.POST, request.FILES or None)
            if formfile.is_valid():
                form = formfile.save(commit=False)
                print(form)
                form.author = user
                form.title = parsed_form['title']
                form.is_final = parsed_form['is_final']
                form.is_result_public = parsed_form['is_result_public']
                form.description = parsed_form['description']
                form.save()
                # zapisuje pytania z ankiety wraz z odpowienimi pytaniami
                for d in parsed_questions:
                    question = Question(form=form, question=d['question'])
                    question.save()
                    # dla kazdego pytania zapisz wszystkie opcje odpowiadania
                    for opt in d['options']:
                        option = Option(question=question, option=opt)
                        option.save()
                return render(request, 'forms/form_form.html', {})
        else:
            form = DocumentUpload()
            return render(request, 'forms/form_form.html', {'form': form})
    
  4. create_form.html

    在这里,我必须提交{{ form.as_p }}< - 我必须在JS **中提交此输入

        {% block content %}
        <form method="post" id="form" enctype='multipart/form-data'>
        {%csrf_token %}
        <div class="form-group">
             {% csrf_token %}
             <label for="form-title">Tytuł formularza</label>
             <input id="form-title" class="form-control" type="text" 
                                      placeholder="Tytuł" required/>
         </div>
         {{ form.as_p }}
    
         .... more divs ...
    
        <input class="btn btn-default" type="submit" value="zapisz"/>
        </form>
        {% endblock %}
    
  5. collect_data.js

    这是我的函数调用来保存create_form.html的输入而不是:

    <input class="btn btn-default" type="submit" value="zapisz"/>
    

    但我不知道如何保存输入:

    {{ form.as_p }}  
    
     function collect_data() {
     var csrftoken = getCookie('csrftoken');
     var data = {
         form_title: $('#form-title').val(),
         is_final: $('#form-is-final').prop('checked'),
         is_public: $('#form-is-public').prop('checked'),
         is_result_public: $('#form-is-result-public').prop('checked'),
         description: $('#description').val(),
         questions: [],
         num_questions: num_questions,
         csrfmiddlewaretoken: csrftoken
     };
     for (var k = 0; k < num_questions; k++) {
        var my_data = {};
        var question_k = $('#question-' + k);
    
        my_data.question = question_k.find('#question-text').val();
        my_data.answer_type = question_k.find('select').val();
        my_data.options = [];
    
        for (var j = 0; j < num_question_options[k]; j++) {
            var answer = question_k.find('#answer-' + j).val();
            if (answer !== '') {
                my_data.options.push(answer)
            }
        }
        my_data.num_options = my_data.options.length;
        data.questions.push(my_data)
    }
    return data
    }
    
  6. submit_data_create.js

    $(document).ready(function (event) {
        $(document).on('submit', '#form', function (e) {
            e.preventDefault();
            var data = collect_data();
            $.ajax({
                type: 'POST',
                url: '/form/create/',
                data: data,
                success: function (data, textStatus) {
                    window.location.href = '/form/list/'
                },
                fail: function (response) {
                    alert('Coś poszło nie tak.');
                }
            });
        })
    });
    

0 个答案:

没有答案