我的Python Django表单没有提交 [英] My form in Python Django is not submitting

查看:175
本文介绍了我的Python Django表单没有提交的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在制作一个使用Django制作时间表的表单,但由于某种原因表单没有提交。

 #choices.py 

COURSE_NAME_CHOICES (''a-plus','A + PC技术员'),('advance java','高级Java / J2EE / Weblogic / Websphere'),('as master','Agile-Scrum Master'), (''生物信息','生物信息数据库培训课程'),('ba','商业分析师(BA')), ('c-sharp','C#.Net'),('ccna','CCNA Voice'),('ceh','认证道德黑客'),('检查站','检查站安全防火墙课程') ,('ccie','思科CCIE IP电话'))
LOCATION_CHOICES =(('south_plainfield','South Plainfield'),('hackensack','Hackensack'),('fairfield','Fairfield' ),('eatontown','Eatentown'))
ROOM_CHOICES =(('A','南平原A:CNA / MCSE'),('B','南普兰菲尔德B:SAS / .Net' ),('C','South Plainfield C:Cisco'),('D','South Plainfield D:QA / .Net / Java'),('E','South Plainfield E:Weblogic / Java / MCSE '),('F','South Plainfield F:Unix / Linux'),('G','South Plainfield G:Oracle / Clinic / Datawarehouse'))
START_TIME_CHOICES =((''8点-30分','8:30 AM'),(''am am','9:00 AM'))
END_TIME_CHOICES =((''eight -30 am','8:30 AM'),''nine am','9:00 AM'))
INSTRUCTOR_CHOICES =(('adewale','Adewale Akinokun'),('ajay','Ajay Kumar'))
TOTAL_HOURS_CHOICES =(('' ',6),('ten',10))
HOURS_PER_CLASS_CHOICES =(('two_and_half',2.5),('three',3))
FREQUENCY_CHOICES =(('sunday','Sunday '',''星期一','星期一'),('星期二','星期二'),('星期三','星期三'),('星期四','星期四'),('星期五','星期五' '),('星期六','星期六'))
STATUS_CHOICES =(('active','Act ('''''''',''''''),(''''''''''''),('''''''''') ),('two_days','2 Days'))

#models.py

从django.db导入模型
从schedule.choices导入*
导入日期时间

类Schedule(models.Model):
course_name = models.CharField(max_length = 128,options = COURSE_NAME_CHOICES,default ='a-plus')
location = models.CharField(max_length = 128,options = LOCATION_CHOICES,default ='south_plainfield')
room = models.CharField(max_length = 128,choices = ROOM_CHOICES,default ='A')
start_date = models.DateField(auto_now = False,auto_now_add = False,default = datetime.date.today)
start_time = models.CharField(max_length = 128,选项= START_TIME_CHOICES,默认值='上午8点')
end_time = models.CharField(max_length = 128,选择= END_TIME_CHOICES,默认='八点半')
in structor = models.CharField(max_length = 128,choices = INSTRUCTOR_CHOICES,default ='adewale')
total_hours = models.IntegerField(options = TOTAL_HOURS_CHOICES,default ='six')
hours_per_class = models.FloatField( options = HOURS_PER_CLASS_CHOICES,default ='four_and_half')
frequency = models.CharField(max_length = 128,choices = FREQUENCY_CHOICES)
status = models.CharField(max_length = 128,options = STATUS_CHOICES)
interval = models.CharField(max_length = 128,options = INTERVAL_CHOICES,default ='one_day')

def __str __(self):
return self.course_name

#forms.py

from django import forms
from schedule.models import Schedule b $ b from schedule.choices import *
import datetime

class ScheduleForm(forms.ModelForm):
course_name = forms.ChoiceField(choices = COURSE_NAME_CHOICES,initial ='a-plus',label =Course Name)
location = forms.ChoiceField(choices = LOCATION_CHOICES , 在里面ial ='south_plainfield',label =Location)
room = forms.ChoiceField(choices = ROOM_CHOICES,initial ='A',label =Room)
start_date = forms.DateField(ini​​tial = datetime.date.today,widget = forms.DateInput(format ='%m /%d /%Y'),input_formats =('%m /%d /%Y'),label =开始日期)
start_time = forms.ChoiceField(options = START_TIME_CHOICES,initial ='eight -30 am',label =Start Time)
end_time = forms.ChoiceField(choices = END_TIME_CHOICES,initial ='eight -30 am' ,标签=结束时间)
导师= forms.ChoiceField(选择= INSTRUCTOR_CHOICES,初始='adewale',标签=教师)
total_hours = forms.ChoiceField(choices = TOTAL_HOURS_CHOICES,initial = 'six',label =Total Hours)
hours_per_class = forms.ChoiceField(choices = HOURS_PER_CLASS_CHOICES,initial ='four_and_half',label =Hours Per Class)
frequency = forms.MultipleChoiceField(widget = forms.CheckboxSelectMultiple,选择= FREQUENCY_CHOICES,标签=频率)
status = forms.MultipleChoiceField(widget = forms.RadioSelect,choices = STATUS_CHOICES,label =Status)
interval = forms.ChoiceField(choices = INTERVAL_CHOICES,initial ='one_day' ,label =Interval)

class Meta:
model = Schedule
fields =('course_name','location','room','start_date','start_time ','end_time','instructor','total_hours','hours_per_class','frequency','status','interval',)

widgets = {}

#urls.py

从django.conf.urls导入网址
从日程表导入视图作为schedule_views

urlpatterns = [
url(r' ^ start_one_schedule / $',schedule_views.start_One_Schedule,name ='start_one_schedule'),
]

#views.py

def start_One_Schedule(request):
form = ScheduleForm()
if request.method =='POST':
form = ScheduleForm(request.POST)

if form.is_valid():
form.save(commit = True)
return render(request,'schedule / schedule.html',{})
else:
print(form.errors)

return render(request,'schedule / start_one_schedule.html',{'form':form})

#start_one_schedule.html

{%block main_content%}
< h2>初始课程时间表< / h2>
< br>
< form id =schedule_formmethod =postaction =/ schedule / start_one_schedule />
{%csrf_token%}
{%for form in form%}
< table class =init_sched_form>
< tr class =init_sched_row>
< td class =init_sched_label> {{field.label_tag}}< / td>
< td class =init_sched_field> {{field}}< / td>
< / tr>
< / table>
{%endfor%}
< button type =submitname =submit>初始计划< / button>
< / form>
{%endblock%}

表单可以显示在html本身上。只是提交按钮根本不起作用。我一定要仔细检查一切,我90%确定我做的一切正确。有人有想法吗?我真的很感激它。谢谢。



编辑:我想我找到了问题所在。通过在模板中显示表单错误,我能够看到一些条目的几个字段是无效的。我修正了其中的两个,将options.py中的选项转换为整数并浮动到字符串中,这不是一个优美的修正,但适用于这种情况。

第二,开始日期字段是无效的,因为显然它只接受YYYY-MM-DD格式的日期,而不是像我想要的那样使用MM / DD / YYYY,所以我改变了初始回来,但如果有人有解决方案,请告诉我。



最后,最后两个错误是困扰我的那些错误。这里是:

状态 - 输入一个值列表。



频率 - 选择一个有效的选项。 ['tuesday','wednesday']不是可用的选择之一。

这些都是多选字段,频率为多选复选框,状态为无线选择。我不知道这些错误是什么意思,因为只有一些选择可供选择,所以我不知道如何输入值列表或为什么这些不是有效的选择。

解决方案

一般而言



您压倒性复制了现成的东西。模型形式出人意料地产生了领域。撇开关于charfields的一点,你可以减少你的表单到以下内容:

  class ScheduleForm(forms.ModelForm):
class Meta:
model = Schedule
fields =('course_name','location','room','start_date','start_time','end_time','instructor','total_hours' ,'hours_per_class','frequency','status','interval',)
widgets = {'frequency':forms.CheckboxSelectMultiple,'status':forms.RadioSelect}



CharField不是容器



不能使用 CharField 用于多种选择。它只保存一个字符串类型的项目。因此,任何传递给它的值都被强制为一个列表的字符串表示形式 ['foo','bar'] 。这与选择不匹配,所以验证失败。这通常通过与频率模型的ManyToManyRelation来解决。是的,数据是静态的,但它真的在这里使用数据库表有很大的不同。



一个获得普及的解决方案是使用 ArrayField JSONField 来自 django.contrib.postgres 。虽然它起作用,但它会使关系变得更加困难,因此如果仅显示此信息并且不会对其进行过滤,最好使用它。



RadioSelect返回一个项目



这基本上是相反的。现在,您正在尝试使用一个窗口小部件,该窗口小部件将返回一个预期为多个窗体字段的值。


I'm making a form involving making a schedule using Django, but for some reason the form is not submitting. I checked using SQLite DB Browser and nothing seems to be submitting.

# choices.py

COURSE_NAME_CHOICES = (('a-plus', 'A+ PC Technician'), ('advance java', 'Advance Java/J2EE/Weblogic/Websphere'), ('a-s master', 'Agile-Scrum Master'), ('android mobile', 'Android Mobile Development'), ('autocad', 'AutoCAD'), ('bio-info', 'Bio-info Database Training course'), ('ba', 'Business Analyst (BA'), ('c-sharp', 'C# .Net'), ('ccna', 'CCNA Voice'), ('ceh', 'Certified Ethical Hacking'), ('checkpoint', 'Checkpoint Security Firewall Course'), ('ccie', 'Cisco CCIE IP Telephony'))
LOCATION_CHOICES = (('south_plainfield', 'South Plainfield'), ('hackensack', 'Hackensack'), ('fairfield', 'Fairfield'), ('eatontown', 'Eatentown'))
ROOM_CHOICES = (('A', 'South Plainfield A: CNA/MCSE'), ('B', 'South Plainfield B: SAS/.Net'), ('C', 'South Plainfield C: Cisco'), ('D', 'South Plainfield D: QA/.Net/Java'), ('E', 'South Plainfield E: Weblogic/Java/MCSE'), ('F', 'South Plainfield F: Unix/Linux'), ('G', 'South Plainfield G: Oracle/Clinic/Datawarehouse'))
START_TIME_CHOICES = (('eight-thirty am', '8:30 AM'), ('nine am', '9:00 AM'))
END_TIME_CHOICES = (('eight-thirty am', '8:30 AM'), ('nine am', '9:00 AM'))
INSTRUCTOR_CHOICES = (('adewale', 'Adewale Akinokun'), ('ajay', 'Ajay Kumar'))
TOTAL_HOURS_CHOICES = (('six', 6), ('ten', 10))
HOURS_PER_CLASS_CHOICES = (('two_and_half', 2.5), ('three', 3))
FREQUENCY_CHOICES = (('sunday', 'Sunday'), ('monday', 'Monday'), ('tuesday', 'Tuesday'), ('wednesday', 'Wednesday'), ('thursday', 'Thursday'), ('friday', 'Friday'), ('saturday', 'Saturday'))
STATUS_CHOICES = (('active', 'Active'), ('inactive', 'Inactive'), ('expired', 'Expired'), ('pending', 'Pending'))
INTERVAL_CHOICES = (('one_day', '1 Day'), ('two_days', '2 Days'))

# models.py

from django.db import models
from schedule.choices import *
import datetime

class Schedule(models.Model):
    course_name = models.CharField(max_length=128, choices=COURSE_NAME_CHOICES, default='a-plus')
    location = models.CharField(max_length=128, choices=LOCATION_CHOICES, default='south_plainfield')
    room = models.CharField(max_length=128, choices=ROOM_CHOICES, default='A')
    start_date = models.DateField(auto_now=False, auto_now_add=False, default=datetime.date.today)
    start_time = models.CharField(max_length=128, choices=START_TIME_CHOICES, default='eight-thirty am')
    end_time = models.CharField(max_length=128, choices=END_TIME_CHOICES, default='eight-thirty am')
    instructor = models.CharField(max_length=128, choices=INSTRUCTOR_CHOICES, default='adewale')
    total_hours = models.IntegerField(choices=TOTAL_HOURS_CHOICES, default='six')
    hours_per_class = models.FloatField(choices=HOURS_PER_CLASS_CHOICES, default='four_and_half')
    frequency = models.CharField(max_length=128, choices=FREQUENCY_CHOICES)
    status = models.CharField(max_length=128, choices=STATUS_CHOICES)
    interval = models.CharField(max_length=128, choices=INTERVAL_CHOICES, default='one_day')

def __str__(self):
    return self.course_name

# forms.py

from django import forms
from schedule.models import Schedule
from schedule.choices import *
import datetime

class ScheduleForm(forms.ModelForm):
    course_name = forms.ChoiceField(choices=COURSE_NAME_CHOICES, initial='a-plus', label="Course Name")
    location = forms.ChoiceField(choices=LOCATION_CHOICES, initial='south_plainfield', label="Location")
    room = forms.ChoiceField(choices=ROOM_CHOICES, initial='A', label="Room")
    start_date = forms.DateField(initial=datetime.date.today, widget=forms.DateInput(format='%m/%d/%Y'), input_formats=('%m/%d/%Y'), label="Start Date")
    start_time = forms.ChoiceField(choices=START_TIME_CHOICES, initial='eight-thirty am', label="Start Time")
    end_time = forms.ChoiceField(choices=END_TIME_CHOICES, initial='eight-thirty am', label="End Time")
    instructor = forms.ChoiceField(choices=INSTRUCTOR_CHOICES, initial='adewale', label="Instructor")
    total_hours = forms.ChoiceField(choices=TOTAL_HOURS_CHOICES, initial='six', label="Total Hours")
    hours_per_class = forms.ChoiceField(choices=HOURS_PER_CLASS_CHOICES, initial='four_and_half', label="Hours Per Class")
    frequency = forms.MultipleChoiceField(widget=forms.CheckboxSelectMultiple, choices=FREQUENCY_CHOICES, label="Frequency")
    status = forms.MultipleChoiceField(widget=forms.RadioSelect, choices=STATUS_CHOICES, label="Status")
    interval = forms.ChoiceField(choices=INTERVAL_CHOICES, initial='one_day', label="Interval")

    class Meta:
        model = Schedule
        fields = ('course_name', 'location', 'room', 'start_date', 'start_time', 'end_time', 'instructor', 'total_hours', 'hours_per_class', 'frequency', 'status', 'interval',)

        widgets = {}

# urls.py

from django.conf.urls import url
from schedule import views as  schedule_views

urlpatterns = [
    url(r'^start_one_schedule/$', schedule_views.start_One_Schedule, name='start_one_schedule'),
]

# views.py

def start_One_Schedule(request):
    form = ScheduleForm()
    if request.method == 'POST':
        form = ScheduleForm(request.POST)

        if form.is_valid():
            form.save(commit=True)
            return render(request, 'schedule/schedule.html', {})
        else:
            print(form.errors)

    return render(request, 'schedule/start_one_schedule.html', {'form': form})

# start_one_schedule.html

{% block main_content %}
<h2>Initial Course Schedule</h2>
<br>
<form id="schedule_form" method="post" action="/schedule/start_one_schedule/">
    {% csrf_token %}
    {% for field in form %}
        <table class="init_sched_form">
            <tr class="init_sched_row">
                <td class="init_sched_label">{{ field.label_tag }}</td>
                <td class="init_sched_field">{{ field }}</td>
            </tr>
        </table>
    {% endfor %}
    <button type="submit" name="submit">Initial Schedule</button>
</form>
{% endblock %}

The form does manage to display on the html itself. It's just that the submit button won't work at all. I made sure to double check everything and I'm 90% sure that I did everything correctly. Does anyone have an idea? I'd really appreciate it. Thanks.

EDIT: I think I figured out the problem. By showing the form errors in the template, I was able to see that some of the entries several fields were invalid. I fixed two of them by turning the choices in choices.py with integers and floats into strings, which is not a graceful fix but it works for this case.

Second, the start date field was invalid because apparently it only accepts dates in the format of YYYY-MM-DD and not MM/DD/YYYY like I want it, so I changed the initial back, but if anyone has solution to that please tell me.

Finally, the final two errors are the ones that are stumping me. Here they are:

status - Enter a list of values.

frequency - Select a valid choice. ['tuesday', 'wednesday'] is not one of the available choices.

Both of these are multiple choice fields, frequency being multiple selection checkbox and status being radio select. I have no idea what these errors mean, since there are only set choices to choose from, so I don't know how to "enter a list of values" or why those aren't valid choices.

解决方案

In general

You're overriding and duplicating things that work out of the box. Model forms generate fields surprisingly well. Setting aside the bit about charfields, you can reduce your form to the following:

class ScheduleForm(forms.ModelForm):
    class Meta:
        model = Schedule
        fields = ('course_name', 'location', 'room', 'start_date', 'start_time', 'end_time', 'instructor', 'total_hours', 'hours_per_class', 'frequency', 'status', 'interval',)
        widgets = { 'frequency': forms.CheckboxSelectMultiple, 'status': forms.RadioSelect }

CharField is not a container

You cannot use a CharField for multiple choices. It only holds one item, of type string. So any value passed to it is coerced to string representation ['foo', 'bar'] for a list. This doesn't match the choices so validation fails. This typically is solved with a ManyToManyRelation to a Frequency model. Yes, the data is "static", but does it really make that much difference to use a database table here.

A solution gaining popularity is to use ArrayField or JSONField from django.contrib.postgres. While it works, it make relations a lot harder, so best used if this information is only displayed and not filtered on.

RadioSelect returns one item

This is basically the reverse. Now you're trying to use a widget that returns one value for a form field that expects multiple.

这篇关于我的Python Django表单没有提交的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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