显示模型输出的问题。ManyToManyField(用户)

时间:2019-12-05 04:54:48

标签: python django user-input

我正在通过构建一个名为TravelBuddies的应用程序来学习Django。它将允许旅行者计划行程并保留相关的旅行项目(例如预订,机票,护照副本,保险信息等),以及为日常活动创建提醒。该应用程序还将能够向旅行者更新本地信息,例如天气或每日新闻。旅行者还可以与某人共享旅行信息,或者让某人与他们合作来计划旅行。

我遇到了问题。我通过Django管理员为吉隆坡添加了两个活动。他们是“去植物园”和“去水族馆”。

当我转到http://127.0.0.1:8000/triplist/时,看到以下页面: enter image description here

如您所见,在“共同计划者”字段中,用户名显示为<QuerySet [<User: williams>]>。但是应该将其显示为Co-planner: williams

当我点击旅行名称:吉隆坡并转到http://127.0.0.1:8000/triplist/kuala-lumpur/时,会发生相同的问题: enter image description here

这是我在models.py中的代码:

from django.contrib.auth.models import User
from django.db import models

# Create your models here.
from django.template.defaultfilters import slugify

class Trip(models.Model):
    trip_name = models.CharField(max_length=100)
    date = models.DateField()
    planner_name = models.CharField(max_length=100)
    add_coplanner = models.ManyToManyField(User)
    slug = models.SlugField(max_length=150, default='null')

    def __str__(self):
        return self.trip_name

    def save(self, *args, **kwargs):
        self.slug = slugify(self.trip_name)
        super().save(*args, **kwargs)

class Activity(models.Model):
    trip = models.ForeignKey(Trip, on_delete=models.CASCADE)
    activity_name = models.CharField(max_length=100)
    date = models.DateField(auto_now=True)
    time = models.TimeField(auto_now= True)
    location = models.CharField(max_length=100)
    item_type = models.CharField(max_length=100)
    item_number = models.CharField(max_length=100)
    add_cotraveller = models.ManyToManyField(User)
    slug = models.SlugField(max_length=150, default='null')

    def __str__(self):
        return self.activity_name

    def save(self):
        super(Activity, self).save()
        self.slug = '%i-%s' % (
            self.id, slugify(self.trip.trip_name)
        )
        super(Activity, self).save()

这是我在views.py中的代码:

from django.views import generic
from .models import Trip, Activity


class TripListView(generic.ListView):
    template_name = 'trips/triplist.html'
    context_object_name = 'all_trips'

    def get_queryset(self):
        return Trip.objects.all()


class ActivityView(generic.DetailView):
    model = Trip
    template_name = 'trips/activity.html'

这是我在urls.py中的代码:

from . import views
from django.urls import path

app_name = 'trips'

urlpatterns = [
    path('triplist/', views.TripListView.as_view(), name='triplist'),
    path('triplist/<slug:slug>/', views.ActivityView.as_view(), name='activity'),
]

这是我在apps.py中的代码:

from django.apps import AppConfig


class TripsConfig(AppConfig):
    name = 'trips'

这是我在triplist.html中的代码:

<!DOCTYPE html>
{% extends 'trips/base.html' %}
{% load static %}
<html lang="en">
<link rel="stylesheet" type="text/css" href="{% static "css/style.css" %}">

<head>
    <meta charset="UTF-8">
    {% block title%}Trip list{% endblock %}
    <title>Trip list</title>
</head>


<body>
    {% block content %}
    <!--Page content-->
    <h1>This is Trip List Page</h1>


    <ol>
        {% for trip in all_trips %}
        <ol>
            <li><a href="{% url 'trips:activity' trip.slug %}">Trip name: {{ trip.trip_name }}</a></li>
            Date: {{ trip.date }}<br>
            Planner: {{ trip.planner_name }}<br>
            Co-planner: {{ trip.add_coplanner.all }}<br>
        </ol>
        {% endfor %}


    </ol>

    <img src="{% static "images/botanical-garden.jpg" %}" alt="Botanical Garden" />
    <!-- New line -->
    {% endblock %}
</body>
</html>

</html>

这是我在activity.html中的代码:

{% extends 'trips/base.html' %}
{% block title%}
Detail
{% endblock %}


{% block content %}

<h3>Activities for {{trip.trip_name}} </h3>

{% for trip_item in trip.activity_set.all %}
<!--<p>Activity name: {{ trip_item.activity_name }}</p>-->
<ol>
    <li>Activity name: {{ trip_item.activity_name }}</li>
    Date: {{ trip_item.date }}<br>
    Time: {{ trip_item.time }}<br>
    Location: {{ trip_item.location }}<br>
    Item Type: {{ trip_item.item_type }}<br>
    Item No: {{ trip_item.item_number }}<br>
    Co-traveller: {{ trip_item.add_cotraveller.all }}
</ol>
{% endfor %}

{% endblock %}

triplist.html和activity.html有什么问题吗?

更新1:顺便说一下,我从下面的链接Auth.User.None when rendering a ManyToManyField中了解了此代码add_coplanner = models.ManyToManyField(User)

问这个问题的人也面临着与我相同的问题。他得到类似<User: gg>]>的信息。建议他重写 str ()方法。但是我不知道该怎么做。

3 个答案:

答案 0 :(得分:1)

“活动”模型中的嗨,请添加

    def get_cotravellers(self):
          return " , ".join([x.username for x in self.add_cotraveller.all()])

在庙宇中称为{{ trip_item.get_cotravellers }}

答案 1 :(得分:1)

您需要在此处进行迭代,因为它是查询集

triplist.html

  Coplanners: 
    {% for user in trip.add_coplanner.all %}
        {{user.name}} 
        #{{user.username}} do this if your User model don't have name field
     #If you want to separate the users with comma
       {% if not forloop.last %} , {% endif %}
    {% endfor %}<br>

答案 2 :(得分:0)

models.py

class Song(models.Model):
user = models.ManyToManyField(User)
song_name = models.CharField(max_length=50)
song_duration = models.IntegerField()

def written_by(self):
    return ",".join([str(p) for p in self.user.all()])

html 文件

    {% for data in data %}

        {{data.written_by}}   # It returns username
        {{data.song_name}}
        {{data.song_duration}}

    {% endfor %}

像这样关联它会起作用