代码之家  ›  专栏  ›  技术社区  ›  Nelson Mongare

Django表单字段未加载到模板上

  •  0
  • Nelson Mongare  · 技术社区  · 6 年前

    所讨论的表单根本不会呈现表单字段,尽管没有引发任何异常(我假设这意味着错误不是视图或表单错误)。所以我的问题是,还有什么可能导致这样的错误? 形式:

    class HandInForm(forms.ModelForm):
        class Meta:
            model = AssignmentsHandedIn
            fields = ['assignment', 'user_hand_in']
    class ResourceForm(forms.ModelForm):
        """Form definition for File."""
        class Meta:
            """Meta definition for Fileform."""
    
            model = Resources
            fields = ['file']
            widgets = {
                'file': forms.FileInput(attrs={"class": "form-control input"}),
            }
    

    视图:

    def hand_in(request, assignment_id):
        assignment_actual = Assignments.objects.get(pk=assignment_id)
        class_assignment = assignment_actual.class_related
        if request.method == "POST":
            assignment_form = HandInForm(data=request.POST)
            resource_form = ResourceForm(data=request.POST)
            if assignment_form.is_valid() and resource_form.is_valid():
                assignment = assignment_form.save()
                assignment.user_hand_in = request.user
                assignment.assignment = assignment_actual
                resource = resource_form.save()
                resource.assignments = assignment
                resource.class_related = class_assignment
            else:
                print(assignment_form.errors, resource_form.errors)
        else:
            assignment_form = HandInForm()
            resource_form = ResourceForm()
        return render(request, "DC/handin.html", {'assignment_form': assignment_form, 'resource_form': resource_form})
    

    模板:

        {% extends "DC/base.html" %}
        {% block body_block %}
        <br><br><br><br>
        <h1 class="titley">New Resource</h1>
        <form class="jumbotron" enctype="multipart/form-data" method="post">
            {% csrf_token %}
            {{ form.as_p }}
            <button type="submit" class="btn btn-primary" name="button">Create</button>
        </form>
        <script>
            var editor = new MediumEditor('.editable');
        </script>
    
        {% endblock body_block %
    
    }
    
    2 回复  |  直到 6 年前
        1
  •  2
  •   Lemayzeur    6 年前

    那是因为你给表格命名 HandInForm() ResourceForm() 分别是:

    assignment_form = HandInForm()
    resource_form = ResourceForm()
    

    但是,您使用 form 在模板中

    {{ form.as_p }}
    

    改为:

    {{ assignment_form.as_p }}
    
    {{ resource_form.as_p }}
    
        2
  •  0
  •   seuling    6 年前

    您的视图用不同的名称发送表单。

    {'assignment_form': assignment_form, 'resource_form': resource_form}

    但是你用 form . 你应该使用你定义的名字。喜欢

    {{ assignment_form.as_p }} 我是说, {{ resource_form.as_p }}