person10559
person10559

Reputation: 57

Django form not saving inputs- refreshes upon submission

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>

Upvotes: 0

Views: 399

Answers (1)

Exprator
Exprator

Reputation: 27513

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

Upvotes: 1

Related Questions