Python 在保存视图和表单集时遇到问题

Python 在保存视图和表单集时遇到问题,python,django,django-forms,django-views,Python,Django,Django Forms,Django Views,我在保存我的观点和表单集时遇到了最困难的时刻。我逐渐意识到,在Django,观点是我的弱点。在过去的几个月里,我一直在研究这个问题,并编写和重写代码。我知道这是最好的学习方式。幸运的是,我的团队给了我这个项目来学习。但我仍然不知道我错在哪里 如果这里有人看到我在哪里,或者给我指出正确的方向,我会非常感激。我正在寻找最好的资源来加强这方面的实力 以下是我的看法: from django.conf import settings from django.views.generic import Vi

我在保存我的观点和表单集时遇到了最困难的时刻。我逐渐意识到,在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()

同样,我要做的是将这些表单集保存到数据库中,这样管理员就可以保存固定订单以供打印

既然您是来学习的,而且您的代码非常复杂(我需要所有的代码来重现您的问题,其中包括模型),我不打算用代码修复来回答

相反,您将学习如何使用调试器,它将修复“我仍然不知道我在哪里出错”

  • 安装ipdb,因为它比pdb更方便,
    pip安装ipdb

  • 设置断点,在您的视图中,添加此行
    导入ipdb;ipdb.set_trace()

  • 在devserver中运行代码,devserver应该在断点处暂停,并显示暂停的代码

  • 了解ipdb,键入“h”,它将显示命令列表,尝试阅读每个命令的文档,您还可以检查其中包含的视频

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


  • 您将知道Python到底在做什么,修复“我仍然不知道哪里出了问题”。此外,您将成为一名不可战胜的程序员(或类似的东西,哈哈哈)

    非常感谢!我现在就准备好了!同时,我也会添加模型,不过我不想寻找答案:)再次感谢你!我得到了ipdb设置和工作,这导致我发现我的foreignkey for contact为null,这不允许保存。那么现在继续说:)