NOT NULL约束失败:使用我的create函数

时间:2018-01-16 03:00:53

标签: django django-models django-forms django-views

我正在尝试使用一个生成2个表单的视图,并使用一个按钮保存它们。我对如何在更新视图中完成此操作有一个好主意,所以我试图在创建视图中应用相同的逻辑。一切似乎都工作正常,但我得到一个NOT NUlL约束失败错误。我意识到这个错误与我的第二种形式有关,可能无法找到附加自己的“载体”,我只是不知道如何去解决它。

这是我的代码:

MODELS.PY

class Carrier(models.Model):
    carrier_name = models.CharField(max_length=255, unique=True)
    mc_number = models.CharField(max_length=10, unique=True, blank=True)
    dot_number = models.CharField(max_length=15, unique=True, blank=True)
    carrier_ein = models.CharField(max_length=9, unique=True)
    carrier_phone = models.CharField(max_length=10)
    carrier_phone_two = models.CharField(max_length=10, blank=True)
    carrier_phone_three = models.CharField(max_length=10, blank=True)
    carrier_fax = models.CharField(max_length=10, blank=True)
    carrier_email = models.CharField(max_length=50, blank=True)

    US_STATES_OR_CAN_PROVINCES = (
        ('AK', 'Alaska'),
        ('AL', 'Alabama'),
        ('AR', 'Arkansas'),
        ('AS', 'American Samoa'),
        ('AZ', 'Arizona'),
        ('CA', 'California'),
        ('CO', 'Colorado'),
        ('CT', 'Connecticut'),
        ('DC', 'District of Columbia'),
        ('DE', 'Delaware'),
        ('FL', 'Florida'),
        ('GA', 'Georgia'),
        ('GU', 'Guam'),
        ('HI', 'Hawaii'),
        ('IA', 'Iowa'),
        ('ID', 'Idaho'),
        ('IL', 'Illinois'),
        ('IN', 'Indiana'),
        ('KS', 'Kansas'),
        ('KY', 'Kentucky'),
        ('LA', 'Louisiana'),
        ('MA', 'Massachusetts'),
        ('MD', 'Maryland'),
        ('ME', 'Maine'),
        ('MI', 'Michigan'),
        ('MN', 'Minnesota'),
        ('MO', 'Missouri'),
        ('MP', 'Northern Mariana Islands'),
        ('MS', 'Mississippi'),
        ('MT', 'Montana'),
        ('NA', 'National'),
        ('NC', 'North Carolina'),
        ('ND', 'North Dakota'),
        ('NE', 'Nebraska'),
        ('NH', 'New Hampshire'),
        ('NJ', 'New Jersey'),
        ('NM', 'New Mexico'),
        ('NV', 'Nevada'),
        ('NY', 'New York'),
        ('OH', 'Ohio'),
        ('OK', 'Oklahoma'),
        ('OR', 'Oregon'),
        ('PA', 'Pennsylvania'),
        ('PR', 'Puerto Rico'),
        ('RI', 'Rhode Island'),
        ('SC', 'South Carolina'),
        ('SD', 'South Dakota'),
        ('TN', 'Tennessee'),
        ('TX', 'Texas'),
        ('UT', 'Utah'),
        ('VA', 'Virginia'),
        ('VI', 'Virgin Islands'),
        ('VT', 'Vermont'),
        ('WA', 'Washington'),
        ('WI', 'Wisconsin'),
        ('WV', 'West Virginia'),
        ('WY', 'Wyoming'),
        ('AB', 'Alberta'),
        ('BC','British Columbia'),
        ('MB', 'Manitoba'),
        ('NB', 'New Brunswick'),
        ('NL', 'Newfoundland and Labrador'),
        ('NT', 'Northwest Territories'),
        ('NS', 'Nova Scotia'),
        ('NU', 'Nunavut'),
        ('ON', 'Ontario'),
        ('PE', 'Prince Edward Island'),
        ('QC', 'Quebec'),
        ('SK', 'Saskatchewan'),
        ('YT', 'Yukon')
    )
    COUNTRIES = (
        ('USA', 'United States'),
        ('CAN', 'Canada')
    )
    carrier_city = models.CharField(max_length=255)
    carrier_state_prov = models.CharField(max_length=2,
                                            choices=US_STATES_OR_CAN_PROVINCES)
    carrier_zipcode = models.CharField(max_length=5)
    carrier_country = models.CharField(max_length=3, choices=COUNTRIES)
    carrier_notes = models.TextField()

    def __str__(self):
        return self.carrier_name

class CarrierDocuments(models.Model):
    carrier = models.OneToOneField(Carrier, related_name='carrier_documents',
                                            on_delete=models.CASCADE)
    broker_carrier_agreement = models.FileField(
                                upload_to='broker_carrier_agreement/%Y/%m/%d/', blank=True)
    carrier_w9 = models.FileField(upload_to='w9/%Y/%m/%d/', blank=True)
    insurance = models.FileField(upload_to='insurance/%Y/%m/%d/', blank=True)
    payment_instructions = models.FileField(upload_to='pay_instructions/%Y/%m/%d/', blank=True)
    uploaded_at = models.DateTimeField(auto_now_add=True)

VIEWS.PY

def create_carrier(request):
    if request.method == 'POST':
        carrier_form = CarrierCreateForm(request.POST)
        carrier_documents = CarrierDocumentsUpload(request.POST, request.FILES)
        if carrier_form.is_valid() and carrier_documents.is_valid():
            carrier_form.save()
            carrier_documents.save()
            messages.success(request, ('Carrier created!'))
            return redirect('carriers:all')
        else:
            messages.error(request, ('Please correct the error below.'))
    else:
        carrier_form = CarrierCreateForm()
        carrier_documents = CarrierDocumentsUpload()
    return render(request, 'carriers/create_carrier.html', {
        'carrier_form': carrier_form,
        'carrier_documents': carrier_documents,
    })

FORMS.PY

class CarrierCreateForm(forms.ModelForm):
    class Meta:
        model = Carrier
        fields = ['carrier_name', 'mc_number', 'dot_number', 'carrier_ein',
                'carrier_phone', 'carrier_phone_two', 'carrier_phone_three',
                'carrier_fax', 'carrier_email', 'carrier_city', 'carrier_state_prov',
                'carrier_zipcode', 'carrier_country','carrier_notes']

class CarrierDocumentsUpload(forms.ModelForm):
    class Meta:
        model = CarrierDocuments
        fields = ['broker_carrier_agreement', 'carrier_w9', 'insurance',
                'payment_instructions']

我认为在我看来,我基本上只是同时提交两个表单而不实际连接它们。根据我的研究,这样的事情应该有效。但我仍然得到了约束错误。

if carrier_form.is_valid() and carrier_documents.is_valid():
    carrier = carrier_form(commit=False)
    carrier_documents.save()
    carrier_documents.carrier = carrier
    carrier.save()
    messages.success(request, ('Carrier created!'))
    return redirect('carriers:all')

任何输入都将不胜感激。谢谢,

根据以下答案进行更新

这个确实将我的“载体”和我上传的文件保存到了正确的位置,但我仍然得到了contstraint错误。

def create_carrier(request):
    if request.method == 'POST':
        carrier_form = CarrierCreateForm(request.POST)
        carrier_documents = CarrierDocumentsUpload(request.POST, request.FILES)
        if carrier_form.is_valid() and carrier_documents.is_valid():
            carrier = carrier_form.save(commit=False)
            carrier.save()
            carrier_documents.carrier = carrier
            carrier_documents.save()
            messages.success(request, ('Carrier created!'))
            return redirect('carriers:all')
        else:
            messages.error(request, ('Please correct the error below.'))
    else:
        carrier_form = CarrierCreateForm()
        carrier_documents = CarrierDocumentsUpload()
    return render(request, 'carriers/create_carrier.html', {
        'carrier_form': carrier_form,
        'carrier_documents': carrier_documents,
    })

2 个答案:

答案 0 :(得分:0)

if carrier_form.is_valid() and carrier_documents.is_valid():
carrier = carrier_form(commit=False)
carrier.save()
carrier_documents.carrier = carrier
carrier_documents.save()
messages.success(request, ('Carrier created!'))
return redirect('carriers:all')

交换carrier和carrier_document save()方法。

答案 1 :(得分:0)

def create_carrier(request):
    carrier_form = CarrierCreateForm(request.POST or None)
    carrier_documents = CarrierDocumentsUpload(request.POST or None, request.FILES or None) 
    if request.method == 'POST':        
        if carrier_form.is_valid() and carrier_documents.is_valid():
           carrier = carrier_form.save(commit=False)
           carrier.save()
           carrier2=carrier_documents.save(commit=False)
           carrier2.carrier = carrier
           carrier2.save()
           messages.success(request, ('Carrier created!'))
           return redirect('carriers:all')
    return render(request, 'carriers/create_carrier.html', {
        'carrier_form': carrier_form,
        'carrier_documents': carrier_documents,
})  

试试这个