简体   繁体   English

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

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

Im getting a NOT NULL constraint error in my code when trying to save my model form, even though the fields I have left empty are optional (have set blank=True, null=True) in models.py尝试保存我的 model 表单时,我的代码中出现 NOT NULL 约束错误,即使我留空的字段在 models.py 中是可选的(已设置空白 = True,null = True)

Im very confused, what am I doing wrong?我很困惑,我做错了什么?

The error is popping up when I leave the first optional field blank (description).当我将第一个可选字段留空(描述)时,会弹出错误。 Filling any of them manually before work.save() pushes the issue to the next field, and passes when all fields are filled.在 work.save() 之前手动填写其中任何一个会将问题推送到下一个字段,并在所有字段都填满时通过。

EDIT: this also happens when trying to create a work instance from the admin dashboard.编辑:尝试从管理仪表板创建工作实例时也会发生这种情况。

models.py模型.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 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']

views.py视图.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})

i was facing the same problem as you , i made a sign up form, and it was giving me the same error because the .save() method was getting executed before i fill in the fields, there was no data to save, because of that: the fields type was None .我遇到了和你一样的问题,我做了一个注册表单,它给了我同样的错误,因为在我填写字段之前执行了.save()方法,没有要保存的数据,因为那:字段类型是None so i just implemented an if else statement to make sure that the .save() method won't be executed if the type of the field isn None , here is a snippet:所以我刚刚实现了一个 if else 语句,以确保如果字段的类型为None ,则不会执行.save()方法,这是一个片段:

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

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

相关问题 即使我设置null = True和blank = True,也会出现“此字段为必填”错误 - Getting “This field is required” error even though I set null=True and blank=True 尽管将null设置为true并将blank设置为true,但Django中的NOT NULL约束失败错误 - NOT NULL constraint failed error in django despite having null set to true and blank set to true 没有Null约束失败-null =已设置真 - Not Null Constraint Failed - null=True already set 为什么不能将Django模型的USPhoneNumberField设置为null = True,blank = True? - Why can't I set my Django Model's USPhoneNumberField to null=True, blank=True? ForeignKey 的 NOT NULL 约束失败(null=True) - NOT NULL constraint failed for ForeignKey(null=True) Django 2.0完整性错误非NULL约束失败 - Django 2.0 Integrity error Not NULL constraint failed Django Integrity错误:Not Null约束失败 - Django Integrity Error : Not Null constraint failed 不是 null 约束失败。 Django 模型-Postgres 相同的错误 null=True 与 null=False - Not null constraint failed. Django Models-Postgres Same error null=True as null=False Django模型blank = True,但是sql总是NOT NULL - Django model blank=True, but sql always NOT NULL 字段为null = True和blank = True序列化器JS中没有错误 - Field with null=True and blank=True serializer None error in JS
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM