django DetailView 没有从 ManyToMany 字段中捕获数据

Posted

技术标签:

【中文标题】django DetailView 没有从 ManyToMany 字段中捕获数据【英文标题】:django DetailView doesn't catch data from ManyToMany field 【发布时间】:2020-08-17 21:20:44 【问题描述】:

我有 3 个模型:第一个主要的“石头”通过 ForeignKey 与“Typs”连接,多对多与“Mentions”连接。 当我尝试使用 DetailView 类为每个“石头”编写详细视图模板时,它仅显示来自“石头”和“类型”的数据,而不是来自“提及”的数据

我的models.py(必要部分)

class StonesManager(models.Manager):
def all_with_prefetch_mentions(self):
    qs = self.get_queryset()
    return qs.prefetch_related('mentions')


class Stones(models.Model):
title = models.CharField(max_length=30, verbose_name='Назва')
place = models.TextField(verbose_name='Месцазнаходжанне')
legend = models.TextField(null=True, blank=True, verbose_name='Легенда')
typ = models.ForeignKey('Typ', null=True, on_delete=models.PROTECT, verbose_name='Тып')
objects = StonesManager()

class Typ(models.Model):
name = models.CharField(max_length=20, db_index=True, verbose_name='Назва тыпу')
def __str__(self):
    return self.name

class StonesImage(models.Model):
image = models.ImageField(upload_to=stones_directory_path_with_uuid)
uploaded = models.DateTimeField(auto_now_add=True)
stones = models.ForeignKey('Stones', on_delete=models.CASCADE)
user = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.CASCADE)

class Mentions(models.Model):
work = models.TextField(verbose_name='Праца')
year = models.PositiveIntegerField(blank=True, null=True)
sacral_objects = models.ManyToManyField(Stones, related_name='mentions', verbose_name='Сакральны аб\'ект')

my views.py(必要部分)

class StonesDetail(generic.DetailView):
queryset = Stones.objects.all_with_prefetch_mentions()
template_name = 'volumbf/stone_detail.html'

def get_context_data(self, **kwargs):
    context = super().get_context_data(**kwargs)
    context['image_form'] = self.stones_image_form()
    return context

def stones_image_form(self):
    if self.request.user.is_authenticated:
        return StonesImageForm()
    return None

我的模板(必要部分) 1.一切都以正确的方式显示

<h2>  stones.title </h2>
<p> stones.legend  </p>
<p> stones.place </p>
<p>Typ: <a href="/volumbf/ stones.typ.pk /"> stones.typ.name </a></p>
    根本不显示

提及:

% for work in stones.mentions.work %
        <p><a href="% url 'work_detail' work.pk %">  stones.mentions.work </a></p>
% endfor %


 % for i in object.stonesimage_set.all %
        <li class="list-inline-item" >
            <img scr=" i.image.url ">
        </li>
 % endfor %

% if image_form %
    <div>
        <h2 >Upload New Image</h2>
    <form method="post"
          enctype="multipart/form-data"
          action="% url 'StonesImageUpload' stones_id=object_id %" >
        % csrf_token %
         image_form.as_p 
        <p ><button class="btn btn-primary"></button> </p>
    </form>
    </div>
% endif %

我认为“stones.mentions.work”不是正确的名称,但我不确定。拜托,我在这里做了我的第一步,需要任何帮助。

【问题讨论】:

【参考方案1】:

我是对的,错误在模板中,见下文

% for work in stones.mentions.all %
    <p><a href="% url 'work_detail' work.pk %">  work </a></p>
% endfor %

% for i in object.stonesimage_set.all %
        <li class="list-inline-item" >
            <img src=" i.image.url "  >
        </li>
% endfor %

action="% url 'StonesImageUpload' stones.pk %"

【讨论】:

我能再问你一个关于同一主题的问题吗?这里不知道怎么写私信【参考方案2】:

我的解决方案适用于 Django 3

使用 DetailView 和 ModelForm

models.py

class DispCause(models.Model):
reason = models.CharField(
    max_length = 100,
    default = 'Late Delivery'
)

class Dispute(models.Model):
   dispcause = models.ManyToManyField(DispCause,
        related_name='disputes')
    msg = models.TextField(
        max_length=2000
      )

forms.py

class DisputeForm(forms.ModelForm):
dispcause = forms.ModelMultipleChoiceField(
    label = "Select reason(s) for your complain",
    queryset = DispCause.objects.all(),
    widget = forms.CheckboxSelectMultiple()

views.py

class DisputeDetails(DetailView):
model = Dispute
template_name = TEMPLATE_DIR + "details.html"

模板

  % for w in object.dispcause.all %
  <tr>
    <td> w </td>
  </tr>
  % endfor %

【讨论】:

以上是关于django DetailView 没有从 ManyToMany 字段中捕获数据的主要内容,如果未能解决你的问题,请参考以下文章

如何使用当前登录用户作为 Django DetailView 的 PK?

python 没有PK或Slug的Django Generic DetailView

django: DetailView: self.object 从方法 post 调用时会引发错误,但从方法 get_context_data 调用时它确实有效

Django TemplateView 与 DetailView

Django 3:将数据添加到 DetailView

Django DetailView/ListView 强制 XML 渲染