我无法使用CreateView

时间:2019-06-22 10:06:42

标签: django

我正在关注buckys django教程,他解释了如何添加专辑而不是歌曲,我想尝试将歌曲添加到特定专辑中,但是不起作用。

我在views.py中添加了一个SongCreate视图,还创建了一个用于输入歌曲详细信息的song_form.html模板。我还尝试了form_valid方法,但它不仅有效。

我的views.py

class AlbumCreate(CreateView):
    model=Albums
    fields=['alb_title','alb_genre','alb_logo','alb_artist']

class SongCreate(CreateView):
    model = Song
    fields = ['song_title', 'song_format']

    def form_valid(self, form):
        album = get_object_or_404(Albums, pk=self.kwargs['pk'])
        form.instance.album = album
        return super(SongCreate, self).form_valid(form)
#My urls.py
 app_name ='music'

urlpatterns = [
    path('',views.IndexView.as_view(), name='index'),
    path('<int:pk>/', views.DetailView.as_view(), name='detail'),
    path('album/add/', views.AlbumCreate.as_view(), name='album-add'),
    path('album/<int:pk>/songadd/', views.SongCreate.as_view(), 
         name='song-add'),
    path('album/<int:pk>/', views.AlbumUpdate.as_view(), name='album- 
         update'),
    path('album/<int:pk>/delete/', views.AlbumDelete.as_view(), 
         name='album-delete'),
    ]


#My song_form.html template
{% extends 'music/base.html' %}
{% block  title %}Add New Song{% endblock  %}
{% block body %}
<div class="container-fluid">
<h4>Add the details of the Song in the given fields.</h4>
    <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 'music/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 %}
#Models.py
class Albums(models.Model):
    alb_title = models.CharField(max_length = 250)
    alb_genre = models.CharField(max_length = 250)
    alb_logo = models.FileField()
    alb_artist = models.CharField(max_length = 250)

    def get_absolute_url(self):
        return reverse("music:detail", kwargs={"pk": self.pk})

    def __str__(self):
        return self.alb_title + '-' + self.alb_artist

class Song(models.Model):
    song = models.ForeignKey(Albums, on_delete = models.CASCADE)
    song_title = models.CharField(max_length = 250)
    song_format = models.CharField(max_length = 10)
    is_favourite = models.BooleanField(default=False)

    def __str__(self):
        return self.song_title

    def get_absolute_url(self):
        return reverse('music:detail', kwargs={'pk': self.song.pk})

单击添加歌曲时,它会将我定向到填写歌曲详细信息的表单,但是当我尝试时,我得到了: / music / album / song / add /中的IntegrityError NOT NULL约束失败:music_song.song_id

2 个答案:

答案 0 :(得分:0)

我给你我使用form_valid()

的方式
    def form_valid(self, form):
        album = get_object_or_404(Albums, pk=self.kwargs['pk'])
        form = form.save(commit=False)
        form.album = album
        form.save()
        return super().form_valid(form)

如果它不起作用,则意味着您所做的更改未反映在数据库中。运行./manage.py makemigrations./manage.py migrate。如果可能的话,可能有必要删除并重新创建整个数据库。

答案 1 :(得分:0)

您必须:

def create_song(request):
    if request.method == "POST":
       form.save()