Django:来自处方集的外键列不起作用

时间:2017-02-01 12:41:36

标签: python django

我正在与Django 1.10.5合作,我收到错误消息,我找不到解决方案。除了表BirthCertificate(见上文)之外,所有模型似乎都能正常运行并且所有表格都是正确的。

我的第一个应用程序中有一个模型文件: Identity models.py

#-*- coding: utf-8 -*-

class Identity(models.Model):

    title = models.CharField(max_length=12,choices=TITLE_CHOICES, verbose_name='Civilité')
    lastname = models.CharField(max_length=30, verbose_name='Nom de famille')
    firstname = models.CharField(max_length=30, verbose_name='Prénom(s)')
    sex = models.CharField(max_length=8, choices=SEX_CHOICES, verbose_name='Sexe')
    birthday = models.DateField(verbose_name='Date de naissance')
    birthcity = models.CharField(max_length=30, verbose_name='Ville de naissance')
    birthcountry = CountryField(blank_label='Sélectionner un pays', verbose_name='Pays de naissance')
    nationality = models.CharField(max_length=30, verbose_name='Nationalité')
    job = models.CharField(max_length=30, verbose_name='Profession')
    adress = models.CharField(max_length=30, verbose_name='Adresse')
    city = models.CharField(max_length=30, verbose_name='Ville')
    zip = models.IntegerField(verbose_name='Code Postal')
    country = CountryField(blank_label='Sélectionner un pays', verbose_name='Pays')
    mail = models.CharField(max_length=30, verbose_name='Email', blank=True)
    phone = models.CharField(max_length=20, verbose_name='Téléphone', blank=True)

    def __unicode__(self):
        return '%s %s %s %s %s %s %s %s %s %s %s %s %s %s %s %s' % (self.id, self.title, self.lastname, self.firstname, self.sex, self.birthday, self.birthcity, self.birthcountry,
                                                                    self.nationality, self.job, self.adress, self.city, self.zip, self.country, self.mail, self.phone)

然后我的第二个应用程序中有另一个模型: BirthCertificate models.py ,它从身份模型中获取两个外键:

#-*- coding: utf-8 -*-


class BirthCertificate(models.Model):

    lastname = models.CharField(max_length=30, null=False, verbose_name='Nom de famille')
    firstname = models.CharField(max_length=30, null=False, verbose_name='Prénom(s)')
    sex = models.CharField(max_length=8, choices=SEX_CHOICES, verbose_name='Sexe')
    birthday = models.DateField(null=False, verbose_name='Date de naissance')
    birthhour = models.TimeField(null=True, verbose_name='Heure de naissance')
    birthcity = models.CharField(max_length=30, null=False, verbose_name='Ville de naissance')
    birthcountry = CountryField(blank_label='Sélectionner un pays', verbose_name='Pays de naissance')
    fk_parent1 = models.ForeignKey(Identity, related_name='ID_Parent1', verbose_name='ID parent1', null=False)
    fk_parent2 = models.ForeignKey(Identity, related_name='ID_Parent2', verbose_name='ID parent2', null=False)
    folderId = models.CharField(max_length=15, null=True)

然后,我在BirthCertificate应用程序中有一个表格,我填写。我可以在此表单中选择一些身份ID。但是,当我填写并验证我的表单时,我收到此错误:

Exception Value: (1048, "Column 'fk_parent1_id' cannot be null")

但是,此列不为空,因为我在选择列表中选择了一个人物:

enter image description here

我也使用表单函数输入 BirthCertificate views.py 文件:

import requests, os, json, glob
from django.shortcuts import render, reverse, get_object_or_404
from django.contrib.auth.decorators import login_required
from django.http import HttpResponseRedirect, HttpResponse
from .models import BirthCertificate
from Identity.models import Identity
from .forms import BirthCertificateForm
from django.db import connection
from django.template import Context
from django.template.loader import get_template
from xhtml2pdf import pisa

@login_required
def BirthCertificate_Form(request) :
    # Fonction permettant de créer le formulaire Acte de Naissance et le remplissage

    if request.method == 'POST':

        Bform = BirthCertificateForm(request.POST or None)

        if Bform.is_valid() :   # Vérification sur la validité des données
            if '_preview2' in request.POST :
                post = Bform.save(commit=False)
                template_name = 'BC_preview.html'

            elif '_save2' in request.POST :
                post = Bform.save()
                return HttpResponseRedirect(reverse('BC_treated', kwargs={'id': post.id}))

    else:
        Bform = BirthCertificateForm()

    return render(request, 'BC_form.html', {"Bform" : Bform})

你有解决方案吗? 如果您需要某些文件或视图,请告诉我,因为我花了2天没有找到解决问题的方法。

编辑完全跟踪

Environment:


Request Method: POST
Request URL: http://localhost:8000/BirthCertificate/formulaire

Django Version: 1.10.5
Python Version: 2.7.12
Installed Applications:
['django.contrib.admin',
 'django.contrib.auth',
 'django.contrib.contenttypes',
 'django.contrib.sessions',
 'django.contrib.messages',
 'django.contrib.staticfiles',
 'BirthCertificate',
 'Identity',
 'bootstrapform',
 'Accueil',
 'captcha',
 'django_countries',
 'log',
 'Mairie']
Installed Middleware:
['django.contrib.sessions.middleware.SessionMiddleware',
 'django.middleware.locale.LocaleMiddleware',
 'django.middleware.common.CommonMiddleware',
 'django.middleware.csrf.CsrfViewMiddleware',
 'django.middleware.gzip.GZipMiddleware',
 'django.contrib.auth.middleware.AuthenticationMiddleware',
 'django.contrib.auth.middleware.SessionAuthenticationMiddleware',
 'django.contrib.messages.middleware.MessageMiddleware',
 'django.middleware.clickjacking.XFrameOptionsMiddleware',
 'django.middleware.security.SecurityMiddleware']



Traceback:

File "/usr/local/lib/python2.7/site-packages/django/core/handlers/exception.py" in inner
  39.             response = get_response(request)

File "/usr/local/lib/python2.7/site-packages/django/core/handlers/base.py" in _legacy_get_response
  249.             response = self._get_response(request)

File "/usr/local/lib/python2.7/site-packages/django/core/handlers/base.py" in _get_response
  187.                 response = self.process_exception_by_middleware(e, request)

File "/usr/local/lib/python2.7/site-packages/django/core/handlers/base.py" in _get_response
  185.                 response = wrapped_callback(request, *callback_args, **callback_kwargs)

File "/usr/local/lib/python2.7/site-packages/django/contrib/auth/decorators.py" in _wrapped_view
  23.                 return view_func(request, *args, **kwargs)

File "/Users/valentinjungbluth/Desktop/Django/Etat_civil/BirthCertificate/views.py" in BirthCertificate_Form
  47.                 post = Bform.save()

File "/usr/local/lib/python2.7/site-packages/django/forms/models.py" in save
  453.             self.instance.save()

File "/usr/local/lib/python2.7/site-packages/django/db/models/base.py" in save
  796.                        force_update=force_update, update_fields=update_fields)

File "/usr/local/lib/python2.7/site-packages/django/db/models/base.py" in save_base
  824.             updated = self._save_table(raw, cls, force_insert, force_update, using, update_fields)

File "/usr/local/lib/python2.7/site-packages/django/db/models/base.py" in _save_table
  908.             result = self._do_insert(cls._base_manager, using, fields, update_pk, raw)

File "/usr/local/lib/python2.7/site-packages/django/db/models/base.py" in _do_insert
  947.                                using=using, raw=raw)

File "/usr/local/lib/python2.7/site-packages/django/db/models/manager.py" in manager_method
  85.                 return getattr(self.get_queryset(), name)(*args, **kwargs)

File "/usr/local/lib/python2.7/site-packages/django/db/models/query.py" in _insert
  1045.         return query.get_compiler(using=using).execute_sql(return_id)

File "/usr/local/lib/python2.7/site-packages/django/db/models/sql/compiler.py" in execute_sql
  1054.                 cursor.execute(sql, params)

File "/usr/local/lib/python2.7/site-packages/django/db/backends/utils.py" in execute
  79.             return super(CursorDebugWrapper, self).execute(sql, params)

File "/usr/local/lib/python2.7/site-packages/django/db/backends/utils.py" in execute
  64.                 return self.cursor.execute(sql, params)

File "/usr/local/lib/python2.7/site-packages/django/db/backends/mysql/base.py" in execute
  115.                 six.reraise(utils.IntegrityError, utils.IntegrityError(*tuple(e.args)), sys.exc_info()[2])

File "/usr/local/lib/python2.7/site-packages/django/db/backends/mysql/base.py" in execute
  110.             return self.cursor.execute(query, args)

File "/Library/Python/2.7/site-packages/MySQLdb/cursors.py" in execute
  205.             self.errorhandler(self, exc, value)

File "/Library/Python/2.7/site-packages/MySQLdb/connections.py" in defaulterrorhandler
  36.     raise errorclass, errorvalue

Exception Type: IntegrityError at /BirthCertificate/formulaire
Exception Value: (1048, "Column 'fk_parent1_id' cannot be null")

0 个答案:

没有答案