繁体   English   中英

完整性错误不是 NULL 约束失败,即使我在 model 中设置了空白=真,空=真

[英]Integrity Error NOT NULL constraint failed even though I have set blank=True, null=True in my model

尝试保存我的 model 表单时,我的代码中出现 NOT NULL 约束错误,即使我留空的字段在 models.py 中是可选的(已设置空白 = True,null = True)

我很困惑,我做错了什么?

当我将第一个可选字段留空(描述)时,会弹出错误。 在 work.save() 之前手动填写其中任何一个会将问题推送到下一个字段,并在所有字段都填满时通过。

编辑:尝试从管理仪表板创建工作实例时也会发生这种情况。

模型.py

class Work(models.Model):
    ## core fields
    creator = models.ForeignKey(User, on_delete=models.CASCADE, blank=True, null=True,
                                   default=None)
    created = models.DateTimeField()
    modified = models.DateTimeField()
    work_slug = models.SlugField(max_length=50) # slug -> TBD: find way to assign default value to slug = archival number.

    archive = models.ForeignKey(Archive, on_delete=models.CASCADE)


    # superfolder -> replaces category, series etc with dynamic hierarchical database
    folder = models.ForeignKey(Folder, on_delete=models.CASCADE)
    

    # basic metadata fields
    name = models.CharField(max_length=50)
    year = models.CharField(max_length=50)
    medium = models.CharField(max_length=50)
    description = models.CharField(max_length=1200, blank=True, null=True)

    # optional metadata
    authors = models.CharField(max_length=50, blank=True, null=True)
    classification = models.CharField(max_length=50, blank=True, null=True)
    location = models.CharField(max_length=50, blank=True, null=True)
    link = models.URLField(max_length=50, blank=True, null=True)
    record_creator = models.CharField(max_length=50, blank=True, null=True) # revisit -> 

    # custom descriptors
    cd1_name = models.CharField(max_length=50, blank=True, null=True)
    cd1_value = models.CharField(max_length=50, blank=True, null=True)
    cd2_name = models.CharField(max_length=50, blank=True, null=True)
    cd2_value = models.CharField(max_length=50, blank=True, null=True)
    cd3_name = models.CharField(max_length=50, blank=True, null=True)
    cd3_value = models.CharField(max_length=50, blank=True, null=True)
    cd4_name = models.CharField(max_length=50, blank=True, null=True)
    cd4_value = models.CharField(max_length=50, blank=True, null=True)
    cd5_name = models.CharField(max_length=50, blank=True, null=True)
    cd5_value = models.CharField(max_length=50, blank=True, null=True)
    cd6_name = models.CharField(max_length=50, blank=True, null=True)
    cd6_value = models.CharField(max_length=50, blank=True, null=True)
    cd7_name = models.CharField(max_length=50, blank=True, null=True)
    cd7_value = models.CharField(max_length=50, blank=True, null=True)


    # Standardized Metadata


    # Methods
    def __str__(self):
        return 'Work: {}'.format(self.name)

    def save(self, *args, **kwargs):
        ''' On save, update timestamps '''
        user = get_current_user()

        if not self.id: # if the model is being created for the first time:
            self.creator = user # assign the currently logged in user as the creator
            self.created = timezone.now() # set the 'created' field to the current date and time
            # self.slug = **archival id of work (automatically determined)** 
        self.modified = timezone.now() # set the modified field to the current date and time. This is reassigned everytime the model is updated.

        return super(Work, self).save(*args, **kwargs)

forms.py

class WorkForm(ModelForm):
    class Meta:
        model = Work
        fields = ['name', 'year', 'medium', 'description', 'authors', 'classification', 'location', 'link', 'record_creator', 'cd1_name', 'cd1_value', 'cd2_name', 'cd2_value', 'cd3_name', 'cd3_value', 'cd4_name', 'cd4_value', 'cd5_name', 'cd5_value', 'cd6_name', 'cd6_value', 'cd7_name', 'cd7_value']

视图.py

def add_work(request, folder_pk):
    '''
    Add a work to the filesystem.

    folder_pk: the primary key of the parent folder

    Checks if the user is logged in and if the user is the creator of the folder. If so, the user is allowed to add a work to the folder. Otherwise, the user is redirected to the login page.
    '''
    # add work to the database
    parent = Folder.objects.get(pk=folder_pk)
    mediaFormSet = modelformset_factory(MediaFile, fields=('name', 'alt_text', 'caption', 'media'), extra=1)

    

    if request.method == "POST" and parent.archive.creator == get_current_user():
        # if the form has been submitted
        # Serve the form -> request.POST
        form = WorkForm(request.POST)
        # mediaFormSet = mediaFormSet(request.POST)

        if form.is_valid(): # if the all the fields on the form pass validation

            # Generate archival ID for work
            # archival ID is random, unique 6 digit number that identifies the work
            archival_id = get_archival_id()

            # create a new work with the parameters retrieved from the form. currently logged in user is automatically linked
            work = form.save(commit=False)
            work.work_slug = archival_id
            work.folder=parent
            work.archive=parent.archive
            work.save()
            
            # Redirect to dashboard page
            return redirect('add_media_to_work', work_pk=work.pk)

    else:
        # If the form is not submitted (page is loaded for example)
        # -> Serve the empty form
        form = WorkForm()


    return render(request, "archival/add_edit_work.html", {"workForm": form})

我遇到了和你一样的问题,我做了一个注册表单,它给了我同样的错误,因为在我填写字段之前执行了.save()方法,没有要保存的数据,因为那:字段类型是None 所以我刚刚实现了一个 if else 语句,以确保如果字段的类型为None ,则不会执行.save()方法,这是一个片段:

if field == None:
    pass
else:
    form.save()

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM