python-Django显示使用外键上传多个图像 [英] python - Django display uploaded multiple images with foreign key

查看:88
本文介绍了python-Django显示使用外键上传多个图像的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

例如,上传一个或多个图像后,我的ID为 31 的帖子在db中显示为:

I have for example the Post with the id 31 after I upload one or more images are displayed in db as:

  1. id(例如:1,2,3)
  2. URL到图像(例如:my-images/image.png)
  3. foreing_id(要发布的ID,即 31 )

但是我不知道如何在此帖子(当然还有其他)的模板中显示图像

But I do not know how to display the image in the template for this post (and others of course)

我的模特:

class Post(models.Model):
    title = models.CharField(max_length=20000)
    date = models.DateTimeField(editable=True, null=True)
    text = models.TextField(max_length=50000)
    is_super = models.IntegerField(default=0)

class Image(models.Model):
    foreing = models.ForeignKey(Post)
    image = models.ImageField(null=True, blank=True, upload_to='my-images')

查看我上传和显示所有帖子的位置(此处显示):

view where i upload and display all posts(Here i display):

class IndexView(generic.ListView):
    paginate_by = 4
    template_name = 'home/index.html'
    context_object_name = 'all_posts'

    def get_queryset(self):
        query = self.request.GET.get('q')
        if query:
            posts = Post.objects.filter(
                Q(text__icontains=query.capitalize()) |
                Q(title__icontains=query.capitalize()) |
                Q(text__icontains=query.lower()) |
                Q(title__icontains=query.lower())
            ).distinct()
            return posts
        else:
            return Post.objects.filter(date__lte=timezone.now()).order_by('-date')

我创建了一个新帖子:

def post_new(request):
    ImageFormSet = modelformset_factory(Image, form=ImageForm, extra=3)
    if request.method == "POST":
        form = PostForm(request.POST, request.FILES or None)
        formset = ImageFormSet(request.POST, request.FILES, queryset=Image.objects.none())
        if form.is_valid() and formset.is_valid():
            post = form.save(commit=False)
            post.date = timezone.now()
            post.save()
            for form in formset.cleaned_data:
                image = form['image']
                photo = Image(foreing_id=post.id, image=image)
                photo.save()
            return render(request, 'home/page.html')
        else:
            form = PostForm()
        return render(request, 'home/edit_post.html',
                  {'form': form, 'error_message': 'something error message'})
    else:
        form = PostForm()
        formset = ImageFormSet(queryset=Image.objects.none())
    return render(request, 'home/edit_post.html', {'form': form, 'formset': formset})

在这里,我需要显示所有这些帖子的图像:

And here i need to display images for all this posts:

这是显示的图像

        <div class="profile-img-container" style="text-align: center">
            <img class="img" src="images">
            <a target="_blank" title="****." href="URL to the uploaded image"><span class="fa fa-expand fa-5x" style="color: darkcyan" aria-hidden="true"></span></a>

完整的index.html(如果需要):

<div class="content">
{% for post in all_posts %}
    <div class="thumbnail">
        <p style="text-align: center">{{ post.title }}</p>
            <p class="text" style="text-align: center; height: 40px; overflow: hidden">{{ post.text }}</p>
                <p><a type="button" class="btn btn-primary" href="{% url 'klass:detail' post.id %}">More...</a></p>
            <div class="profile-img-container" style="text-align: center">
                <img class="img" src="/media/**display images**" style="height: 150px">
                <a target="_blank" title="****." href="**url to images**"><span class="fa fa-expand fa-5x" style="color: darkcyan" aria-hidden="true"></span></a>
            </div>
            {% if user.is_authenticated %}
                <form method="post" style="text-align: right">
                <p>
                    {% csrf_token %}
                    <a methods="post" role="button" class="btn btn-info" href="{% url 'klass:favorite' post.id %}">
                        <i class="fa fa-heart" style="color: red" aria-hidden="true"></i>great! {{ post.is_super }}
                    </a>
                </p>
                </form>
                <span style="margin-left: 90px">Published: {{ post.date }}</span>
            {% else %}
                <p style="text-align: right">****<br>
                <a role="button" class="btn btn-info disabled" style="text-align: right">
                <i class="fa fa-heart" aria-hidden="true"></i>great!</a>
                {{ post.date }}
                </p>
            {% endif %}
    </div>
{% endfor %}

编辑

网址:

from django.conf.urls import url, include
from django.contrib import admin
from django.conf import settings
from django.conf.urls.static import static

urlpatterns = [
    url(r'^admin/', admin.site.urls),
    url(r'^home_page/', include('home.urls', namespace='home')),
    url(r'^captcha/', include('captcha.urls')),
] + static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT)

设置:

STATIC_URL = '/static/'

STATICFILES_DIRS = [
    os.path.join(BASE_DIR, 'home/static'),
]

MEDIA_URL = '/media/'

MEDIA_ROOT = os.path.join(BASE_DIR, 'media')

家庭应用中的另一个网址:

another urls in home app:

from django.conf.urls import url
from . import views

app_name = 'home'

urlpatterns = [
    ***,
    url(r'^$', views.IndexView.as_view(), name='index'),
    url(r'^(?P<post_id>[0-9]+)/$', views.comments, name='detail'),
    url(r'^(?P<post_id>[0-9]+)/addcomment$', views.addcomment, name='comment'),
    url(r'^(?P<post_id>[0-9]+)/favorite/$', views.favorite, name='favorite'),
    url(r'^(?P<pk>[0-9]+)/edit/$', views.post_edit, name='edit'),
    url(r'^post/new/$', views.post_new, name='post_new'),
    url(r'^(?P<post_id>[0-9]+)/delete_album/$', views.delete_post, name='delete_post'),
    ****,
]

推荐答案

您应遍历post.image_set.all并分别显示每个图像,例如:

You should loop through post.image_set.all and display each image separately, for example:

{% for image in post.image_set.all %}
<div class="profile-img-container" style="text-align: center">
  <img class="img" src="{{ image.image.url }}" style="height: 150px">
  <a target="_blank" href="{{ image.image.url }}">
    <span class="fa fa-expand fa-5x" style="color: darkcyan" aria-hidden="true"></span>
  </a>
</div>
{% endfor %}

一些注意事项:

  1. 您不应在图像网址中包含/media,因为它将由Django自动附加.

  1. You shouldn't include /media in your image url as it will be automatically appended by Django.

出于可读性原因,不建议将外键命名为foreign(还要检查拼写).考虑将其重命名为使用小写的父模型名称(例如post),使其变为post = models.ForeignKey(Post)

Naming your foreign keys as foreign (also check your spelling) is not recommended for readability reasons. Consider renaming it to use the parent model's name in lowercase (such as post) instead so that it becomes post = models.ForeignKey(Post)

不建议使用_id引用外键.请改用模型本身,例如:photo = Image(post=post, image=image)

Referencing the foreign key using _id is not recommended. Use the model itself instead, for example: photo = Image(post=post, image=image)

这篇关于python-Django显示使用外键上传多个图像的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆