【问题标题】:HTML select multiple values from styled list with checkboxesHTML从带有复选框的样式列表中选择多个值
【发布时间】:2020-01-10 12:18:20
【问题描述】:

我有一个 django 项目,其中包含我想要包含在发布请求中的用户列表。请注意,只有我检查过的用户才应该包含在基于 django 函数的视图中的发布请求中。

我想知道如何将已检查用户的值获取到基于 django 发布请求函数的视图中?

和这张图不完全一样,但是复选框和用户部分是一样的,我不知道如何将本地文件放入堆栈溢出!

项目页面:

@login_required
def projectPage(request):
    obj = Project.objects.filter(canview__user=request.user)
    assignments = Assignment.objects.filter(canview__user=request.user)
    allstudents = UserProfile.objects.all()
    username = request.user
    context = {
        'object': obj,
        'MyName': username,
        'Assignments': assignments,
        'students': allstudents
    }
    return render(request, 'allProjects.html', context)

POST 请求页面:

@login_required
def create_project(request):
    if request.method == 'POST':

        name = request.POST.get('Project-Name')
        description = request.POST.get('Project-Description') 
        parent_assignment = Assignment.objects.get(pk=request.POST.get('Project-ParentAssignmentID'))

        membersInProject == SOMETHING

        project = Project(name=name, description=description, parent_assignment=parent_assignment, members = membersInProject)


        project.save()

        return redirect('allaStudieplaner')

在 HTML 模板中:

{% for student in students %}
                        <div class="custom-control custom-checkbox">

                            <span class="d-flex align-items-center">


                                <div style="margin-right: 10px">
                                    <div class="circle">
                                        <span class="initials" , style="color: #ffffff"> {{ elev.user|capfirst|first }}
                                        </span>
                                      </div>
                                </div>

                              <div style="width: 300px">

                                <span class="h6 mb-0" data-filter-by="text">{{elev.user|capfirst}}</span>
                              </div>
                              <div class="checkboxx"> <input type="checkbox" unchecked>
                                <style>
                                .checkerName {
                                  margin-left: 10px
                                }

                                .checkboxx {
                                  align-content: flex-end;
                                  margin-left: 300px
                                }
                                </style> </div>

                            </span>
                          </label>
                        </div>
                        {% endfor %}

【问题讨论】:

    标签: javascript jquery html css django


    【解决方案1】:

    输入属性

    您需要能够读取 django 文件中字段的name。通过将name 属性添加到input type="checkbox" 元素来做到这一点。

    然后您会想知道哪个学生与该复选框相关联。通过在复选框的value 属性中添加学生的一些数据来做到这一点。

    <input type="checkbox" name="students[]" value="{{ student.name }}">
    

    注意到students[] 而不是students?这是因为应该能够选中学生的多个复选框。并且通过在名称后使用[] 确保复选框值将在array 中发送,每个选中的input 值都包括在内。否则,您只需在单个值中覆盖每个 students

    表格

    当你想向服务器提交一些东西(有或没有 JS)你需要form 元素。这个form 元素需要包裹在input 元素周围,以便input 元素的值是form 的一部分。

    form 元素上指定actionmethod 属性以指示请求必须发送到的位置以及它应该使用的什么方法这样做。

    现在您还需要一种方法来触发form 进行提交。你可以在 JS 中做到这一点,但现在我只使用 HTML 来显示它。

    加一个input type="submit"或者button type="submit",后者更适合做造型,在表格里加上。通常放在最后,表示没有更多的字段需要填写,下一步是提交。

    <form id="create-project-form" action="create_project" method="POST">
        {% for student in students %}
           ...
           ...
        {% endfor %}
        <button type="submit">Send the form</button>
    </form>
    

    Fetch 和 XMLHTTPRequest

    注意:我无法对此进行测试,也没有 Django 经验,因此这将是根据我在示例中找到的内容来设置 JS 端的指南。

    在 JavaScript 中有两种方法可以将值发送到服务器。 FetchXMLHTTPRequest。前者是向服务器发送 HTTPRequest 的最新技术,而旧版浏览器支持后者。 所以在这种情况下,我们将使用 Fetch

    首先,我们创建将使用fetch 发送数据的函数。该函数采用urldata 参数。 url 是我们发送请求的地方,data 是必须发送的值。

    function postForm(url, data) {
        return fetch(url, {
            method: 'POST',           // Sending as POST
            body: data,               // Include the data 
            credentials: 'include',
            headers: {
                'Content-Type': 'multipart/form-data',  // Tell the server what kind of data to expect.
                'X-Requested-With': 'XMLHttpRequest'    // Tell the server that this is a XMLHttpRequest. Django needs this.
            }
        }).then((response) => {
            if (response.status === 200) {              // Check if request has succeeded.
                return response.text();                 // If so return the response in a string.
            }
            throw new Error(response.status);           // Else throw an error.
        }).catch((error) => {                           // catch is called whenever an error occurs. 
            console.log(error);                         // Show the error.
        });
    };
    

    太好了,fetch 功能已经到位。现在我们继续执行应该从表单中获取数据并发送请求的函数。

    下面我创建了submitCreateProjectForm 函数。它将与submit 事件挂钩,并且只能在提交表单时调用。 event 参数将为我们提供有关什么事件以及哪个表单已提交的信息。

    然后我们可以将表单的数据存储在FormData 实例中。 FormData 将从表单中获取所有namesvaluesinput 元素并将其存储。

    在您获得名称和值后,使用我们刚刚创建的 fetch 函数将请求发送到服务器。

    function submitCreateProjectForm(event) {
        const form = event.target;            // The form that has been submitted
        const data = new FormData(form);      // Extract the data from the form
        const url = '/destinationtosendto/';  // Define your url to send the form data to.
        postForm(url, data);                  // And send!
        event.preventDefault();               // Stop form from default behavior so the page won't reload.
    };
    

    每当用户提交表单时,您都会想发送一些东西。因此,请在我们制作的表单上收听submit 事件。

    const form = document.getElementById('create-project-form');   // Get the form element.
    if (form !== null) {                                           // Check if the form element has been found.
        form.addEventListener('submit', submitCreateProjectForm)   // If so then add an event listener to it. In this case listen for submit.
    }
    

    这应该在表单提交时向服务器发送一个请求。现在我不知道将数据发送到的 URL,因为我从未使用过 Django,也不知道您项目的 endpoints。这将由你来弄清楚。

    祝你好运,祝你有美好的一天!

    【讨论】:

    • 禁止直接分配到多对多集合的前端。改用students.set()。
    • 这是什么意思?
    • 我在尝试您的代码时遇到了这个错误 :) 非常感谢您的帮助!
    • 很高兴为您提供帮助。我以前从未使用过 Django,所以这也是我的学习经历。在做了一些研究之后,我发现我们必须对 Django 执行更多步骤来处理form 的信息。查看这些链接 MDN Django Form TutorialWorking with forms | Django。如果你真的想使用 HTMLRequest,我们可以用一些 JavaScript 修改代码。阅读这些链接并尝试一下。
    • 谢谢,你能告诉我我们如何使用一些javascript来解决这个问题吗?
    猜你喜欢
    • 1970-01-01
    • 2017-09-17
    • 2023-04-02
    • 2019-11-24
    • 1970-01-01
    • 1970-01-01
    • 2021-06-06
    • 2010-12-02
    • 1970-01-01
    相关资源
    最近更新 更多