使用 Django 模型表单 + 表单向导 + Crispy - 不进行第二步

2024-04-19

我对 django 中的表单相当陌生。

我的问题是我有一些非常大的模型,我必须将它们分解成一系列较小的表单以供用户填写。

所以我一直在尝试使用脆皮表单,昨天在 YouTube 上观看 Mike Hibberts 教程(Python Django 教程 19 - 使用表单向导)后,我想看看是否可以使用脆皮表单来完成这项工作。

一切似乎对我来说都很好,但是当我按下提交时,表单似乎已经过验证,但没有继续执行步骤 2。

我这样做完全错误吗?

感谢您的任何帮助或建议!


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])), 
)

模型.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>

祝你有美好的一天!!!


对于未来的任何人,我想我已经解决了我的问题。 我花了一点时间才弄清楚,但我坚持不懈的修补得到了回报。 抱歉,我不会详细说明我必须更改的内容,但我确信你们大多数人都可以从我发布的代码中看到更改。表格看起来很棒!会话向导按预期工作!一切似乎都很好。祝大家好运!!

来自 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>
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

使用 Django 模型表单 + 表单向导 + Crispy - 不进行第二步 的相关文章

  • 从 Python 下载/安装 Windows 更新

    我正在编写一个脚本来自动安装 Windows 更新 我可以将其部署在多台计算机上 这样我就不必担心手动更新它们 我想用 Python 编写这个 但找不到任何关于如何完成此操作的信息 我需要知道如何搜索更新 下载更新并从 python 脚本安
  • 从sklearn PCA获取特征值和向量

    如何获取 PCA 应用程序的特征值和特征向量 from sklearn decomposition import PCA clf PCA 0 98 whiten True converse 98 variance X train clf f
  • Python中列表中两个连续元素的平均值

    我有一个偶数个浮点数的列表 2 34 3 45 4 56 1 23 2 34 7 89 我的任务是计算 1 和 2 个元素 3 和 4 5 和 6 等元素的平均值 在 Python 中执行此操作的快捷方法是什么 data 2 34 3 45
  • 使用 Python 计算 Spark 中成对 (K,V) RDD 中每个 KEY 的平均值

    我想与 Python 共享这个特定的 Apache Spark 解决方案 因为它的文档非常贫乏 我想通过 KEY 计算 K V 对 存储在 Pairwise RDD 中 的平均值 示例数据如下所示 gt gt gt rdd1 take 10
  • 对使用 importlib.util 导入的对象进行酸洗

    我在使用Python的pickle时遇到了一个问题 我需要通过将文件路径提供给 importlib util 来加载一些 Python 模块 如下所示 import importlib util spec importlib util sp
  • Python Django-如何从输入文件标签读取文件?

    我不想将文件保存在我的服务器上 我只想在下一页中读取并打印该文件 现在我有这个 index html
  • GradientTape 根据损失函数是否被 tf.function 修饰给出不同的梯度

    我发现计算的梯度取决于 tf function 装饰器的相互作用 如下所示 首先 我为二元分类创建一些合成数据 tf random set seed 42 np random seed 42 x tf random normal 2 1 y
  • Python:我不明白 sum() 的完整用法

    当然 我明白你使用 sum 与几个数字 然后它总结所有 但我正在查看它的文档 我发现了这一点 sum iterable start 第二个参数 start 的作用是什么 这太尴尬了 但我似乎无法通过谷歌找到任何示例 并且对于尝试学习该语言的
  • 如何在 Django 中使每五个帖子成为广告帖子

    我正在尝试允许用户赞助帖子 以便为该帖子带来更多点击量 我想让每五个帖子成为赞助帖子 但如果我尝试在模板中使用可整除并循环浏览广告 那么它将发布all第四个帖子后的广告 这是我尝试过的一些代码 编辑 我已将问题更改为不会显示帖子的问题 有人
  • Django - 提交具有同一字段多个输入的表单

    预警 我对 Django 以及一般的 Web 开发 非常陌生 我使用 Django 托管一个基于 Web 的 UI 该 UI 将从简短的调查中获取用户输入 通过我用 Python 开发的一些分析来提供输入 然后在 UI 中呈现这些分析的可视
  • 使用 NLP 进行地址分割

    我目前正在开发一个项目 该项目应识别地址的每个部分 例如来自 str Jack London 121 Corvallis ARAD ap 1603 973130 输出应如下所示 street name Jack London no 121
  • ModelChoiceField 在提交表单时给出无效选择错误

    我想允许用户删除特定模型的关联外键列表 假设我们有这两个模型 class IceBox models Model class FoodItem models Model name models CharField icebox models
  • php 表单提交 - Q2

    我对这个虚拟问题感到抱歉 这是我的简单 PHP 表单 其中包含两个 SQL 表和 ADD 提交 按钮 我希望将人员从 Test1 转移到 Test2 很多事情都很好 只有提交按钮不起作用 因此 Test2 表没有反馈 Revised 现在提
  • 导入错误:无法导入名称“时间戳”

    我使用以下代码在 python 3 6 3 中成功安装了 ggplot conda install c conda forge ggplot 但是当我使用下面的代码将其导入笔记本时 出现错误 from ggplot import Impor
  • 计算互相关函数?

    In R 我在用ccf or acf计算成对互相关函数 以便我可以找出哪个移位给我带来最大值 从它的外观来看 R给我一个标准化的值序列 Python 的 scipy 中是否有类似的东西 或者我应该使用fft模块 目前 我正在这样做 xcor
  • bs4 `next_sibling` VS `find_next_sibling`

    我在使用时遇到困难next sibling 并且类似地与next element 如果用作属性 我不会得到任何返回 但如果用作find next sibling or find next 然后就可以了 来自doc https www cru
  • 通过 Web 界面执行 python 单元测试

    是否可以通过 Web 界面执行单元测试 如果可以 如何执行 EDIT 现在我想要结果 对于测试 我希望它们是自动化的 可能每次我对代码进行更改时 抱歉我忘了说得更清楚 EDIT 这个答案此时已经过时了 Use Jenkins https j
  • 如何在 Django 中使我的模型字段可选?

    我正在尝试遵循底部的完整示例 https docs djangoproject com en dev topics auth customizing https docs djangoproject com en dev topics au
  • 使用Multiprocessing和Pool时如何访问全局变量?

    我试图避免将变量冗余地传递到dataList e g 1 globalDict 2 globalDict 3 globalDict 并在全球范围内使用它们 global globalDict然而 在下面的代码中并不是这样做的解决方案 是否有
  • tkinter:打开一个带有按钮提示的新窗口[关闭]

    Closed 这个问题需要调试细节 help minimal reproducible example 目前不接受答案 用户如何按下 tkinter GUI 中的按钮来打开新窗口 我只需要非常简单的解决方案 如果代码也能被解释那就太好了 这

随机推荐