Django form not saving inputs- refreshes upon submission

两盒软妹~` 提交于 2020-01-06 06:04:27

问题


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>

回答1:


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='' ...... >


来源:https://stackoverflow.com/questions/49125925/django-form-not-saving-inputs-refreshes-upon-submission

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!