我在 Django 应用程序中收到错误“无法解压不可迭代对象”

问题描述 投票:0回答:1

我浏览了一些主题,其问题几乎与我的相同,但没有一个真正有帮助。问题是我正在编写一个训练 Django 应用程序,其中存储我喜欢的音乐专辑的信息。目前,我正在添加一个表单,我想通过该表单将专辑添加到数据库(而不是“/admin/”中的标准表单)。所以,我拥有的模型非常简单:

from django.db import models


class Genre(models.Model):
    name = models.CharField(max_length=30)

    class Meta:
        verbose_name_plural = "genres"

    def __str__(self):
        return self.name


class Album(models.Model):
    author = models.CharField(max_length=100)
    name = models.CharField(max_length=100)
    release_date = models.IntegerField()
    cover = models.ImageField(upload_to="media")
    genres = models.ManyToManyField("Genre", related_name="album")

    def __str__(self):
        return self.name

如您所见,Album 和 Genre 类通过 ManyToManyField 相互关联。负责将相册添加到数据库的form如下所示:

from django import forms
from .models import Genre

CHOICES = Genre.objects.all()


class AddAlbumForm(forms.Form):
    author = forms.CharField(label="Album's author", max_length=100)
    name = forms.CharField(label="Album's name", max_length=100)
    release_date = forms.IntegerField(label="Album's release year")
    genres = forms.MultipleChoiceField(widget=forms.CheckboxSelectMultiple, choices=CHOICES)
    cover = forms.FileField()

总而言之,除了带有“genres”变量的行之外,该表单是可操作的(如果我注释它,该表单就可以正常工作)。相关的view看起来像这样:

from django.shortcuts import render
from django.http import HttpResponseRedirect
from django.core.paginator import Paginator

from albums.models import Album, Genre
from albums.forms import AddAlbumForm

def add_album(request):
    if request.method == "POST":
        form = AddAlbumForm(request.POST, request.FILES)
        if form.is_valid():
            album = Album()
            album.name = form.cleaned_data.get("name")
            album.author = form.cleaned_data.get("author")
            album.release_date = form.cleaned_data.get("release_date")
            album.cover = form.cleaned_data.get("cover")
            album.genres = form.cleaned_data.get("genres")
            album.save()
            return HttpResponseRedirect("/")
    else:
        form = AddAlbumForm()
    return render(request, "albums/add_album.html", {"form": form})

最后,表单的模板看起来像这样:

{% extends "base.html" %}

{% block page_title %}
    <h2>Add an album: </h2>
{% endblock page_title %}

{% block page_content %}
<form action="/add_album/" method="post" enctype="multipart/form-data">
    {% csrf_token %}
    {{ form.as_p }}
    <p><input type="submit" value="Submit"></p>
</form>
{% endblock page_content %}

至于urls,我不会发布相关代码,因为我的问题与此问题无关。 因此,当我尝试使用表单访问 url 时,出现以下错误:

TypeError at /add_album/
Cannot unpack non-iterable Genre object

我希望所有可供选择的流派都显示在表单中,以便用户可以选择多个选项并将它们保存为相关专辑的“流派”属性。

我做错了什么,伙计们?任何帮助将不胜感激!

python django forms typeerror manytomanyfield
1个回答
0
投票

试试这个

genres = forms.ModelMultipleChoiceField(widget=forms.CheckboxSelectMultiple, queryset=Genre.objects.all())

您试图将查询集作为选择传递,这是行不通的。

参考这个

https://docs.djangoproject.com/en/5.0/ref/forms/fields/#fields-which-handle-relationships

© www.soinside.com 2019 - 2024. All rights reserved.