使用django init表单中的ListView创建ViewView

时间:2018-01-30 23:50:41

标签: django listview create-view

我正在使用sigurdga/django-jquery-file-upload处理多个上传图片,所以我想在用户进入页面时实现这一目标。他上传的照片出现在页面中,有没有办法不初始化django CreateView,所有对象都像ListView一样显示?

我有这个createview:

class PictureCreateView(CreateView):
model = Picture
fields = "__all__"
template_name = 'fileupload/picture_form.html'
# form_class = PictureForm

# def get_initial(self):
#     initial = super(PictureCreateView, self).get_initial()
#     initial = initial.copy()
#     files = [serialize(p) for p in self.get_queryset()]
#     data = {'files': files}
#     response = JSONResponse(data, mimetype=response_mimetype(self.request))
#     response['Content-Disposition'] = 'inline; filename=files.json'
#     return response


def form_valid(self, form):
    self.object = form.save(commit=False)
    self.object.usuario_id = self.request.user.id
    self.object.save()
    usuario = User.objects.get(id=self.request.user.id)

    if usuario:
        photos = Picture.objects.filter(usuario_id=usuario.id)
        for photo in photos:
            photo.usuario_id = self.request.user.id
            photo.save()

    files = [serialize(self.object)]
    data = {'files': files}
    response = JSONResponse(data, mimetype=response_mimetype(self.request))
    response['Content-Disposition'] = 'inline; filename=files.json'
    return response

def form_invalid(self, form):
    data = json.dumps(form.errors)
    return HttpResponse(content=data, status=400, content_type='application/json')

的ListView

class PictureListView(ListView):
model = Picture
template_name = 'fileupload/picture_list.html'

HTML

{% extends "fileupload/upload_base.html" %}

{% block content %}
    <ul>
    {% for picture in object_list %}
        <img src="/media/{{ picture.file }}" />
    {% endfor %}
    </ul>
{% endblock %}

1 个答案:

答案 0 :(得分:0)

快速解决方案是使用get_context_data方法

 def get_context_data(self, **kwargs):
    # Call the base implementation first to get a context
    context = super(PictureCreateView, self).get_context_data(**kwargs)
    # Add in a QuerySet of all the books
    context['pictures'] = Picture.objects.filter(usuario_id=self.request.user.id)
    return context

Template.html

{% extends "fileupload/upload_base.html" %}
{% load static %}
{% load upload_tags %}

{% block content %}
    {% for picture in pictures %}
        <img src="/media/{{ picture.file }}" />
    {% endfor %}
{%endlock%}