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



我写了一个代码来上传音乐图像,它工作,但当我试图编辑旧的帖子(我还没有添加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来命名类。这是个坏习惯。

相关内容

  • 没有找到相关文章

最新更新