如何从Django中的视图更新ImageField [英] How to update a ImageField from views in django

查看:207
本文介绍了如何从Django中的视图更新ImageField的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

尝试从表单中更新照片有点烦。我有这个:

Im a bit frustared trying to update a photo from a form. I have this:

<form action="/subir-fotos/{{campana_id}}/{{point_id}}/" method="POST" enctype="multipart/form-data" id="form_tomaFoto{{page}}">{% csrf_token %}

<input type="hidden" value="{{i.titulo_foto.id}}" name="titulo">
<p><input type="file" accept="image/*" name="foto" required></p>

<p><input type="submit" value="Enviar foto" class="boton"></p>
</div>
</form>

我的模型:

class InteraccionFotos(models.Model):
    campana = models.ForeignKey('dashboard.Campana')
    titulo_foto = models.ForeignKey('actividad_fotos.TitulosFotos')
    punto_interaccion = models.ForeignKey(PuntoInteraccion)
    foto = models.ImageField(upload_to='.',blank=True,null=True)

然后,在我看来,我有这个:

Then, in my View, I have this:

class SubeFotoView(FormView):
    form_class = FilebabyForm
    success_url = '/'
    template_name = 'tomar_fotos.html'

    def form_valid(self,form):
        form.save(commit=True)
        messages.success(self.request, 'File uploaded!')
        return super(SubeFotoView, self).form_valid(form)


    def post(self, request, *args, **kwargs):
        campana = self.kwargs.get('campana_id')
        point_id = self.kwargs.get('point_id')
        titulo_foto = request.POST['titulo']
        foto = request.FILES['foto']
        crea_foto = InteraccionFotos.objects.filter(pk=1,campana_id=3,punto_interaccion_id=5).update(foto=foto)
        data = {}
        data['success'] = "Foto subida con exitosamente"
        return HttpResponse(json.dumps(data), content_type='application/json')

正如您在 crea_foto 变量中看到的那样有一个查询集,我在其中进行了过滤,然后更新了 foto 字段,但无法正常工作。事情是,如果不是过滤器,我做一个 create 查询集可以正常工作并创建照片,在管理中,如果我从头开始上传或更新照片也可以。仅在 update 查询集上发生,如何解决它的任何线索?

As you can see in crea_foto variable I have a queryset where I made a filter and then update the field foto, but I can't get it works. Thing is if instead filter, I do a create queryset works fine and create the photo, in the admin if I upload from scratch or update a photo works fine too. Only happens with update queryset, any clue of how to solve it?

PS:我使用的是Boto,

PS: I'm using Boto, but since images are uploaded with other methods it is discarded that Boto be the problem.

推荐答案

这真的很容易,只需添加一下在POST方法中:

It was really easy, just add this in POST method:

m = InteraccionFotos.objects.get(pk=1)
m.foto = request.FILES['foto']
m.save()

这篇关于如何从Django中的视图更新ImageField的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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