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

Posted

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了Django表示不保存输入 - 提交后刷新相关的知识,希望对你有一定的参考价值。

我正在尝试使用两个下拉菜单创建一个网站:部门和课程编号。下拉菜单的数据来自我的SQL数据库的“courses”表。现在我的网站正确初始化,并在下拉菜单中显示正确的选项。但是,当用户在下拉菜单中选择一个选项并提交他们的选择时,网站将重新加载为空白平板,以便不保存或处理他们的选择。错误位于CourseForm表单中的某处,因为我有另一种形式(Working_Form),它以不同的方式创建但完美地运行。 CourseForm /其相关模型有什么问题?

models.朋友

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.朋友

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.朋友

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)

编辑:从GET更改方法到POST后,我仍然面临同样的问题。我使用views.py代码来手动设置args字典,发现无论form_CourseForm.is_valid()的结果如何,即使我在两个下拉菜单中进行选择,也没有任何内容添加到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>
    <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()

还有在html中

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

以上是关于Django表示不保存输入 - 提交后刷新的主要内容,如果未能解决你的问题,请参考以下文章

我在 viewpager 选项卡中的片段不刷新

django表单提交后如何用弹框提示成功?

django 制作web网站,动态页面数据已更新,但是无法刷新,这是怎么回事?是页面缓存吗?

怎么实现form表单提交后不重新刷新当前页面

毕业设计——Django项目网页刷新表单重复提交问题

如何使用 Django、Ajax、jQuery 在不刷新页面的情况下提交表单?