我正在将django-model-utils
用于继承管理器。我想用一个字典得到两个子类的结果而不重复。
class Images(models.Model):
user = models.ForeignKey(settings.AUTH_USER_MODEL, related_name='images_created', on_delete=models.CASCADE)
created = models.DateTimeField(auto_now_add=True, null=True, blank=True)
objects = InheritanceManager()
class Postimg(Images):
user_img= models.ImageField(upload_to='images/%Y/%m/%d', null=True, blank=True)
class Postsms(Images):
user_message = models.CharField(max_length=500,blank=True)
def home(request):
all_post = Images.objects.all().order_by('-created').select_subclasses()
return render(request, 'copybook/home.html',{ 'all_post':all_post})
{% for foo in all_post %}
<hr>
<br> SMS by: <p>{{ foo.user}} __ {{ foo.created }}</p>
<h2>{{ foo.user_message }}</h2>
<hr>
<br> IMAGE by: <p>{{ foo.user}} __ {{ foo.created }}</p>
<img src="{{ foo.user_img.url }}"width="250">
{% endfor %}
当我上传应该在首页上居首的图像或消息时,我期望得到结果,但是现在当我上传图像时,空白消息也会被迭代。
我认为问题出在我的home.html中,因为我不知道如何迭代 超过两个子类,并且有一个for循环而没有重复。
答案 0 :(得分:0)
In your template, you are processing every item as if it were both a message and an image. That's why you get empty image sections for messages and empty message sections for images.
The simplest workaround would be to check if user_img
or user_message
evaluates to True
:
{% for foo in all_post %}
<hr>
{% if foo.user_message %}
<br> SMS by: <p>{{ foo.user}} __ {{ foo.created }}</p>
<h2>{{ foo.user_message }}</h2>
{% else %}
<br> IMAGE by: <p>{{ foo.user}} __ {{ foo.created }}</p>
<img src="{{ foo.user_img.url }}"width="250">
{% endif %}
{% endfor %}
Instead of else
you can do a separate if foo.user_img
to avoid message objects with empty messages to be interpreted as images.