Home > front end >  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

Time:05-23

i wrote a code to upload images of music and it works ,but when i try to edit older posts (i hadnt add img field yet) it shows this error

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

my models:

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

views:

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)

and template:

{% 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 %}

whats wrong with it?can u hlp me pls?

CodePudding user response:

You can always change that field to:

upload = models.DateTimeField(auto_now_add=True, null=True)
# or even possibly
upload = models.DateTimeField(auto_now_add=True, default=timezone.now)

that should fix that problem.

PS you should not name classes with snake_case. It's bad habit.

  • Related