我正在尝试通过表单添加歌曲但不断获取
NOT NULL约束失败:post_song.album_id。
截至目前,我只能手动添加歌曲并且没有连接到原始专辑。
from django.db import models
from django.core.urlresolvers import reverse
from django.conf import settings
from django.contrib.auth.models import User
class Album(models.Model):
creator = models.CharField(max_length=250)
album_name = models.CharField(max_length=250)
album_photo = models.FileField()
author = models.ForeignKey(User, blank=True, null=True, related_name ='album_post')
category = models.ManyToManyField(Category)
def get_absolute_url(self):
return reverse('post:detail', kwargs={'pk': self.pk})
def __str__(self):
return self.creator + ' - ' + self.album_name
class Song(models.Model):
album = models.ForeignKey(Album, on_delete=models.CASCADE, null=True)
song_name= models.CharField(max_length=1000)
def __str__(self):
return self.song_name
def get_absolute_url(self):
return reverse('post:detail', kwargs={'pk': self.pk})
class SongAdd(CreateView):
model = Song
fields = ['song_name']
def form_valid(self, form):
form.instance.album_id = self.request.GET.get('album_pk')
return super(SongAdd, self).form_valid(form)
{% block body %}
<div class="container-fluid">
<div class="row">
<div class="col-sm-12 col-md-7">
<div class="panel panel-default">
<div class="panel-body">
<form class="form-horizontal" action="" method="post" enctype="multipart/form-data">
{% csrf_token %}
{% include 'post/form-template.html' %}
<div class="form-group">
<div class="col-sm-offset-2 col-sm-10">
<button type="submit" class="btn btn-success">Submit</button>
</div>
</div>
</form>
</div>
</div>
</div>
</div>
</div>
{% endblock %}
答案 0 :(得分:0)
在您看来,您缺少相册字段。表单不知道您要将歌曲关联到哪个专辑。
答案 1 :(得分:0)
试试这个:
j
确保class SongAdd(CreateView):
model = Song
fields = ['song_name']
def form_valid(self, form):
album = Album.objects.get(pk=album_id_variable)
form.instance.album = album
return super(SongAdd, self).form_valid(form)
是有效的相册ID。