在Django中显示图片

时间:2018-11-19 04:51:55

标签: django

尽管我意识到有类似的问题,但我一直无法完成这项工作。希望有人能指出我正确的方向。

我有一个django应用程序,它允许使用它上传图像。现在我的模型看起来像这样。

从代码中调用图像时,由于某种原因图像未显示。我可以想象的原因是在view.py文件中,或者在模板文件中如何调用它。

提前感谢您的帮助,

型号

class Category(models.Model):
    name = models.CharField(max_length=128, unique=True)
    image = models.ImageField(blank=True, null=True, upload_to="locations/%Y/%m/%D")
    views = models.IntegerField(default=0)
    likes = models.IntegerField(default=0)
    slug = models.SlugField(unique=True)

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

    class Meta:
        verbose_name_plural = 'categories'

    def __str__(self):
        return self.name

观看次数

def index(request):
    # Query the databse for a list of ALL categories currently stored.
    # Order the categories by no likes in descending order .
    # Retrieve the top 5 only - or all if less than 5.
    # Place the list in context_dict dictionary
    # that will be passed to the template engine.
    category_list = Category.objects.order_by('-likes')[:5]
    page_list = Page.objects.order_by('-views')[:5]

    context_dict = {'categories': category_list, 'pages': page_list}

    # Render the response and send it back!

    return render(request, 'Spaces/index.html', context_dict)


def show_category(request, category_name_slug):
    # Create a context dictionary which we can pass
    # to the template rendering engine.
    context_dict = {}

    try:
        # Can we find a category name slug with the given name?
        # If we can't, the .get() method raises a DoesNotExist exception.
        # So the .get() method returns one model instance or raises an exception.
        category = Category.objects.get(slug=category_name_slug)
        # Retrieve all of the associated pages.
        # Note that filter() returns a list of page objects or an empty list
        pages = Page.objects.filter(category=category)

        # Adds our results list to the template context under name pages.
        context_dict['pages'] = pages
        # We also add the category object from
        # the database to the context dictionary.
        # We'll use this in the template to verify that the category exists.
        context_dict['category'] = category

        # We get here if we didn't find the specified category.
        # Don't do anything -
        # the template will display the "no category" message for us.
    except Category.DoesNotExist:
        context_dict['category'] = None
        context_dict['pages'] = None
        # Go render the response and return it to the client.
    return render(request, 'Spaces/category.html', context_dict)

模板

{% load staticfiles %}
{% load i18n %}
<!DOCTYPE html>

<html>
<head>
    <meta charset="utf-8">
    <meta name="viewport" content="width=device-width, initial-scale=1">

    <title>Side Spacer</title>

    <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0/css/bootstrap.min.css">
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
    <script src="https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.12.9/umd/popper.min.js"></script>
    <script src="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0/js/bootstrap.min.js"></script>
    <script src="https://use.fontawesome.com/releases/v5.0.8/js/all.js"></script>
    <link href="style.css" rel="stylesheet">

</head>
<body>

  <!-- Navigation -->

<nav class="navbar navbar-expand-md navbar-light bg-light sticky-top">

    <div class="container-fluid">
        <a class="navbar-brand" href="#"><img src="#"></a>
        <button class="navbar-toggler" type="button" data-toggle="collapse" data-target="#navbarResponsive">
            <span class="navbar-toggler-icon"></span>
        </button>

        <div class="collapse navbar-collapse" id="navbarResponsive">

            <ul class="navbar-nav ml-auto">
                <li class="nav-item active"><a class="nav-link" href="#">Home</a></li>
                <li class="nav-item"><a class="nav-link" href="#">Spaces</a></li>
                <li class="nav-item"><a class="nav-link" href="/Spaces/about/">How it works</a></li>
                <li class="nav-item"><a class="nav-link" href="#">Pricing</a></li>
        {% if user.is_authenticated %}
        <li class="nav-item"><a class="nav-link" href="{% url 'logout' %}">Log out {{user.username}}</a></li>
        {% else %}
        <li class="nav-item"><a class="nav-link" href="{% url 'signup' %}">Sign Up</a></li>
        <li class="nav-item"><a class="nav-link" href="{% url 'login' %}">Login</a></li>
        {% endif %}
            </ul>

        </div>
    </div>

</nav>

<!--- Image Slider -->

<div id="slides" class="carousel slide" data-ride="carousel">

    <ul class="carousel-indicators">
        <li data-target="#slides" data-slide-to="0"class="active"></li>
    </ul>

    <div class="carousel-inner">
        <div class="carousel-item active">

            <div class="carousel-caption">
                <h3 class="display-2">Need a workspace on the go?</h3>
                <h3>Great locations and flexible pricing!</h3>
                <button type="button" class="btn btn-outline-light btn-lg" href="{% url 'signup' %}">Join Now!</button>
            </div>
        </div>
    </div>

</div>

<!--- Jumbotron -->
<hr class="my-4">

<div class="container-fluid">

    <div class="row jumbotron">
        <div class="col-xs-12 col-sm-12 col-md-9 col-lg-9 col-xl-10">
            <p class="lead">For mobile professionals, startups, and business that need the extra deskpace!<br> Productive workspaces are available to help you get things done!<br> Our plans start at $99/month! </p>
        </div>
        <div class="col-xs-12 col-sm-12 col-md-3 col-lg-3 col-xl-2">
                <a href="#"> <button type="button" class="btn btn-outline-secondary btn-lg">Our Services</button></a>
        </div>
    </div>

</div>
            <div class="container">
              <!-- Example row of columns -->
              <div class ="row">
                <div class ="col">
                  <h2>Most Viewed Spaces</h2>
              {% if categories %}
              <ul>
                {% for category in categories %}
                  <li>
                                            {% if item != None %}
                                        <img src="{% get_media_prefix %}{{ category.image }}" width="500px" />
                                            {% endif %}
                    <a href="/Spaces/category/{{ category.slug }}">{{ category.name }}</a>
                  </li>
                  {% endfor %}
              </ul>
              {% else %}
                <strong>There are no Spaces present.</strong>
              {% endif %}

                </div>
                  <div class ="col">
                    <h2>Most Viewed Events</h2>
                      <p>
                            {% if pages %}
                                <ul>
                            {% for page in pages %}
                                <li><a href="{{ page.url }}">{{ page.title }}</a></span></li>
                             {% endfor %}
                               </ul>
                            {% else %}
                                <strong>There are no Events present.</strong>
                         {% endif %}
                        </p>
                  </div>
                <div>
                                    {% if user.is_authenticated %}
              <div>
                <p><a class="btn btn-success" href="/Spaces/add_category/" role="button">Add New Space »</a></p>
                <p><a class="btn btn-success" href="/Spaces/add_page/" role="button">Create New Event »</a></p>
              </div>
                                {% endif %}
            </div> <!-- /container -->
              <hr>


              <div class="container-fluid padding">
                <div class="row text-center">

                    <div class="col-md-4">

                        <hr class="light">
                        <img src="#">
                        <hr class="light">
                        <p>555-555-55555</p>
                        <p>email@someonesmail.com</p>
                        <p>100 Street name</p>
                        <p>City, State, 0000</p>

                    </div>

                    <div class="col-md-4">

                        <hr class="light">
                        <h5>Our hours</h5>
                        <hr class="light">
                        <p>Monday: 9AM - 5PM</p>
                        <p>Saturday: 10AM - 4PM</p>
                        <p>Sunday: Closed</p>

                    </div>

                    <div class="col-md-4">

                            <hr class="light">
                            <h5>Service Area</h5>
                            <hr class="light">
                            <p>City, State, 0000</p>
                            <p>City, State, 0000</p>
                            <p>City, State, 0000</p>

                    </div>

                    <div class="col-12">

                        <hr class="light">
                        <h5>&copy; nameofthebusiness </h5>

                    </div>

                </div>
              </div>
  <script src="https://code.jquery.com/jquery-3.3.1.slim.min.js" integrity="sha384-q8i/X+965DzO0rT7abK41JStQIAqVgRVzpbzo5smXKp4YfRvH+8abtTE1Pi6jizo" crossorigin="anonymous"></script>
  <script>window.jQuery || document.write('<script src="../../assets/js/vendor/jquery-slim.min.js"><\/script>')</script>
  <script src="../../assets/js/vendor/popper.min.js"></script>
  <script src="https://stackpath.bootstrapcdn.com/bootstrap/4.1.3/js/bootstrap.min.js" integrity="sha384-ChfqqxuZUCnJSK3+MXmPNIyE6ZbWh2IMqE241rYiqJxyMiZ6OW/JmZQ5stwEULTy" crossorigin="anonymous"></script>
</body>
</html>

3 个答案:

答案 0 :(得分:2)

您必须在映像之前添加get_media_prefix。我使用{{category.image.url}}从AWS S3提供媒体,但是我认为在这里您只使用{{category.image}}。玩一点,看看。

 <img src="{% get_media_prefix %}{{ category.image }}" width="500px" />

答案 1 :(得分:0)

您应该为图像提供正确的路径。对我来说,下面的代码可以正常工作。

在设置中:

MEDIA_URL = '/media/'
MEDIA_ROOT = os.path.join(BASE_DIR, 'media')

显示图像

<img src="/media/{{category.image}}" width="500px" />

答案 2 :(得分:0)

发现了问题。

{% if item != None %}
 <img src="{% get_media_prefix %}{{ category.image }}" width="500px" />
                                            {% endif %}

也更改了

{% if category.image %}
<img src="{{ category.image.url }}"  />
{% endif %}

问题解决了