django.db.utils.IntegrityError: NOT NULL constraint failed: pages_add_music.upload error

django.db.utils.IntegrityError: NOT NULL constraint failed: pages_add_music.upload error

我写了一个代码来上传音乐图片并且它有效,但是当我尝试编辑旧帖子时(我还没有添加 img 字段)它显示以下错误:

django.db.utils.IntegrityError: NOT NULL constraint failed: pages_add_music.upload

Models.py

class add_music(models.Model):
    name = models.CharField(max_length=100)
    artist = models.CharField(max_length=100)
    nation = models.CharField(max_length=100)
    language = models.CharField(max_length=100)
    year = models.DecimalField(max_digits=4,decimal_places=0,null=True)
    genre = models.TextField()
    duration = models.DecimalField(max_digits=3,decimal_places=2,null=True)
    upload = models.DateTimeField(auto_now_add=True)
    img = models.ImageField(blank=True,null=True,upload_to='images/')
    def __str__(self):
        return self.name.title()+" by "+self.artist

观看次数:

def edit_music_view(request,music_id):
my_object = add_music.objects.get(id=music_id)

if request.method != 'POST':
    form = add_music_form(instance=my_object)
else:
    form = add_music_form(instance=my_object,data=request.POST)
    if form.is_valid():
        form.save()
context={'form':form,'my_object':my_object} 
return render(request,'pages/edit_music.html',context)

模板文件:

{% extends 'pages/base.html' %}

{% block content %}

<p>{{ my_object }}</p>

<form action="{% url 'pages:edit_music' my_object.id %}" method='post' enctype="multipart/form-data">
    {% csrf_token %}
    {{ form.as_p }}
    <button type="submit" value="yes">save</button>
</form>
{% endblock %}

怎么了?

您可以随时将该字段更改为:

upload = models.DateTimeField(auto_now_add=True, null=True)

应该可以解决这个问题。

PS 你不应该用 snake_case 命名 类。这是个坏习惯。