Django 2.1将变量传递给模板,

时间:2018-11-24 04:10:14

标签: python django

这里有一个关于将变量传递到Django模板中的问题。目标是根据摄影类型过滤出一组照片。我最初想从S3和它所在的文件夹中执行此操作,但是此刻超出了我的技能范围。我只是为此创建了不同的URL而已。我遇到的问题是,我想将变量传递到扩展base_layout.html的模板中,但不会为该变量呈现任何内容。我只是想念怎么做吗?

Model.py

from django.db import models


# Create your models here.
class Gallery(models.Model):
    title = models.CharField(max_length = 50)
    body = models.TextField(max_length = 500)
    created = models.DateTimeField(auto_now_add = True)
    thumb = models.ImageField(default = 'default.jpg', blank = True)
    slug = models.SlugField(blank = True)
    order = models.CharField(max_length = 2, blank = True)

    def __str__(self):
        return self.title

    def body_preview(self):
        return self.body[:50]

class photoUrl(models.Model):
    url = models.CharField(max_length = 128)
    uploaded_on = models.DateTimeField(auto_now_add = True)

class Photos(models.Model):
    title = models.CharField(max_length = 50)
    picture = models.ImageField(blank = True)
    created = models.DateTimeField(auto_now_add = True)
    catagory = models.CharField(max_length=256, choices=[('wedding', 'wedding'), ('portrait', 'portrait'), ('landscape', 'landscape'), ('boudoir', 'boudoir'),], blank = True)

    def __str__(self):
        return self.title

views.py

from django.shortcuts import render
from django.http import HttpResponse
from django.urls import reverse
from . models import Photos

# Create your views here.


def photo_wedding(request):
    photo_list = Photos.objects.filter(catagory = 'wedding').order_by('created')
    photoCat = 'Wedding'
    return render(request, 'gallery/gallery.html', {'photo_list' : photo_list}, {'photoCat' : photoCat})

urls.py

from django.contrib import admin
from django.urls import path
from . import views

app_name='gallery'

urlpatterns = [
    path('wedding/', views.photo_wedding, name='wedding'),
    path('portrait/', views.photo_portrait, name='portrait'),
    path('landscape/', views.photo_landscape, name='landscape'),
    path('boudoir/', views.photo_boudoir, name='boudoir'),
]

gallery.html

{% extends 'gallery/base_layout.html' %}

{% load static %}

{% block gallery %}

    <div class="gallery" id="gallery">
        <div class="container">
            <div class="w3l-heading">

                <h3>{{photoCat}}</h3>

                <div class="w3ls-border"> </div>
            </div>
        </div>
{% endblock gallery %}

3 个答案:

答案 0 :(得分:1)

根据render的定义:

  

render(request, template_name, context=None, content_type=None, status=None, using=None)   将给定的模板与给定的上下文字典组合在一起,并返回带有该呈现文本的HttpResponse对象。

render方法将第一个参数作为request,将第二个参数作为template_name,第三个参数是context,其类型为字典,您选择将其传递给模板,您可以使用键访问字典的所有值。

因此您的方法应如下所示:

def photo_wedding(request):
    photo_list = Photos.objects.filter(catagory = 'wedding').order_by('created')
    photoCat = 'Wedding'
    return render(request, 'gallery/gallery.html', {'photo_list' : photo_list, 'photoCat' : photoCat})

答案 1 :(得分:0)

为什么要传递两个字典。只需添加一个密钥。那就是上下文数据。

在基于类的视图中,您还可以重载方法get_context_data

答案 2 :(得分:0)

使用render()函数,第三个参数是上下文。上下文是用于将变量发送到模板的字典。无需通过两个命令

import React from "react";
import ReactDOM from "react-dom";
import { Transition } from "react-transition-group";
import { BrowserRouter, Route, Link } from "react-router-dom";
import { TweenLite, TimelineMax } from "gsap";

const startState = { autoAlpha: 0, y: -50 };
const onEnter = node => TweenLite.set(node, startState);
const addEndListener = props => (node, done) => {
  const timeline = new TimelineMax();
  if (props.show) {
    timeline
      .to(node, 0.5, {
        autoAlpha: 1,
        y: 0
      })
      .to(node, 0.5, { x: -25 })
      .to(node, 0.5, {
        x: 0,
        onComplete: done
      });
  } else {
    timeline.to(node, 0.5, {
      autoAlpha: 0,
      y: 50,
      onComplete: done
    });
  }
};
const Home = props => {
  return (
    <Transition
      unmountOnExit
      in={props.show}
      onEnter={onEnter}
      addEndListener={addEndListener(props)}
    >
      {state => {
        return <div>Hello {state + " Home!"}</div>;
      }}
    </Transition>
  );
};
const Projects = props => {
  return (
    <Transition
      unmountOnExit
      in={props.show}
      onEnter={onEnter}
      addEndListener={addEndListener(props)}
    >
      {state => {
        return <div>Hello {state + " Projects!"}</div>;
      }}
    </Transition>
  );
};

const App = props => {
  return (
    <BrowserRouter>
      <div>
        <br />
        <Link to="/">Home</Link>
        <br />
        <Link to="/projects/one">Show project</Link>
        <br />
        <Route exact path="/">
          {({ match }) => <Home show={match !== null} />}
        </Route>
        <Route exact path="/projects/one">
          {({ match }) => <Projects show={match !== null} />}
        </Route>
      </div>
    </BrowserRouter>
  );
};

const rootElement = document.getElementById("root");
ReactDOM.render(<App />, rootElement);
const LinkOrStatic = props => {
  const path = props.to;
  return (
    <Route exact path={path}>
      {({ match }) => {
        if (match) {
          return props.children;
        }
        return (
          <Link className={props.className} to={props.to}>
            {props.children}
          </Link>
        );
      }}
    </Route>
  );
};