python - 我的 View 和表单集保存时遇到问题

标签 python django django-forms django-views

我在保存 View 和表单集方面遇到了最困难的时期。我开始意识到 View 是我在 Django 中的弱点。过去几个月我一直在致力于这个工作并编写和重写代码。我知道这是最好的学习方式。幸运的是,我的团队给了我这个项目供我学习。但我还是不知道我错在哪里。

如果这里有人看到我的错误或指出我正确的方向,我将不胜感激。我正在寻找最好的资源来在这个领域变得更强。

这是我的观点:

from django.conf import settings
from django.views.generic import View
from django.views.generic import TemplateView
from django.shortcuts import render
from itertools import chain

from .models import *
from .forms import *
from .emailtemplates import OrderFormNotification


class OrderFormProcessor(object):
    def __init__(self, contact=None, contact_form_class=ContactForm,
        letterhead_form_class=LetterHeadFormSet,
        windowenv_form_class=WindowEnvFormSet,
        numbertenenv_form_class=NumberTenEnvFormSet,
        ninebytwelveenv_form_class=NineByTwelveEnvFormSet,
        tenbythirteenenv_form_class=TenByThirteenEnvFormSet,
        businesscard_form_class=BusinessCardFormSet,
        send_notification=False):
    self.contact_form_class = contact_form_class
    self.letterhead_form_class = letterhead_form_class
    self.windowenv_form_class = windowenv_form_class
    self.numbertenenv_form_class = numbertenenv_form_class
    self.ninebytwelveenv_form_class = ninebytwelveenv_form_class
    self.tenbythirteenenv_form_class = tenbythirteenenv_form_class
    self.businesscard_form_class = businesscard_form_class
    self.send_notification = send_notification
    self.contact = contact

def process(self, request, context=None):
    if not context:
        context = {}

    contact = self.contact

    data = request.POST or None

    contact_form = self.contact_form_class(data,
            instance=contact)

    forms = dict(
        contact_form=contact_form,
    )

    formsets = dict(
        letterhead_formset=self.letterhead_form_class(data,                 prefix='letterhead_'),
        windowenv_formset=self.windowenv_form_class(data, prefix='windowenv_'),
        numbertenenv_formset=self.numbertenenv_form_class(data, prefix='numbertenenv_'),
        ninebytwelveenv_formset=self.ninebytwelveenv_form_class(data, prefix='ninebytwelveenv_'),
        tenbythirteenenv_formset=self.tenbythirteenenv_form_class(data, prefix='tenbythirteenenv_'),
        businesscard_formset=self.businesscard_form_class(data, prefix='businesscard_'),
    )

    if request.method == 'POST':
        form_is_valid = all([f.is_valid() for f in forms.values() + \
                formsets.values()])
        if form_is_valid:
            contact = forms['contact_form'].save(commit=False)

            contact.letterhead_form = formsets['letterhead_formset'].save()
            contact.windowenv_form = formsets['windowenv_formset'].save()
            contact.numbertenenv_form = formsets['numbertenenv_formset'].save()
            contact.ninebytwelveenv_form = formsets['ninebytwelveenv_formset'].save()
            contact.tenbythirteenenv_form = formsets['tenbythirteenenv_formset'].save()
            contact.businesscard_form = formsets['businesscard_formset'].save()

            contact.save()

            if self.send_notification:
                email = OrderFormNotification(to=[settings.NO_REPLY_EMAIL_ADDRESS],
                extra_context=data)
                email.send()
        else:
            pass

    all_forms = chain(forms.values(), chain.from_iterable(formsets.values()))
    context = context.copy()
    context.update(forms.items() + formsets.items())
    context.update(
        error_list=list(chain.from_iterable([form.errors.values() for form in all_forms])),
    )

    return (forms, formsets), context


class OrderFormView(View):
    template_name = 'orderform.html'

    def dispatch(self, request, *args, **kwargs):
        processor = OrderFormProcessor(send_notification=True)

        (forms, formsets), context = processor.process(request)
        return render(request, self.template_name, context)


class ThankYou(TemplateView):
    template_name = 'thank-you.html'

这是我的表格:

from django import forms
from django.forms import ModelForm, extras
from django.forms.models import modelformset_factory
from django.contrib.localflavor import us

from django.forms.widgets import RadioSelect, CheckboxSelectMultiple

from .models import *


class ContactForm(forms.ModelForm):
    address = forms.ChoiceField(required = True, widget=RadioSelect(), choices=ADDRESS_CHOICES,)
    class Meta:
        model = Contact


class LetterHeadForm(forms.ModelForm):
    address = forms.ChoiceField(required = False, widget=RadioSelect(), choices=ADDRESS_CHOICES)
    class Meta:
        model = LetterHead
        widgets = {
            'contact': forms.HiddenInput,
            'quantity': forms.Select(choices=QUANTITY_CHOICES),
        }


class WindowEnvForm(forms.ModelForm):
    address = forms.ChoiceField(required = False, widget=RadioSelect(), choices=ADDRESS_CHOICES)
    class Meta:
        model = WindowEnv
        widgets = {
            'contact': forms.HiddenInput,
            'quantity': forms.Select(choices=QUANTITY_CHOICES),
        }


class NumberTenEnvForm(forms.ModelForm):
    address = forms.ChoiceField(required = False, widget=RadioSelect(), choices=ADDRESS_CHOICES)
    class Meta:
        model = NumberTenEnv
        widgets = {
            'contact': forms.HiddenInput,
            'quantity': forms.Select(choices=QUANTITY_CHOICES),
        }


class NineByTwelveEnvForm(forms.ModelForm):
    address = forms.ChoiceField(required = False, widget=RadioSelect(), choices=ADDRESS_CHOICES)
    class Meta:
        model = NineByTwelveEnv
        widgets = {
            'contact': forms.HiddenInput,
            'quantity': forms.Select(choices=QUANTITY_CHOICES),
        }


class TenByThirteenEnvForm(forms.ModelForm):
    address = forms.ChoiceField(required = False, widget=RadioSelect(), choices=ADDRESS_CHOICES)
    class Meta:
        model = TenByThirteenEnv
        widgets = {
            'contact': forms.HiddenInput,
            'quantity': forms.Select(choices=QUANTITY_CHOICES),
        }


class BusinessCardForm(forms.ModelForm):
    print_choices = forms.ChoiceField(required = True, widget=RadioSelect(), choices=PRINT_CHOICES)
    card_styles = forms.ChoiceField(required = True, widget=RadioSelect(), choices=CARD_CHOICES)
    card_mailing_address = forms.ChoiceField(required = True, widget=RadioSelect(), choices=ADDRESS_CHOICES)
    class Meta:
        model = BusinessCard
        widgets = {
            'contact': forms.HiddenInput,
        }


class RushOrderForm(forms.ModelForm):
    class Meta:
        model = RushOrder
        widgets = {
            'contact': forms.HiddenInput,
            'rush_order': forms.CheckboxInput,
            'in_hand_date': forms.extras.SelectDateWidget
        }


class OrderNoteForm(forms.ModelForm):
    class Meta:
        model = OrderNote
        widgets = {
            'contact': forms.HiddenInput,
            'add_note': forms.CheckboxInput,
            'notes': forms.Textarea
        }


LetterHeadFormSet = modelformset_factory(LetterHead,
    form=LetterHeadForm, extra=2, max_num=2)
WindowEnvFormSet = modelformset_factory(WindowEnv,
    form=WindowEnvForm, extra=2, max_num=2)
NumberTenEnvFormSet = modelformset_factory(NumberTenEnv,
    form=NumberTenEnvForm, extra=2, max_num=2)
NineByTwelveEnvFormSet = modelformset_factory(NineByTwelveEnv,
    form=NineByTwelveEnvForm, extra=2, max_num=2)
TenByThirteenEnvFormSet = modelformset_factory(TenByThirteenEnv,
    form=TenByThirteenEnvForm, extra=2, max_num=2)
BusinessCardFormSet = modelformset_factory(BusinessCard,
    form=BusinessCardForm, extra=2, max_num=2)

以下是模型:

from django.db import models
from django.forms import ModelForm

from django.utils.translation import ugettext_lazy as _
from django.contrib.localflavor.us.models import PhoneNumberField

PRINT_CHOICES = (
    ('exact reprint', 'Exact Reprint'),
    ('reprint with changes', 'Reprint With Changes'),
    ('new', 'New')
)

QUANTITY_CHOICES = (
    ('1000', '1000'),
    ('2500', '2500'),
    ('5000', '5000')
)

CARD_QUANTITY_CHOICES = (
    ('250', '250'),
    ('500', '500'),
    ('1000', '1000')
)

CARD_CHOICES = (
    ('chef/black', 'Chef/Black'),
    ('executive/red', 'Executive/Red')
)

ADDRESS_CHOICES = (
    ('eisenhower', 'Eisenhower'),
    ('wheeler', 'Wheeler'),
)


class Contact(models.Model):
    first_name = models.CharField(max_length=100, help_text="First Name")
    last_name = models.CharField(max_length=100, help_text="Last Name")
    email_address = models.EmailField(max_length=275)
    address = models.CharField(max_length=10, choices=ADDRESS_CHOICES)

    def __unicode__(self):
        return "%s %s" % (self.first_name, self.last_name)


class BaseStationary(models.Model):
    contact = models.ForeignKey(Contact, related_name='%(class)s_related')
    address = models.CharField(max_length=10, choices=ADDRESS_CHOICES)
    quantity = models.CharField(max_length=4, choices=QUANTITY_CHOICES)

    class Meta:
        abstract = True


class LetterHead(BaseStationary):
    pass


class WindowEnv(BaseStationary):
    pass


class NumberTenEnv(BaseStationary):
    pass


class NineByTwelveEnv(BaseStationary):
    pass


class TenByThirteenEnv(BaseStationary):
    pass


class BusinessCard(models.Model):
    contact = models.ForeignKey(Contact, related_name='businesscards')
    card_first_name = models.CharField(max_length=100)
    card_last_name = models.CharField(max_length=100)
    title = models.CharField(max_length=100)
    print_choices = models.CharField(max_length=19, choices=PRINT_CHOICES)
    card_styles = models.CharField(max_length=12, choices=CARD_CHOICES)
    card_email_address = models.EmailField(max_length=275)
    office_phone_number = PhoneNumberField(_('main office phone number'),
        blank=True, null=True)
    toll_free_number = PhoneNumberField(_('toll free number'),
        blank=True, null=True)
    mobile_number = PhoneNumberField(_('mobile phone number'),
        blank=True, null=True)
    fax_number = PhoneNumberField(_('main office fax'),
        blank=True, null=True)
    card_mailing_address = models.CharField(max_length=10,
        choices=ADDRESS_CHOICES)
    card_quantity = models.CharField(max_length=3,
        choices=CARD_QUANTITY_CHOICES)


class RushOrder(models.Model):
    contact = models.ForeignKey(Contact, related_name='rushorders')
    rush_order = models.BooleanField()
    in_hand_date = models.DateField(blank=True, null=True)


class OrderNote(models.Model):
    contact = models.ForeignKey(Contact, related_name='ordernotes')
    add_note = models.BooleanField()
    notes = models.TextField()

因此,我再次尝试做的是将这些表单集保存到数据库中,这样管理员将保存固定订单以用于打印目的。

最佳答案

由于您是来这里学习的,并且您的代码非常复杂(我需要所有重现您的问题所需的代码,其中包括模型),因此我不会回答通过代码修复。

相反,您将学习如何使用调试器,这将修复“我仍然不知道哪里出了问题”。

  1. 安装ipdb,因为它比仅仅pdb更方便,pip install ipdb

  2. 设置断点,在你看来,添加这行import ipdb; ipdb.set_trace().

  3. 在开发服务器中运行代码,开发服务器应在断点处暂停,并显示其暂停处的代码。

  4. 了解ipdb,输入“h”,它会显示一个命令列表,尝试阅读每个命令的文档,你也可以查看this article其中包括一个视频。

  5. 单步执行代码,通过在调试器中键入“n”,解释器应移动到下一行代码,“d”进入,“u”进入out 等...您可以随时从提示符处执行 Python。

你会知道Python到底在做什么,修复“我仍然不知道我哪里出了问题”。而且,你会成为一个无敌的程序员(或者类似的东西哈哈哈)

关于python - 我的 View 和表单集保存时遇到问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12112172/

相关文章:

python - 在 Django ORM 中执行 Groupby

python - Ajax 成功调用显示带有表单数据的 div

Django help_text

python - 在 django 中从中间件生成/隐藏消息

python - 如何在 Python Pandas 中处理由于夏令时而具有可变时区偏移的时间序列?

python - 如何使用 SQLAlchemy ORM 替换 Postgres 数组元素?

python - Django 继承和永久链接

python - 新的数据框架,其中包含付款当月所支付债务的百分比

python - python sorted()中的反向第二排序特征

python - 如何在不知道要查询哪些字段的情况下构建 Django 查询?