使用Django模型表单+表单向导+脆饼 - 不进行第二步 [英] Using Django model forms + form wizard + Crispy - Does not proceed to second step
问题描述
我的问题是我有一些非常大的模型,我必须分解成一系列较小的表单供用户填写。
所以我一直在玩脆情的形式,昨天在YouTube上看到Mike Hibberts教程(Python Django教程19 - 使用表单向导)后,我想看看我能否使用这个工具一个脆弱的形式。
一切似乎都对我好转,但是当我按提交表单似乎被验证,但不进行到步骤2。
我完全错了吗?
感谢任何帮助或建议!
forms.py
from django import forms
从crispy_forms.helper导入FormHelper
从crispy_forms.layout导入提交,布局,ButtonHolder
从crispy_forms.bootstrap导入StrictButton
从模型导入ProcessSheet
class EnterData(forms.ModelForm):
def __init __(self,* args,** kwargs):
super(EnterData,self).__ init __(* args,** kwargs)
#如果您传递FormHelper构造函数一个窗体实例
#它构建一个默认布局,其所有字段
self.helper = FormHelper(self)
self.helper.form_class ='form-horizontal'
self.helper.label_class =' text-center col-lg-4'
self.helper.field_class ='col-lg-8'
self.helper.layout.append(Submit('save','save '))
self.helper.layout =布局(
'sheet_id',
'sheet_title',
'part_name',
ButtonHolder('save',css_class ='btn-warning'),
)
#你可以动态调整你的布局
class Meta:
model = ProcessSheet
fields =__all__
class Sheet1(forms.ModelForm):
def __init __(self,* args,** kwargs):
printsheet 1 init !!!!!!!!!!!!!!!
super(Sheet1,self).__ init __(* args,** kwargs)
#如果您传递FormHelper构造函数一个窗体实例
#它构建一个默认布局,其所有字段
self.helper = FormHelper(self)
self.helper.form_tag = False
self.helper.form_class ='form-horizontal'
self.helper.label_class ='text-centre col -lg-4'
self.helper.field_class ='col-lg-8'
self.helper.layout =布局(
'sheet_id',
'sheet_title',
'part_name',
)
class Meta:
model = ProcessSheet
fields =__all__
class Sheet2(forms.ModelForm):
def __init __(self,* args,** kwargs):
super(Sheet2,self).__ init __(* args,** kwargs )
#如果你传递FormHelper构造函数一个窗体实例
#它构建一个默认布局,其所有字段
self.helper = FormHelper(self)
self.helper.form_tag = False
self.helper.form_class ='form-horizontal'
self.helper.label_class ='text-center col- lg-4'
self.helper.field_class ='col-lg-8'
self.helper.layout =布局(
'cooling',
'喷嘴',
'zone_5',
)
class Meta:
model = ProcessSheet
fields =__all__
views.py
从django.shortcuts导入render_to_response的$ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $
logr = logging.getLogger(__ name__)
从表单导入EnterData
#在此创建您的视图。
def SheetSelect(request):
logr.debug(IM IN SELECT !!!!!!!!!!!)
打印IM IN SELECT !!!!! !!!!!!!
form = EnterData(request.POST或None)
log_data_message =请输入一些数据
如果form.is_valid():
数据= form.cleaned_data
如果不是ProcessSheet.objects.filter(sheet_id = data ['sheet_id']):
save_it = form.save(commit = False)
save_it.save()
form = EnterData()
log_data_message =数据输入好!
else:
log_data_message =工作表ID已经存在!
sheets = ProcessSheet.objects.all()
return render_to_response('PS14.html',
localals(),
context_instance = RequestContext(request))
def SheetFocus(request,sheet_id = 0):
sheet = ProcessSheet.objects.get(id = sheet_id)
返回render_to_response('PS24.html',
local(),
context_instance = RequestContext(request))
class SheetWizard(SessionWizardView):
logr.debug(IM IN WIZARD !!!!!!!!! !!!)
template_name =sheet_form.html
def done(self,form_list,** kwargs):
logr.debug(IM IN DONE!
form_data = process_form_data(form_list)
返回render_to_response('done.html',{'form_data':form_data})
def process_form_data(form_list):
form_data = [form.cleaned_data for form in form_list]
logr.debug(DONE PROCESS FORM DATA !!!!!!!!!!!)
return form_data
urls.py
from django.conf.urls import pattern,include,url
from process_forms.forms import Sheet1,Sheet2
from process_forms.views import SheetWizard
urlpatterns = pattern('',
url(r'^ all /','process_forms.views.SheetSelect'),
url(r'^ get /(?P< sheet_id> \d +)/' ,'process_forms.views.SheetFocus'),
url(r'^ entry /',SheetWizard.as_view([Sheet1,Sheet2])),
)
models.py
$ d code从django.core.validators导入MaxValueValidator,MinValueValidator#在这里创建你的模型。
类ProcessSheet(models.Model):
ejector_confirmation_on = models.BooleanField(default = True)
number_of_cavities = models.IntegerField(blank = True,null = True,validators = [
MaxValueValidator(100),
MinValueValidator(1)
])
date = models.IntegerField(blank = True,null = True)
shift = models.IntegerField(blank = True,null = True,validators = [
MaxValueValidator(4),
MinValueValidator(1)
])
sheet_desc = $($空格= True,null = True)
sheet_id = models.CharField(max_length = 16,blank = False,null = True)
sheet_title = models.CharField(max_length = 24,blank = False,null = True)
part_number = models.CharField(max_length = 16,blank = False,null = True)
part_name = models.CharField(max_length = 16,blank = True ,null = True)
machine_no = models.CharField(max_length = 16,blank = True,null = True)
special_notes = models.CharField(max_length = 256,blank = True,null = True)
end_of_arm_tool_number = models.CharField(max_length = 16,blank = True,null = True)
program_picker_robot = models.CharField(max_length = 16,blank = True,null = True)
nozzle_tip_size = .CharField(max_length = 16,blank = True,null = True)
k_cut = models.BooleanField(default = False)
hydraulic_unit_pressure = models.CharField(max_length = 16,blank = True,null = True )
valve_gate = models.CharField(max_length = 16,blank = True,null = True)
coloring = models.CharField(max_length = 16,blank = True,null = True)
reasons_for_changes = models.CharField(max_length = 16,blank = True,null = True)
finger_print = models.CharField(max_length = 16,blank = True,null = True)
initial = models。 CharField(max_length = 16,blank = True,null = True)
V1 = models.FloatField(blank = True,null = True)
V2 = models.FloatField(blank = null = True)
V3 = models.FloatField(blank = True,null = True)
V4 = models.FloatField(blank = True,null = True)
V5 = models.FloatField blank = True,null = True)
position_pressure = models.FloatField(blank = True,null = True)
pack_1 = models.FloatField(blank = True,null = True)
pack_2 = models.FloatField(blank = True,null = True)
pack1 = models.FloatField(blank = True,null = True)
pack2 = mo dels.FloatField(blank = True,null = True)
shot_size = models.FloatField(blank = True,null = True)
back_1 = models.FloatField(blank = True,null = True)
screw_speed = models.FloatField(blank = True,null = True)
cushion_in_inches = models.FloatField(blank = True,null = True)
inject_time = models.FloatField(blank = True,null = true)
cycle_time = models.FloatField(blank = True,null = True)
cooling = models.FloatField(blank = True,null = True)
hot_sprue_1 = models.FloatField(blank = true,null = True)
喷嘴= models.FloatField(blank = True,null = True)
zone_1_barrel = models.FloatField(blank = True,null = True)
zone_2_barrel = models。 FloatField(blank = True,null = True)
zone_3_barrel = models.FloatField(blank = True,null = True)
mold = models.FloatFi eld(blank = True,null = True)
dryer = models.FloatField(blank = True,null = True)
zone_1 = models.FloatField(blank = True,null = True)
zone_2 = models.FloatField(blank = True,null = True)
zone_3 = models.FloatField(blank = True,null = True)
zone_4 = models.FloatField(blank = True,null = True)
zone_5 = models.FloatField(blank = True,null = True)
zone_6 = models.FloatField(blank = True,null = True)
zone_7 = models.FloatField(blank = null = True)
zone_8 = models.FloatField(blank = True,null = True)
zone_9 = models.FloatField(blank = True,null = True)
zone_10 = models.FloatField blank = True,null = True)
zone_11 = models.FloatField(blank = True,null = True)
zone_12 = models.FloatField(blank = Tr ue,null = True)
flowmeter_reading = models.FloatField(blank = True,null = True)
def Meta():
managed = True
sheet_form.html
{%extendsbase.html%}
{%block content%}
< H1>这是输入表单< / H1> {{wizard.steps.count}}< / p>的步骤{{wizard.steps.step1}}
< p>
< br>
{{log_data_message}}
< form action =/ sheets / entry /method =post>
{{wizard.management_form}}
{%load crispy_forms_tags%}
{%crispy wizard.form%}
{%if wizard.steps.prev%}
< button name =wizard_goto_steptype =submitvalue ={ {wizard.steps.first}}>第一步< / button>
< button name =wizard_goto_steptype =submitvalue ={{wizard.steps.prev}}>上一步< / button>
{%endif%}
< input type =submitvalue =提交/>
< / form>
{%endblock%}
{%块链接%}
{%表中的表格%}
< a HREF =/ sheets / get / {{sheet.id}}> {{sheet.sheet_title}}< / a>
< br>
{%endfor%}
{%endblock%}
< br>
有一个美好的一天!!!
解决方案对于任何人来说,我认为我解决了我的问题。
花了一点时间才能弄清楚,但是我的持续修补付出了代价。
对不起,我不会详细介绍我必须改变的内容,但可以肯定,大多数人可以看到我发布的代码的更改。形式看起来很棒!会话向导按预期工作!一切似乎都没事。最好的运气大家!!
来自forms.py的类
class Sheet1(forms.ModelForm):
def __init __(self,* args,** kwargs):
super(Sheet1,self).__ init __(* args,** kwargs)
self .fields ['machine_no'] = forms.ChoiceField(choices = get_site_choices())
self.helper = FormHelper(self)
self.helper.form_tag = False
#self.helper。 label_class ='text-center col-lg-4'
#self.helper.field_class ='col-lg-8'
self.helper.layout =布局(
HTML({ %include \progress_bar_min.html\with value = \1\%}),
HTML({%include \form_head_information.html\,value = \ + str(args)+\%}),
TabHolder(
Tab(
'Sheet Information',
PrependedText('sheet_id','Django - '),
警报(content ='< strong>自动生成的ID!< /强大>只是你知道'',css_class =alert-warning alert-dismissible),
'sheet_title',
'part_name',
),
Tab b $ b'新闻位置',
'machine_no',
'sheet_desc',
),
标签(
'评论',
警报content ='< strong>帮助我们改进!< / strong>请留下很多评论。',css_class =alert-info alert-dismissible),
'comment',
),
),
ButtonHolder(
提交('Save','Save',css_class ='btn-info'),
提交('wizard_goto_step','0'),
提交('wizard_goto_step','1'),
提交('wizard_goto_step','2'),
),
)
query = ProcessSheet.objects.latest('id')。sheet_id
self.fields ['sheet_id']。widget.attrs ['readonly'] = True
self.fields ['sheet_id']。initial = query +' - '+ str(time.time())
self。字段['sheet_id']。label =此表的ID
self.fields ['sheet_title']。label =输入此表的标题
self.fields ['part_name'] .label =输入零件号
class Meta:
model = ProcessSheet
fields =(
'sheet_id',
sheet_title',
'part_name',
'machine_no',
'comment',
'sheet_desc',
)
sheet_form.html
{%extends base.html%
{%block content%}
< H1>这是{{views_context_var}}< / H1>的输入表单{{wizard.steps.count}}< / p>的步骤{{wizard.steps.step1}}
< p>
< br>
< form action =/ sheets / entry /method =post>
{{wizard.management_form}}
{%load crispy_forms_tags%}
{%crispy wizard.form%}
< ; /形式>
{%endblock%}
< br>
I am fairly new to forms in django.
My issue is I have a few very large models that I have to break up into a series of smaller forms for the users to fill out.
So I've been playing around with crispy forms and yesterday after watching Mike Hibberts tutorial ( Python Django tutorial 19 - Using the Form Wizard ) on youtube I wanted to see if I could make this work with a crispy form.
Everything seems to render ok to me, however when I press submit the form seems to be validated but does not proceed to step 2.
Am I doing this completely wrong??
Thanks for any help or suggestions!
forms.py
from django import forms
from crispy_forms.helper import FormHelper
from crispy_forms.layout import Submit, Layout, ButtonHolder
from crispy_forms.bootstrap import StrictButton
from models import ProcessSheet
class EnterData(forms.ModelForm):
def __init__(self, *args, **kwargs):
super(EnterData, self).__init__(*args, **kwargs)
# If you pass FormHelper constructor a form instance
# It builds a default layout with all its fields
self.helper = FormHelper(self)
self.helper.form_class = 'form-horizontal'
self.helper.label_class = 'text-center col-lg-4'
self.helper.field_class = 'col-lg-8'
self.helper.layout.append(Submit('save', 'save'))
"""
self.helper.layout = Layout(
'sheet_id',
'sheet_title',
'part_name',
ButtonHolder('save', css_class='btn-warning'),
)
# You can dynamically adjust your layout
"""
class Meta:
model = ProcessSheet
fields = "__all__"
class Sheet1(forms.ModelForm):
def __init__(self, *args, **kwargs):
print "sheet 1 init!!!!!!!!!!!!!!!"
super(Sheet1, self).__init__(*args, **kwargs)
# If you pass FormHelper constructor a form instance
# It builds a default layout with all its fields
self.helper = FormHelper(self)
self.helper.form_tag = False
self.helper.form_class = 'form-horizontal'
self.helper.label_class = 'text-center col-lg-4'
self.helper.field_class = 'col-lg-8'
self.helper.layout = Layout(
'sheet_id',
'sheet_title',
'part_name',
)
class Meta:
model = ProcessSheet
fields = "__all__"
class Sheet2(forms.ModelForm):
def __init__(self, *args, **kwargs):
super(Sheet2, self).__init__(*args, **kwargs)
# If you pass FormHelper constructor a form instance
# It builds a default layout with all its fields
self.helper = FormHelper(self)
self.helper.form_tag = False
self.helper.form_class = 'form-horizontal'
self.helper.label_class = 'text-center col-lg-4'
self.helper.field_class = 'col-lg-8'
self.helper.layout = Layout(
'cooling',
'nozzle',
'zone_5',
)
class Meta:
model = ProcessSheet
fields = "__all__"
views.py
from django.shortcuts import render_to_response, RequestContext
from process_forms.models import ProcessSheet
from django.contrib.formtools.wizard.views import SessionWizardView
import logging
logr = logging.getLogger(__name__)
from forms import EnterData
# Create your views here.
def SheetSelect(request):
logr.debug( "IM IN SELECT!!!!!!!!!!!!" )
print "IM IN SELECT!!!!!!!!!!!!"
form = EnterData(request.POST or None)
log_data_message = "Please Enter Some Data"
if form.is_valid():
data = form.cleaned_data
if not ProcessSheet.objects.filter(sheet_id=data['sheet_id']):
save_it = form.save(commit=False)
save_it.save()
form = EnterData()
log_data_message = "Data Entered Ok!"
else:
log_data_message = "Sheet ID already exists!"
sheets = ProcessSheet.objects.all()
return render_to_response('PS14.html',
locals(),
context_instance=RequestContext(request))
def SheetFocus(request, sheet_id=0):
sheet = ProcessSheet.objects.get(id=sheet_id)
return render_to_response('PS24.html',
locals(),
context_instance=RequestContext(request))
class SheetWizard(SessionWizardView ):
logr.debug( "IM IN WIZARD!!!!!!!!!!!!" )
template_name = "sheet_form.html"
def done(self, form_list, **kwargs):
logr.debug( "IM IN DONE!!!!!!!!!!!!" )
form_data = process_form_data(form_list)
return render_to_response('done.html', {'form_data': form_data})
def process_form_data(form_list):
form_data = [form.cleaned_data for form in form_list]
logr.debug( "DONE PROCESS FORM DATA!!!!!!!!!!!!" )
return form_data
urls.py
from django.conf.urls import patterns, include, url
from process_forms.forms import Sheet1, Sheet2
from process_forms.views import SheetWizard
urlpatterns = patterns('',
url(r'^all/', 'process_forms.views.SheetSelect'),
url(r'^get/(?P<sheet_id>\d+)/', 'process_forms.views.SheetFocus'),
url(r'^entry/', SheetWizard.as_view([Sheet1,Sheet2])),
)
models.py
from django.db import models
from django.core.validators import MaxValueValidator, MinValueValidator
# Create your models here.
class ProcessSheet(models.Model):
ejector_confirmation_on = models.BooleanField(default=True)
number_of_cavities = models.IntegerField(blank=True, null=True,validators=[
MaxValueValidator(100),
MinValueValidator(1)
])
date = models.IntegerField(blank=True, null=True)
shift = models.IntegerField(blank=True, null=True,validators=[
MaxValueValidator(4),
MinValueValidator(1)
])
sheet_desc = models.TextField(blank=True, null=True)
comment = models.TextField(blank=True, null=True)
sheet_id = models.CharField(max_length=16, blank=False,null=True)
sheet_title = models.CharField(max_length=24, blank=False,null=True)
part_number = models.CharField(max_length=16, blank=False,null=True)
part_name = models.CharField(max_length=16, blank=True, null=True)
machine_no = models.CharField(max_length=16, blank=True, null=True)
special_notes = models.CharField(max_length=256,blank=True, null=True)
end_of_arm_tool_number = models.CharField(max_length=16, blank=True, null=True)
program_picker_robot = models.CharField(max_length=16, blank=True, null=True)
nozzle_tip_size = models.CharField(max_length=16, blank=True, null=True)
k_cut = models.BooleanField(default=False)
hydraulic_unit_pressure = models.CharField(max_length=16, blank=True, null=True)
valve_gate = models.CharField(max_length=16, blank=True, null=True)
colorant = models.CharField(max_length=16, blank=True, null=True)
reasons_for_changes = models.CharField(max_length=16, blank=True, null=True)
finger_print = models.CharField(max_length=16, blank=True, null=True)
initial = models.CharField(max_length=16, blank=True, null=True)
V1 = models.FloatField(blank=True, null=True)
V2 = models.FloatField(blank=True, null=True)
V3 = models.FloatField(blank=True, null=True)
V4 = models.FloatField(blank=True, null=True)
V5 = models.FloatField(blank=True, null=True)
position_pressure = models.FloatField(blank=True, null=True)
pack_1 = models.FloatField(blank=True, null=True)
pack_2 = models.FloatField(blank=True, null=True)
pack1 = models.FloatField(blank=True, null=True)
pack2 = models.FloatField(blank=True, null=True)
shot_size = models.FloatField(blank=True, null=True)
back_1 = models.FloatField(blank=True, null=True)
screw_speed = models.FloatField(blank=True, null=True)
cushion_in_inches = models.FloatField(blank=True, null=True)
injection_time = models.FloatField(blank=True, null=True)
cycle_time = models.FloatField(blank=True, null=True)
cooling = models.FloatField(blank=True, null=True)
hot_sprue_1 = models.FloatField(blank=True, null=True)
nozzle = models.FloatField(blank=True, null=True)
zone_1_barrel = models.FloatField(blank=True, null=True)
zone_2_barrel = models.FloatField(blank=True, null=True)
zone_3_barrel = models.FloatField(blank=True, null=True)
mold = models.FloatField(blank=True, null=True)
dryer = models.FloatField(blank=True, null=True)
zone_1 = models.FloatField(blank=True, null=True)
zone_2 = models.FloatField(blank=True, null=True)
zone_3 = models.FloatField(blank=True, null=True)
zone_4 = models.FloatField(blank=True, null=True)
zone_5 = models.FloatField(blank=True, null=True)
zone_6 = models.FloatField(blank=True, null=True)
zone_7 = models.FloatField(blank=True, null=True)
zone_8 = models.FloatField(blank=True, null=True)
zone_9 = models.FloatField(blank=True, null=True)
zone_10 = models.FloatField(blank=True, null=True)
zone_11 = models.FloatField(blank=True, null=True)
zone_12 = models.FloatField(blank=True, null=True)
flowmeter_reading = models.FloatField(blank=True, null=True)
def Meta():
managed = True
sheet_form.html
{% extends "base.html" %}
{% block content %}
<H1> This is the entry form </H1>
<p>Step {{ wizard.steps.step1 }} of {{ wizard.steps.count }}</p>
<br>
{{log_data_message}}
<form action="/sheets/entry/" method="post">
{{ wizard.management_form }}
{% load crispy_forms_tags %}
{% crispy wizard.form %}
{% if wizard.steps.prev %}
<button name="wizard_goto_step" type="submit" value="{{ wizard.steps.first }}">"first step"</button>
<button name="wizard_goto_step" type="submit" value="{{ wizard.steps.prev }}">"prev step"</button>
{% endif %}
<input type="submit" value="Submit" />
</form>
{% endblock %}
{% block links %}
{% for sheet in sheets %}
<a HREF="/sheets/get/{{ sheet.id }}">{{sheet.sheet_title}}</a>
<br>
{% endfor %}
{% endblock %}
<br>
Have a great day!!!
解决方案 For anyone in the future i think ive solved my issue.
took a little while for me to figure it out but my persistent tinkering payed off.
sorry im not going into detail about what i had to change, but im sure most of you can see the changes from the code i posted. the forms look great! the session wizard works as expected! and all seems to be ok. best of luck everyone!!
Class from forms.py
class Sheet1(forms.ModelForm):
def __init__(self, *args, **kwargs):
super(Sheet1, self).__init__(*args, **kwargs)
self.fields['machine_no'] = forms.ChoiceField(choices=get_site_choices())
self.helper = FormHelper(self)
self.helper.form_tag = False
#self.helper.label_class = 'text-center col-lg-4'
#self.helper.field_class = 'col-lg-8'
self.helper.layout = Layout(
HTML("{% include \"progress_bar_min.html\" with value=\"1\" %}"),
HTML("{% include \"form_head_information.html\" with value=\""+str(args)+"\" %}"),
TabHolder(
Tab(
'Sheet Information',
PrependedText('sheet_id', 'Django-'),
Alert(content='<strong>Automatically Generated ID!</strong> Just so you know.', css_class="alert-warning alert-dismissible"),
'sheet_title',
'part_name',
),
Tab(
'Press Location',
'machine_no',
'sheet_desc',
),
Tab(
'Comments',
Alert(content='<strong>Help Us Improve!</strong> Please leave lots of comments.', css_class="alert-info alert-dismissible"),
'comment',
),
),
ButtonHolder(
Submit('Save', 'Save', css_class='btn-info'),
Submit('wizard_goto_step', '0'),
Submit('wizard_goto_step', '1'),
Submit('wizard_goto_step', '2'),
),
)
query = ProcessSheet.objects.latest('id').sheet_id
self.fields['sheet_id'].widget.attrs['readonly'] = True
self.fields['sheet_id'].initial = query+'-'+str(time.time())
self.fields['sheet_id'].label = "ID For This Sheet"
self.fields['sheet_title'].label = "Enter A Title For This Sheet"
self.fields['part_name'].label = "Enter The Part Number"
class Meta:
model = ProcessSheet
fields =(
'sheet_id',
'sheet_title',
'part_name',
'machine_no',
'comment',
'sheet_desc',
)
sheet_form.html
{% extends "base.html" %}
{% block content %}
<H1> This is the entry form {{views_context_var}}</H1>
<p>Step {{ wizard.steps.step1 }} of {{ wizard.steps.count }}</p>
<br>
<form action="/sheets/entry/" method="post">
{{ wizard.management_form }}
{% load crispy_forms_tags %}
{% crispy wizard.form %}
</form>
{% endblock %}
<br>
这篇关于使用Django模型表单+表单向导+脆饼 - 不进行第二步的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!