1

Hi everyone I want to save the html array for dynamic inputs into the database using django, I have three dynamic inputs on my form, here is my code:

Views.py

def generatescripts(request):
    # if this is a POST request we need to process the form data
    if request.method == 'POST':
        # create a form instance and populate it with data from the request:
        form = GenerateScriptsForm(request.POST)
        # check whether it's valid:
        if form.is_valid():
            # process the data in form.cleaned_data as required
            # ...
            # redirect to a new URL:

            Step = request.POST.getlist('Step')

            for el in Step:
                form.save()

            return HttpResponseRedirect('/thanks/')

    # if a GET (or any other method) we'll create a blank form
    else:
        form = GenerateScriptsForm()

    return render(request, 'page/generatescripts.html', {'form': form})

forms.py

from django import forms
from .models import Steps

class GenerateScriptsForm(forms.ModelForm):

    class Meta:
        model= Steps
        fields = "__all__" 

models.py

from django.db import models

# Create your models here.
class Steps(models.Model):

    Step = models.CharField(max_length=200,default='0')
    Description = models.CharField(max_length=200,default='0')
    Result = models.CharField(max_length=200,default='0')

multiple inputs with the same name and I cant save with my code, this code only save one value from the array generatescripts.html

<input type="button" value="Preview form" class="add" id="preview" />
<input type="button" value="Add a Step" class="add" id="add" />

    <script>
 $(document).ready(function() {
    $("#add").click(function() {
        var lastField = $("#buildyourform div:last");
        var intId = (lastField && lastField.length && lastField.data("idx") + 1) || 1;
        var fieldWrapper = $("<div class=\"fieldwrapper\" id=\"field" + intId + "\"/>");
        fieldWrapper.data("idx", intId);
        var step = $("<input type=\"text\" name= \"Step\" placeholder= \"Step\" class=\"fieldname\" />");
        var description = $("<input type=\"text\" name= \"Description\" placeholder= \"description\" class=\"fieldname\" />");
        var expectedresult = $("<input type=\"text\" name= \"Result\" class=\"fieldname\" />");

        var fType = $("<select class=\"fieldtype\"><option value=\"checkbox\">Checked</option><option value=\"textbox\">Text</option><option value=\"textarea\">Paragraph</option></select>");
        var removeButton = $("<input type=\"button\" class=\"remove\" value=\"-\" />");
        removeButton.click(function() {
            $(this).parent().remove();
        });
        fieldWrapper.append(step);
        fieldWrapper.append(description);
        fieldWrapper.append(expectedresult);
        fieldWrapper.append(fType);
        fieldWrapper.append(removeButton);
        $("#buildyourform").append(fieldWrapper);
    });
    $("#preview").click(function() {
        $("#yourform").remove();
        var fieldSet = $("<fieldset id=\"yourform\"><legend>Your Form</legend></fieldset>");
        $("#buildyourform div").each(function() {
            var id = "input" + $(this).attr("id").replace("field","");
            var label = $("<label for=\"" + id + "\">" + $(this).find("input.fieldname").first().val() + "</label>");
            var input;
            switch ($(this).find("select.fieldtype").first().val()) {
                case "checkbox":
                    input = $("<input type=\"checkbox\" id=\"" + id + "\" name=\"" + id + "\" />");
                    break;
                case "textbox":
                    input = $("<input type=\"text\" id=\"" + id + "\" name=\"" + id + "\" />");
                    break;
                case "textarea":
                    input = $("<textarea id=\"" + id + "\" name=\"" + id + "\" ></textarea>");
                    break;    
            }
            fieldSet.append(label);
            fieldSet.append(input);
        });
        $("body").append(fieldSet);
    });
});
    </script>
        <input type="submit"  />

</form>

{% endblock %}
2
  • so what's the problem? also, put your HTML file and Steps model in question Commented May 13, 2018 at 5:58
  • Well its not working, now I show these file can you help me? the code is only saving one value from the html array, I mean using a select every post add a row into the database even if I post multiple inputs with the same name Commented May 13, 2018 at 6:30

1 Answer 1

2

I just read your view function, change it to this:

def generatescripts(request):
    if request.method == 'POST':
        Steps = request.POST.getlist('Step')
        Results = request.POST.getlist('Result')
        Descriptions = request.POST.getlist('Description')

        # FIXME: number of each field should equal
        c = min([len(Steps), len(Results), len(Descriptions)])
        for i in range(c):
            # create a form instance and populate it with data from the request:
            form = GenerateScriptsForm({'Step': Steps[i], 'Result': Results[i], 'Description': Descriptions[i]})
            # check whether it's valid:
            if form.is_valid():
                form.save()
        return HttpResponseRedirect('/thanks/')

    else:
        form = GenerateScriptsForm()

    return render(request, 'page/generatescripts.html', {'form': form})
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.