嘿那里,
我在一个视图中传递两个应用模型时遇到了困难。我有2个应用程序:
我的期望是,我想在Post视图中显示作者的头像,所以我可以将它包含在帖子循环中。
作者if (l.get(i) > 900)
:
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)
models.py
谢谢
---更新2 ---
解决
@Gagik&amp; @Daniel回答解决了我的问题。我只需要使用此标记:
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,)
我没有更改上面的任何代码。除了我不需要这一行:
{{ post.post_author.avatar }}
谢谢
答案 0 :(得分:1)
您需要通过ForeignKey文件将Author和Post模型相互关联,例如:
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时,你已经可以通过post对象访问Author了。
答案 1 :(得分:1)
Gagik和JF的答案应该足以让你弄清楚该做什么。您的外键称为“post_author”,因此您应该在模板中使用:
{{ post.post_author.avatar }}
您无需获得所有作者,并将其传递到视图中的模板中。