Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/python/348.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181

Warning: file_get_contents(/data/phpspider/zhask/data//catemap/0/azure/11.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Python Django表单不保存输入-提交后刷新_Python_Django_Django Models_Django Forms_Django Views - Fatal编程技术网

Python Django表单不保存输入-提交后刷新

Python Django表单不保存输入-提交后刷新,python,django,django-models,django-forms,django-views,Python,Django,Django Models,Django Forms,Django Views,我正在尝试创建一个有两个下拉菜单的网站:Department和coursenumber。下拉菜单的数据来自我的SQL数据库的courses表。现在,我的网站已正确初始化,并在下拉菜单中显示正确的选项。但是,当用户在下拉菜单中选择一个选项并提交他们的选择时,网站将作为一块空白板重新加载,因此他们的选择不会被保存或处理。错误在CourseForm表单中的某个地方,因为我有另一个表单,它以不同的方式创建,但工作得非常完美。CourseForm/其关联模型有什么问题 models.py forms.py

我正在尝试创建一个有两个下拉菜单的网站:Department和coursenumber。下拉菜单的数据来自我的SQL数据库的courses表。现在,我的网站已正确初始化,并在下拉菜单中显示正确的选项。但是,当用户在下拉菜单中选择一个选项并提交他们的选择时,网站将作为一块空白板重新加载,因此他们的选择不会被保存或处理。错误在CourseForm表单中的某个地方,因为我有另一个表单,它以不同的方式创建,但工作得非常完美。CourseForm/其关联模型有什么问题

models.py

forms.py

views.py

编辑: 在将方法从GET更改为POST之后,我仍然面临同样的问题。我使用views.py代码手动设置args字典,发现无论form_CourseForm.is_的结果如何,都不会向args添加任何内容,即使我在两个下拉菜单上都进行了选择。这对我来说毫无意义,但似乎form_CourseForm根本不起作用

def home(request):
    context = {}
    res = None
    if request.method == 'POST':
        form_CourseForm = CourseForm(request.POST)
        form_prof_fn = SearchForm_prof_fn(request.POST)
        form_prof_ln = SearchForm_prof_ln(request.POST)
        args = {}
        if form_CourseForm.is_valid():
            data = form_CourseForm.cleaned_data
            if data['dept']:
                args['dept'] = "Math" #doesn't work
            if data['course_num']:
                args['course_num'] = "100" #doesn't work
        else:
            args['dept'] = "History" #doesn't work
        args['rv'] = "123" #does work, so issue isn't with args itself
index.html

还有html


六羟甲基三聚氰胺六甲醚。。。通常情况下,表单是通过POST方法提交的,您有if request.method='GET'-您是指if request.method==''POST'吗?您必须更改请求类型。您编写的逻辑需要在POST方法中,更改它们,以及html页面中的form方法,以便POST而不是Get。您的模板是什么样子的?course_num和dept都不是必需的,因此您的表单可以在这两个字段都为空的情况下有效。@Daniel Roseman我刚刚上传了html模板的相关部分。是的,这是真的,但是,即使我选择了两个下拉菜单,这个问题也会发生。请注意,您似乎没有将参数传递回模板,因此它将永远不会显示。我做了这些更改,这有助于网站的结构,但问题仍然存在。我在编辑部分的问题底部添加了额外的上下文。你说输入没有正确保存??您没有保存它们,因此它没有保存,您必须编写MyModel.objects.create,才能保存到要保存@Person10559的数据库对不起,为什么我需要.create函数?现在的问题是,由于某种原因,视图无法识别CourseForm的输入,因此无法识别或存储用户输入。我不需要将输入保存到数据库中,我只需要将它们添加到args字典中以生成一个表。我认为form_CourseForm=CourseFormrequest.POST应该存储用户输入,但事实并非如此。我不需要更改下拉菜单中的选项,这些列表应该保持不变@exprator您是否尝试打印数据并检查您是否获得了任何信息?我的HTML模板中有一个方法,我刚刚添加到我的问题中,用于打印args字典,因此,是的,即使我在两个下拉菜单上进行选择,我也可以看到args中没有添加任何部门或课程编号。
from django import forms
from django_select2.forms import ModelSelect2Widget
from .models import Dept, Course_num

class CourseForm(forms.Form):
    dept = forms.ModelChoiceField(
        queryset=Dept.objects.distinct().\
            order_by('dept').exclude(dept__isnull=True),
        required=False,
        empty_label="No preference",
        label=u"Department")

    course_num = forms.ModelChoiceField(
        queryset=Course_num.objects.distinct().\
            order_by('course_num').exclude(course_num__isnull=True),
        required=False,
        empty_label="No preference",
        label=u"Course Number")
from django.shortcuts import render
from django import forms
from .models import Dept, Course_num
from .forms import CourseForm 
...
class Working_Form(forms.Form):
    working_info = forms.ChoiceField(choices=WORKING_DATA_LIST, required=False)
    show_args = forms.BooleanField(label='Show args_to_ui',
                               required=False)

def home(request):
    context = {}
    res = None
    if request.method == 'POST':
        form_CourseForm = CourseForm(request.POST)
        working_info = Working_Form(request.POST)
        args = {}
        if form_CourseForm.is_valid():
            data = form_CourseForm.cleaned_data
            if data['dept']:
                args['dept'] = data['dept']
            if data['course_num']:
                args['course_num'] = data['course_num']
        if working_info.is_valid():
            ...
            if working_info.is_valid.cleaned_data['show_args']:
                context['args'] = 'args_to_ui = ' + json.dumps(args, indent=2)

        if ('dept' in args) == ('course_num' in args): 
            try:
                results = process_inputs(args)
            except Exception as e:
                print('Exception caught')
        else:
            context['err'] = forms.ValidationError("Error")
            results = None

    else:
        form_CourseForm = CourseForm()
        working_info = Working_Form()
    # handle situation when results is None (i.e. no inputs have been entered)

    if results is None:
        context['result'] = None

    else: #process output info
        context['num_results'] = len(results)

    context['form_CourseForm'] = form_CourseForm
    context['working_info'] = working_info
    return render(request, 'index.html', context)
def home(request):
    context = {}
    res = None
    if request.method == 'POST':
        form_CourseForm = CourseForm(request.POST)
        form_prof_fn = SearchForm_prof_fn(request.POST)
        form_prof_ln = SearchForm_prof_ln(request.POST)
        args = {}
        if form_CourseForm.is_valid():
            data = form_CourseForm.cleaned_data
            if data['dept']:
                args['dept'] = "Math" #doesn't work
            if data['course_num']:
                args['course_num'] = "100" #doesn't work
        else:
            args['dept'] = "History" #doesn't work
        args['rv'] = "123" #does work, so issue isn't with args itself
<html>
    <head>
        <title>Website</title>
        <link rel="stylesheet" type="text/css" href="{% static "/main.css" %}" />
    </head>
    <body>
        <div id="header">
            <h1>Website</h1>
        </div>
        <div class="frame">
            <form method="post">
                {% csrf_token %}
                <table class="form_CourseForm">
                    {{ form_CourseForm }}
                </table>                                  
                <p>and/or</p>
                <table class="Working Form">
                    {{ working_form }}
                </table>
                <input type="submit" value="Submit" />
            </form>
        </div>

        {% if args %}
        <div class="args">
            <pre>{{ args }}</pre>
        </div>
        {% endif %}

...code to print output table...
    </body>
</html>
def home(request):
    context = {}
    res = None
    if request.method == 'POST':
        form_CourseForm = CourseForm(request.POST)
        working_info = Working_Form(request.POST)
        args = {}
        if form_CourseForm.is_valid():
            if request.POST['dept']:
                args['dept'] = request.POST['dept']
            if request.POST['course_num']:
                args['course_num'] = request.POST['course_num']
        if working_info.is_valid():
            ...

        if ('dept' in args) == ('course_num' in args): 
            try:
                results = process_inputs(args)
            except Exception as e:
                print('Exception caught')
        else:
            context['err'] = forms.ValidationError("Error")
            results = None
        return render(request,'template.html',{'args':args})
    else:
        form_CourseForm = CourseForm()
        working_info = Working_Form()
<form method='post' action='' ...... >