开发者

Django template tag to output images from model

I am new to Django and just started working on my first project. i have a mode located at common.utils.abstact_models.py:

class PhotoModel(BaseModel):
  submitted_by = models.ForeignKey(User)
  caption = models.TextField(blank=True, null=True)
  photo = FileBrowseField('Image (Initial Directory)', max_length=100, directory='uploads/')
  is_default = models.BooleanField(default=False)

class Meta
  abstract = True

maybe this also will be useful. i have another model:

class Photo(BaseModel):
  event = models.ForeignKey(Event)
  photo = models.ImageField(max_length=255, upload_to="uploads/event_photos")
  is_featured = models.BooleanField(default=False)

i have pictures uploaded to MEDIA_URL/uploads/event_photos

i need to write a template tag to output photos of current user. Lets say 10 photos. i almost dont have any code, i started from some.

from django import template
from common.utils.abstract_models.py import PhotoModel

register = template.Library()

def do_random_photos(parser, token):
  myobjects = PhotoModel.objects.all()
  return {'objects': myobjects}

clas开发者_Python百科s RandomPhotosNode(template.Node):
  def __init__(self, context):
  self.

def render(self, context):
  return

do you have any suggestions in writing this template tag?


output photos of current user.your need add a filter ,use 'request.user.id' get current user's id. show 10 photos need Django's Pagination.

def show_photos(request):
  photos = PhotoModel.objects.filter(submitted_by=request.user.id)
  paginator = Paginator(photos,9)
  try:
    page = int(request.GET.get('page',1))
  except ValueError:
    page = 1
  try:
    photos = paginator.page(page)
  except:
    photos = paginator.page(paginator.num_pages)
  ctx = {'photos':photos}
  return render_to_response('a templates', ctx, context_instance = RequestContext(request))

then, in you templates

{% for photo in photos.object_list %}
<img src="{{ photo.photo }}" />
{% endfor %}
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜