python - Django 中的完整性错误

标签 python django

我在我的一个表单中添加了一个 Many2Many 字段,现在我在提交时收到 IntegrityError。确切的错误文本是

IntegrityError at /add_person/ hireterm_person.mail_lists may not be NULL

在我添加新字段之前它工作正常。当我查看有关调试更改的 POST 数据时,我看到它正在传递,所以我不知道中断发生在哪里。

模型

from django.db import models
from django.forms import ModelForm
from django import forms
from django.contrib.auth.models import User

class Mailists(models.Model):
    name = models.CharField(blank=True, max_length=100)
    email = models.CharField(blank=True, max_length=100)

    def __unicode__(self):
        return u'%s' % (self.name)

class Person(models.Model):
    ROLE_CHOICES = (
        ('Mrkt', 'Marketing'),
        ('Fin/Off', 'Finance / Office'),
        ('Care', 'Care'),
        ('Sales', 'Sales'),
        )
    ROLE_TYPE = (
        ('Full', 'Full Time'),
        ('Part', 'Part Time'), 
        ('Intern', 'Intern'),
        )

    first_name = models.CharField(blank=True, max_length=100)
    last_name = models.CharField(blank=True, max_length=100)
    date_added = models.DateField(auto_now_add=True)
    date_start = models.DateField(auto_now=False)
    role = models.CharField(max_length=100, default = "", choices = ROLE_CHOICES)
    manager = models.ForeignKey('self', limit_choices_to = {'is_manager': True}, null=True, blank=True)
    title = models.CharField(blank=True, max_length=100)
    role_type = models.CharField(max_length=100, default = "", choices = ROLE_TYPE)
    laptop_needed = models.BooleanField(default=True)
    phone_needed = models.BooleanField(default=True)
    desk_loco = models.CharField(blank=True, max_length=100)
    mail_lists = models.ManyToManyField(Mailists, blank=True)
    notes = models.CharField(blank=True, max_length=500)
    is_manager = models.BooleanField(default=False)
    is_active = models.BooleanField(default=True)

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

class PersonForm(ModelForm):
    mail_lists = forms.ModelMultipleChoiceField(queryset=Mailists.objects.all(), widget=forms.CheckboxSelectMultiple(), required=False)
    class Meta:
        model = Person

编辑

我添加了 mail_lists = request.POST.getlist('mail_lists')。当我向其中添加打印时,返回的列表是所有复选框,POST 数据仍然是单个字符串,最后一个复选框被选中。

浏览量

from hireterm.models import Person, Mailists, PersonForm
from django.shortcuts import get_object_or_404, render
from django.template import Context, loader
from django.http import HttpResponseRedirect, HttpResponse
from django.contrib.auth.decorators import login_required
from django.contrib.auth import authenticate, login
from django.contrib.auth import logout
from django.core.mail import send_mail

@login_required
def home(request):
    return render(request, 'hireterm/home.html')

def add_person(request):
    if request.method == 'POST':
        mail_lists = request.POST.getlist('mail_lists') 
        person_form = PersonForm(request.POST)
        if person_form.is_valid(): 
            person_form.save()
            return HttpResponseRedirect('/new_hire') # Redirect after POST

    else:
        person_form = PersonForm() # An unbound form

    return render(request, 'hireterm/additem.html', {
        'form': person_form,
    })

最佳答案

在你的领域:

mail_lists = models.ManyToManyField(Mailists, blank=True)

您已将 blank=True 添加到该字段,但未添加 null=True。这意味着您的数据库期望该字段具有值。因此,当它不存在时,您会收到错误消息。

null

If True, Django will store empty values as NULL in the database. Default is False. Note that empty string values will always get stored as empty strings, not as NULL. Only use null=True for non-string fields such as integers, booleans and dates. For both types of fields, you will also need to set blank=True if you wish to permit empty values in forms, as the null parameter only affects database storage (see blank).

blank

If True, the field is allowed to be blank. Default is False.

Note that this is different than null. null is purely database-related, whereas blank is validation-related. If a field has blank=True, form validation will allow entry of an empty value. If a field has blank=False, the field will be required.

这里有一些其他的解释:

关于python - Django 中的完整性错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18243149/

相关文章:

python - Pyodbc 未从 SQL Server 返回错误

python - 使用 f2py 编译 Fortran 模块

python - Django 或类似的复合主键

json - 结合 DjangoObjectType 和 ObjectType - Django, GraphQL

python - 迭代拟合多项式曲线

python - 将二维数组合并到现有的三维数组

Python:导入错误:没有名为 os 的模块

Django:查找多对多关系中的所有值,其中相关集的所有元素都符合特定条件

python - Django如何为模型属性自动生成唯一的数字/字符串

python - 如何复制文件,然后使用 python 将其保存为动态文件名