Django表单未保存输入-提交后刷新 [英] Django form not saving inputs- refreshes upon submission

查看:61
本文介绍了Django表单未保存输入-提交后刷新的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试创建一个带有两个下拉菜单的网站:部门和课程号。下拉菜单的数据来自我的SQL数据库的课程表。现在,我的网站已正确初始化,并在下拉菜单中显示了正确的选项。但是,当用户在下拉菜单中选择一个选项并提交他们的选择时,该网站将重新加载为空白状态,因此不会保存或处理他们的选择。错误出现在CourseForm表单中的某处,因为我还有另一种表单(Working_Form),该表单以不同的方式创建,但效果很好。 CourseForm /它的关联模型怎么了?



models.py



<$ p来自django.db的$ p> 导入模型

类Dept(models.Model):
dept = models.CharField(max_length = 255,db_column ='dept' )
class Meta:
managed = False
db_table ='courses'
def __str __(self):
返回self.dept

class Course_num(models.Model):
course_num = models.CharField(max_length = 255,db_column ='course_number')
class Meta:
managed = False
db_table ='courses '
def __str __():
return self.course_num

forms.py

 从django导入表单
从django_select2.forms导入ModelSelect2Widget
from .models import Dept,Course_num

class CourseForm(forms.Form):
dept = forms.ModelChoiceField(
queryset = Dept.obje cts.distinct()。\
order_by('dept')。exclude(dept__isnull = True),
required = False,
empty_label = No preference,
标签= u部门)

course_num = form.ModelChoiceField(
queryset = Course_num.objects.distinct()。\
order_by('course_num')。exclude(course_num__isnull = True),必需
= False,
empty_label =无偏好,
label = u课程编号)

views.py

 来自Django .shortcuts import从django导入表单中渲染
从.models import Dept,Course_num
从.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):
上下文= {}
res =无
,如果request.method =='POST':
form_CourseForm = CourseForm(request.POST)
working_info = Working_Form(request.POST)
args = {}
如果form_CourseForm.is_valid():
数据= form_CourseForm.cleaned_data
如果data ['dept']:
args ['dept'] =数据['dept']
if data ['course_num']:
args ['course_num'] = data ['course_num']
if working_info.is_valid():
。 ..
如果working_info.is_valid.cleaned_data ['show_args']:
context ['args'] ='args_to_ui ='+ json.dumps(args,indent = 2)

if(args中的'dept')==(args中的'course_num'):
try:
结果= process_inputs(args)
例外,例如e:
print (捕获到异常)
其他:
context ['err'] = Forms.ValidationError( Err或)
结果=无

其他:
form_CourseForm = CourseForm()
working_info = Working_Form()
#处理结果为无时的情况(即没有输入任何输入)

如果结果为None:
context ['result'] = None

else:#process输出信息
context ['num_results'] = len(结果)

context ['form_CourseForm'] = form_CourseForm
context ['working_info'] = working_info
return render(request,'index。 html',上下文)

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

  def home(request):
context = {}
res = None
如果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#如果data ['course_num']:
args ['course_num'] = 100#不起作用
不起作用
其他:
args ['dept'] =历史#不起作用
args ['rv'] = 123#起作用,所以问题不解决't与args本身

index.html

 < html> 
< head>
< title>网站< / title>
< link rel = stylesheet type = text / css href = {%static /main.css%} />
< / head>
< body>
< div id = header>
< h1>网站< / h1>
< / div>
< div class = frame>
< form method = post>
{%csrf_token%}
< table class = form_CourseForm>
{{form_CourseForm}}
< / table>
< p>和/或< / p>
< table class = Working Form>
{{working_form}}
< / table>
<输入类型= submit value =提交 />
< / form>
< / div>

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

...代码以打印输出表...
< / body>
< / html>


解决方案

  def home (请求):
context = {}
res = None
if request.method =='POST':
form_CourseForm = CourseForm(request.POST)
working_info = Working_Form(request.POST)
args = {}
如果form_CourseForm.is_valid():
如果request.POST ['dept']:
args ['dept'] = request.POST ['dept']
如果有request.POST ['course_num']:
args ['course_num'] = request.POST ['course_num']
如果working_info.is_valid ():
...

if(参数中的'dept')==(参数中的'course_num'):
尝试:
结果= process_inputs( args)
,但异常除外,例如e:
print('抓到异常')
否则:
context ['err'] = Forms.ValidationError( Error)
结果=无
返回render(reque st,'template.html',{'args':args})
其他:
form_CourseForm = CourseForm()
working_info = Working_Form()

以及html

  


I am trying to create a website with two dropdown menus: Department and Course Number. The data for the dropdown menus comes from the "courses" table of my SQL database. Right now my website initializes properly and shows the correct options in the dropdown menus. However, when the user selects an option within the dropdown menus and submits their choices, the website reloads as a blank slate so their selections are not being saved or processed. The error lies somewhere in the CourseForm form because I have another form (Working_Form) that is created in a different way but works perfectly. What is wrong with CourseForm/its associated models?

models.py

from django.db import models

class Dept(models.Model):
    dept = models.CharField(max_length=255, db_column = 'dept')
    class Meta:
        managed = False
        db_table = 'courses'
    def __str__(self):
        return self.dept

class Course_num(models.Model):
    course_num = models.CharField(max_length=255, db_column = 'course_number')
    class Meta:
        managed = False
        db_table = 'courses'
    def __str__(self):
        return self.course_num

forms.py

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")

views.py

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)

EDIT: After changing the method to POST from GET, I still face the same issue. I played around with the views.py code to manually set the args dictionary and found that regardless of the result of form_CourseForm.is_valid(), nothing is added to args, even when I make selections on both dropdown menus. This makes no sense to me, but it seems like form_CourseForm isn't functional at all?

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>
    <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()

and also in html

<form method='post' action='' ...... >

这篇关于Django表单未保存输入-提交后刷新的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆