好的,这是我在上一个问题中的一次性问题:
all forms are not saving to my database using class based views
我仍然无法将这些表单保存到我的数据库中。我已经完成了这里完成的工作:
http://haineault.com/blog/155/
有多个内联form_sets,但无法弄清楚我缺少哪些不会保存。联系表单再次保存联系信息,但其他六个表单不会将选定的固定文件保存到数据库中。
我知道这里有很多代码:(
视图:
from django.conf import settings
from django.views.generic.edit import CreateView
from django.views.generic import TemplateView
from .models import *
from .forms import *
from .emailtemplates import OrderFormNotification
class OrderFormView(CreateView):
model = Contact
form_class = ContactForm
template_name = 'orderform.html'
success_url = 'thank-you'
def get_context_data(self, **kwargs):
context = super(OrderFormView, self).get_context_data(**kwargs)
formsets = dict(
letterhead_formset=LetterHeadFormSet(prefix='letterhead'),
windowenv_formset=WindowEnvFormSet(prefix='windowenv'),
numbertenenv_formset=NumberTenEnvFormSet(prefix='numbertenenv'),
ninebytwelveenv_formset=NineByTwelveEnvFormSet(prefix='ninebytwelveenv'),
tenbythirteenenv_formset=TenByThirteenEnvFormSet(prefix='tenbythirteenenv'),
businesscard_formset=BusinessCardFormSet(prefix='businesscard'),
)
context.update({
'letterhead_form': LetterHeadForm,
'windowenv_form': WindowEnvForm,
'numbertenenv_form': NumberTenEnvForm,
'ninebytwelveenv_form': NineByTwelveEnvForm,
'tenbythirteenenv_form': TenByThirteenEnvForm,
'businesscard_form': BusinessCardForm,
'rushorder_form': RushOrderForm,
'ordernote_form': OrderNoteForm,
})
context.update(formsets.items())
return context
def form_valid(self, form):
context = self.get_context_data()
letterhead_form = context['letterhead_formset']
windowenv_form = context['windowenv_formset']
numbertenenv_form = context['numbertenenv_formset']
ninebytwelveenv_form = context['ninebytwelveenv_formset']
tenbythirteenenv_form = context['tenbythirteenenv_formset']
businesscard_form = context['businesscard_formset']
if form.is_valid() and letterhead_form.is_valid() and windowenv_form.is_valid()\
and numbertenenv_form.is_valid() and ninebytwelveenv_form.is_valid()\
and tenbythirteenenv_form.is_valid() and businesscard_form.is_valid():
self.object = form.save()
letterhead_form.instance = self.object
letterhead_form.save()
windowenv_form.instance = self.object
windowenv_form.save()
numbertenenv_form.instance = self.object
numbertenenv_form.save()
ninebytwelveenv_form.instance = self.object
ninebytwelveenv_form.save()
tenbythirteenenv_form.instance = self.object
tenbythirteenenv_form.save()
businesscard_form.instance = self.object
businesscard_form.save()
data = form.cleaned_data
email = OrderFormNotification(to=[settings.NO_REPLY_EMAIL_ADDRESS, ],
extra_context=data)
email.send()
else:
return super(OrderFormView, self).form_valid(form)
def get_context_data(self, **kwargs):
context = super(OrderFormView, self).get_context_data(**kwargs)
if self.request.POST:
context['letterhead_form'] = LetterHeadFormSet(self.request.POST)
context['windowenv_form'] = WindowEnvFormSet(self.request.POST)
context['numbertenenv_form'] = NumberTenEnvFormSet(self.request.POST)
context['ninebytwelveenv_form'] = NineByTwelveEnvFormSet(self.request.POST)
context['tenbythirteenenv_form'] = TenByThirteenEnvFormSet(self.request.POST)
context['businesscard_form'] = BusinessCardFormSet(self.request.POST)
else:
context['letterhead_form'] = LetterHeadFormSet()
context['windowenv_form'] = WindowEnvFormSet()
context['numbertenenv_form'] = NumberTenEnvFormSet()
context['ninebytwelveenv_form'] = NineByTwelveEnvFormSet()
context['tenbythirteenenv_form'] = TenByThirteenEnvFormSet()
context['businesscard_form'] = BusinessCardFormSet()
return context
形式:
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()
HTML:
{% load i18n %}
<!doctype html>
<title>Cuisine Solutions - Order Form</title>
<meta name="description" content="">
<meta name="author" content="">
<!-- For iPhone 4 -->
<link rel="apple-touch-icon-precomposed" sizes="114x114" href="apple-touch-icon.png">
<!-- For iPad 1-->
<link rel="apple-touch-icon-precomposed" sizes="72x72" href="apple-touch-icon.png">
<!-- For iPhone 3G, iPod Touch and Android -->
<link rel="apple-touch-icon-precomposed" href="apple-touch-icon-precomposed.png">
<!-- For Nokia -->
<link rel="shortcut icon" href="apple-touch-icon.png">
<!-- For everything else -->
<link rel="shortcut icon" href="/favicon.ico">
<!--iOS. Delete if not required -->
<meta name="apple-mobile-web-app-capable" content="yes">
<meta name="apple-mobile-web-app-status-bar-style" content="black-translucent">
<link rel="apple-touch-startup-image" href="img/splash.png">
<!--Microsoft. Delete if not required -->
<meta http-equiv="cleartype" content="on">
<meta http-equiv="X-UA-Compatible" content="IE=edge,chrome=1">
<!-- http://t.co/dKP3o1e -->
<meta name="HandheldFriendly" content="True">
<meta name="MobileOptimized" content="320">
<meta name="viewport" content="width=device-width, target-densitydpi=160dpi, initial-scale=1">
<link rel="stylesheet" type="text/css" href="css/uniform.aristo.css" >
<link rel="stylesheet" type="text/css" href="css/style.css" >
<!-- http://t.co/y1jPVnT -->
<link rel="canonical" href="/">
<script type="text/javascript" src="https://ajax.googleapis.com/ajax/libs/jquery/1.6.4/jquery.min.js" ></script>
<script type="text/javascript" src="js/jFormer-uncompressed.js" ></script>
<script type="text/javascript" src="js/jquery.uniform.js" ></script>
<script type="text/javascript" src="http://use.typekit.com/fso1uib.js"></script>
<script type="text/javascript">try{Typekit.load();}catch(e){}</script>
{% block orderform.scripts %}
<script type="text/javascript">
$(function() {
$('.formrow.inline.{{ letterhead_formset.prefix }}').formset({
prefix: '{{ letterhead_formset.prefix }}',
})
$('.formrow.inline.{{ windowenv_formset.prefix }}').formset({
prefix: '{{ windowenv_formset.prefix }}',
})
$('.formrow.inline.{{ numbertenenv_formset.prefix }}').formset({
prefix: '{{ numbertenenv_formset.prefix }}',
})
$('.formrow.inline.{{ ninebytwelveenv_formset.prefix }}').formset({
prefix: '{{ ninebytwelveenv_formset.prefix }}',
})
$('.formrow.inline.{{ tenbythirteenenv_formset.prefix }}').formset({
prefix: '{{ tenbythirteenenv_formset.prefix }}',
})
$('.formrow.inline.{{ businesscard_formset.prefix }}').formset({
prefix: '{{ businesscard_formset.prefix }}',
})
})
</script>
{% endblock %}
<div id="container">
<header>
<div id="logo">Cuisine Solutions</div>
<h1>Stationery and Business Card Order Form</h1>
</header>
<ul>
<li>Letterhead and envelope orders will be sent directly to print. Proofs will not be generated.</li>
<li>Business card proofs will be sent to you within one business day. You must approve business card proofs before files are sent to print.</li>
<li>For all orders, please allow 7—10 business days for printing and delivery unless "rush order" is selected below. Rush orders will incur additional fees.</li>
<li><a href="CS_Order_Form_Pricing.pdf" target="_blank">Click here</a> to download pricing information. For questions or concerns, please email <a href="mailto:orders@hzdg.com">orders@hzdg.com</a>.</li>
</ul>
<div class="form-name">
<p>Add your contact information</p>
</div>
<form action="" method="post">{% csrf_token %}
<div id="contact-form">
<div class="field-wrapper">
<p><label for="full-name">Full Name:*</label></p>
<div>{{ form.first_name }}{{ form.last_name }}</div>
<div class="help-text">{{ form.first_name.help_text }}</div><div class="help-text">{{ form.last_name.help_text }}</div>
<div class="errors">{{ form.first_name.errors }}{{ form.last_name.errors }}</div>
</div>
<div class="field-wrapper">
<h4><label for="full-name">E-mail Address:*</label></h4>
<div>{{ form.email_address }}</div>
<div class="errors clearfix">{{ form.email_address.errors }}</div>
</div>
<div class="field-wrapper clearfix">
<div class="stationary-address-label">Address:</div>
<div class="stationary-address-radio">{{ form.address }}</div>
<div class="errors clearfix">{{ form.address.errors }}</div>
</div>
</div>
<div class="form-name">
<h4>Letterhead</h4>
</div>
<div class="letterhead-form clearfix">
{{letterhead_formset.management_form}}
{% for form in letterhead_formset %}
{% if forloop.counter == 1 %}
<div>
{% else %}
<button id="add-letterhead">Add Another Letterhead</button>
<div id="letterhead-form-two">
<button id="hide-letterhead-form">Remove Letterhead Form</button>
<div class="form-name clearfix">
<h4>Letterhead(2)</h4>
</div>
{% endif %}
{% for field in form %}
{% include "includes/letterhead-form.html" %}
{% endfor %}
</div>
{% endfor %}
</div>
<div class="form-name">
<h4>Window Envelopes</h4>
</div>
<div class="windowenv-form clearfix">
{{windowenv_formset.management_form}}
{% for form in windowenv_formset %}
{% if forloop.counter == 1 %}
<div>
{% else %}
<button id="add-windowenv">Add Another Window Envelope</button>
<div id="windowenv-form-two">
<button id="hide-windowenv-form">Remove Window Envelope Form</button>
<div class="form-name clearfix">
<h4>Window Envelopes(2)</h4>
</div>
{% endif %}
{% for field in form %}
{% include "includes/windowenv-form.html" %}
{% endfor %}
</div>
{% endfor %}
</div>
<div class="form-name">
<h4>#10 Envelopes</h4>
</div>
<div class="numberten-form clearfix">
{{numbertenenv_formset.management_form}}
{% for form in numbertenenv_formset %}
{% if forloop.counter == 1 %}
<div>
{% else %}
<button id="add-numbertenenv">Add Another #10 Envelope</button>
<div id="numbertenenv-form-two">
<button id="hide-numbertenenv-form">Remove #10 Envelope Form</button>
<div class="form-name clearfix">
<h4>#10 Envelopes(2)</h4>
</div>
{% endif %}
{% for field in form %}
{% include "includes/numbertenenv-form.html" %}
{% endfor %}
</div>
{% endfor %}
</div>
<div class="form-name">
<h4>9 x 12 Envelopes</h4>
</div>
<div class="ninebytwelveenv-form clearfix">
{{ninebytwelveenv_formset.management_form}}
{% for form in ninebytwelveenv_formset %}
{% if forloop.counter == 1 %}
<div>
{% else %}
<button id="add-ninebytwelveenv">Add Another 9X12 Envelope</button>
<div id="ninebytwelveenv-form-two">
<button id="hide-ninebytwelveenv-form">Remove 9X12 Envelope Form</button>
<div class="form-name clearfix">
<h4>9X12 Envelopes(2)</h4>
</div>
{% endif %}
{% for field in form %}
{% include "includes/ninebytwelveenv-form.html" %}
{% endfor %}
</div>
{% endfor %}
</div>
<div class="form-name">
<h4>10 x 13 Envelopes</h4>
</div>
<div class="tenbythirteen-form">
{{tenbythirteenenv_formset.management_form}}
{% for form in tenbythirteenenv_formset %}
{% if forloop.counter == 1 %}
<div>
{% else %}
<button id="add-tenbythirteenenv">Add Another 10X13 Envelope</button>
<div id="tenbythirteenenv-form-two">
<button id="hide-tenbythirteenenv-form">Remove 10X13 Envelope Form</button>
<div class="form-name clearfix">
<h4>10X13 Envelopes(2)</h4>
</div>
{% endif %}
{% for field in form %}
{% include "includes/tenbythirteenenv-form.html" %}
{% endfor %}
</div>
{% endfor %}
</div>
<div class="form-name">
<h4>Business Cards</h4>
</div>
<div class="businesscard-form clearfix">
{{businesscard_formset.management_form}}
{% for form in businesscard_formset %}
{% if forloop.counter == 1 %}
<div>
{% else %}
<button id="add-businesscard">Add Another Business Card</button>
<div id="businesscard-form-two">
<button id="hide-businesscard-form">Remove business Envelope Form</button>
<div class="form-name clearfix">
<h4>Business Card(2)</h4>
</div>
{% endif %}
{% for field in form %}
{% include "includes/businesscard-form.html" %}
{% endfor %}
</div>
{% endfor %}
</div>
<div class="form-name">
<h4>Extras</h4>
</div>
<div id="rushorder-form">
<div class="field-wrapper">
<div class="rush-checkbox">{{ rushorder_form.rush_order.errors }}{{ rushorder_form.rush_order }}<span class="rush-label">Is This A Rush Order</span></div>
<div class="rush-dates">{{ rushorder_form.in_hand_date.errors }}{{ rushorder_form.in_hand_date }}</div>
</div>
</div>
<div id="ordernote-form">
<div class="field-wrapper">
<div class="notes-checkbox">{{ ordernote_form.add_note.errors }}{{ ordernote_form.add_note }}<span class="notes-label">Add A Note</span></div>
<div class="notes">{{ ordernote_form.notes.errors }}{{ ordernote_form.notes }}</div>
</div>
</div>
<input id="orderform-submit" type="submit" value="Submit" />
</form>
</div>
<footer class="clearfix">
<p></p>
</footer>
<script>
$(function() {
$('.rush-dates').hide();
$('.notes').hide();
$('#letterhead-form-two').hide();
$('#windowenv-form-two').hide();
$('#numbertenenv-form-two').hide();
$('#ninebytwelveenv-form-two').hide();
$('#tenbythirteenenv-form-two').hide();
$('#businesscard-form-two').hide();
$("#add-letterhead").click(function (e) {
$("#letterhead-form-two").show();
$("#add-letterhead").hide();
e.preventDefault();
});
$("#add-windowenv").click(function (e) {
$("#windowenv-form-two").show();
$("#add-windowenv").hide();
e.preventDefault();
});
$("#add-numbertenenv").click(function (e) {
$("#numbertenenv-form-two").show();
$("#add-numbertenenv").hide();
e.preventDefault();
});
$("#add-ninebytwelveenv").click(function (e) {
$("#ninebytwelveenv-form-two").show();
$("#add-ninebytwelveenv").hide();
e.preventDefault();
});
$("#add-tenbythirteenenv").click(function (e) {
$("#tenbythirteenenv-form-two").show();
$("#add-tenbythirteenenv").hide();
e.preventDefault();
});
$("#add-businesscard").click(function (e) {
$("#businesscard-form-two").show();
$("#add-businesscard").hide();
e.preventDefault();
});
$("#hide-letterhead-form").click(function (e) {
$("#letterhead-form-two").hide();
$("#add-letterhead").show();
e.preventDefault();
});
$("#hide-windowenv-form").click(function (e) {
$("#windowenv-form-two").hide();
$("#add-windowenv").show();
e.preventDefault();
});
$("#hide-numbertenenv-form").click(function (e) {
$("#numbertenenv-form-two").hide();
$("#add-numbertenenv").show();
e.preventDefault();
});
$("#hide-ninebytwelveenv-form").click(function (e) {
$("#ninebytwelveenv-form-two").hide();
$("#add-ninebytwelveenv").show();
e.preventDefault();
});
$("#hide-tenbythirteenenv-form").click(function (e) {
$("#tenbythirteenenv-form-two").hide();
$("#add-tenbythirteenenv").show();
e.preventDefault();
});
$("#hide-businesscard-form").click(function (e) {
$("#businesscard-form-two").hide();
$("#add-businesscard").show();
e.preventDefault();
});
$(".rush-checkbox input").click(function(){
$(this).is(':checked') ? $(".rush-dates").show() : $(".rush-dates").hide();
});
$(".notes-checkbox input").click(function(){
$(this).is(':checked') ? $(".notes").show() : $(".notes").hide();
});
});
</script>
每个包含:
{% if field.is_hidden %}
{{ field }}
{% else %}
<div class="formrow inline {{ letterhead_formset.prefix }}">
{% for error in field.errors %}
<div class="errorField">
{{ error }}
</div>
{% endfor %}
<label for="id_{{ field.name }}"{% if field.field.required %} class="required"{% endif %}>{{ field.label|safe }}</label>
{{ field }}
{% if field.help_text %}
<span>{{ field.help_text|safe }}</span>
{% endif %}
</div>
{% endif %}