2016-12-07 51 views
1

Hei there,如何在一个视图中传递多个应用程序的模型? [django]

我很难在一个视图中传递两个应用程序模型。我有2个应用程序:

  • 作者

我期望是,我想在后视图中显示作者的化身,所以我可以将其包含在帖子中循环。

作者models.py

class Author(models.Model): 
avatar  = models.ImageField(upload_to='images/%Y/%m/%d', verbose_name=u'Author Avatar', validators=[validate_image], blank=True, null=True) 
user  = models.OneToOneField(User, on_delete=models.CASCADE) 
location = models.CharField(max_length=30, blank=True) 

...

views.py

from app_author.models import Author 

class PostList(ListView): 
    model = Post 
    template_name = 'app_blog/blog_homepage.html' 
    context_object_name = 'post_list' 
    paginate_by = 9 

    def get_context_data(self, **kwargs): 
     context = super(PostList, self).get_context_data(**kwargs) 
     context['post_hot'] = Post.objects.filter(misc_hot_post = True).order_by('-misc_created')[:1] 
     context['post_list'] = Post.objects.filter(misc_published = True).order_by('-misc_created') 
     context['author'] = Author.objects.all() # No need this line 
     return context 

当我打电话模板这样的事情,这是行不通的。该{{ author.avatar }}没有显示:

{% for post in post_list %} 
<ul> 
    <li>{{ post.title }}</li> # This is works just fine 
    <li>{{ author.avatar }}</li> # This does not work at all 
<ul> 
{% endfor %} 

我的帖子应用urls.py

from . import views 
from django.conf import settings 
from app_blog.views import PostList, PostDetailView 
from django.conf.urls import include, url 
from django.conf.urls.static import static 

urlpatterns = [ 
    url(r'^$', views.PostList.as_view(), name='post-list'), 
] + static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT) 

任何帮助将不胜感激! 提前谢谢!

问候

--- UPDATE ---

这里是我的帖子models.py

import datetime 
from django import forms 
from django.db import models 
from django.conf import settings 
from autoslug import AutoSlugField 
from django.forms import ModelForm 
from app_author.models import Author 
from taggit.managers import TaggableManager 
from django.contrib.auth.models import User 
from django.core.exceptions import ValidationError 
from django.template.defaultfilters import slugify 

# CUSTOM FILE SIZE VALIDATOR 
def validate_image(fieldfile_obj): 
    filesize = fieldfile_obj.file.size 
    megabyte_limit = 5 
    if filesize > megabyte_limit*1024*1024: 
     raise ValidationError("Max file size is %sMB" % str(megabyte_limit)) 

class Category(models.Model): 
    # PRIMARY DATA 
    id      = models.AutoField(primary_key=True) 
    category_name   = models.CharField(max_length=200, verbose_name=u'Category Name', blank=False, null=False) 

    def __str__(self): 
     return str(self.category_name) 

class Post(models.Model): 
    # PRIMARY DATA 
    post_image    = models.ImageField(upload_to='images/%Y/%m/%d', verbose_name=u'Post Featured Image', validators=[validate_image], blank=True, null=True) 
    post_author    = models.ForeignKey(Author, related_name="user_posts", null=True, blank=True) 
    post_title    = models.CharField(max_length=200, verbose_name=u'Post Title', blank=False, null=False) 
    post_sub_title   = models.CharField(max_length=200, verbose_name=u'Post Sub-Title', blank=False, null=False) 
    post_category   = models.ForeignKey('Category', verbose_name=u'Post Category', on_delete=models.CASCADE) 
    post_content   = models.TextField() 
    post_tags    = TaggableManager() 
    slug     = AutoSlugField(populate_from='post_title') 

    # MISC 
    misc_created   = models.DateTimeField(default=datetime.datetime.now, null=True, blank=True) 
    misc_modified   = models.DateTimeField(default=datetime.datetime.now, null=True, blank=True) 
    misc_hot_post   = models.BooleanField(default=False) 
    misc_published   = models.BooleanField(default=False) 

    def __str__(self): 
     return str(self.post_title) 

    @models.permalink 
    def get_absolute_url(self): 
     return 'app_blog:post', (self.slug,) 

谢谢

---更新2 ---

解决

@Gagik & @Daniel答案sloved我的问题。我只需要用这个标签代替:

{{ post.post_author.avatar }} 

我没有更改上面的任何代码。除了我不需要这行:

context['author'] = Author.objects.all() 

谢谢

+1

'post.author.avatar'? –

+0

@JF仍然没有工作:( –

+0

Post和Author之间的关系是什么?然后?显示您的模型 –

回答

1

您可以通过ForeignKey的文件需要相关作者和发布模式,以对方,如:

class Post (models.Model): 
    author = models.ForeignKey(Author) 

然后,当你可以访问你的头像通过post.author。

更新:更新的问题

更新应答后。 我认为你需要更新你的模板如下。使用post.post_author.avatar访问您需要的化身:

{% for post in post_list %} 
<ul> 
    <li>{{ post.title }}</li> # This is works just fine 
    <li>{{ post.post_author.avatar }}</li> # This does not work at all 
<ul> 

{%ENDFOR%}

考虑到这一点请注意,您不需要搜索作者的拼命在您的视图。所以你不需要有以下行:

context['author'] = Author.objects.all() # This is where I expect the magic is 

因为当你有ForeignKey,那么你已经可以通过发布对象访问Author。

+0

是的,我做了,但没有工作,请看看我更新的问题。谢谢 –

+0

我已经更新了答案,请检查 –

+0

是的,它做了技巧,它现在工作!谢谢!:D 你真的帮了我,再次感谢@Gagi k –

1

Gagik和JF的答案应该足以让你找出该做什么。你的外键被称作“post_author”,所以这是你应该在模板中使用什么:

{{ post.post_author.avatar }} 

没有必要为你的所有作者和他们传递到视图中的模板,你在做什么。

+0

谢谢!有用!再次感谢:D –

相关问题