2016-12-07 81 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 –

相關問題