使用Get()函数编辑多个对象Django

时间:2016-05-28 13:31:17

标签: python django django-models django-views

我想在Django中编辑两个表单。 “汽车旅馆”及其“图片”的表格。在我的应用中,用户可以将多个图像上传到“汽车旅馆”模型。现在,用'get()'函数编辑图像给了我,

MultipleObjectsReturned get() returned more than one MotelImages -- it returned 4!

模型

class Motel(models.Model):
    user= models.ForeignKey(User)
    title= models.CharField(max_length=120)
    body= models.TextField()
    #other fields

class MotelImages(models.Model):
    motel= models.ForeignKey(Motel, default=None, related_name='images')
    image= models.ImageField(upload_to='company', verbose_name= 'Image')

class MotelImagesForm(forms.ModelForm):
    image= forms.ImageField(label='Image',)

    def __init__(self, *args, **kwargs):
        super(MotelImagesForm,self).__init__(*args, **kwargs)
        self.fields['image'].widget= forms.FileInput(attrs={'name':'image',
                                                         'multiple':'multiple'})

保存表单的视图

def create_motel(request):
    if request.method=="POST":

        motelForm= MotelForm(request.POST, request.FILES)
        formset=MotelImagesForm(request.POST, request.FILES)

        if motelForm.is_valid() and formset.is_valid():

           human= True

           motel_form= motelForm.save(commit=False)
           motel_form.user= request.user
           motel_form.pub_date= datetime.datetime.now()
           motel_form.save()

           for image in request.FILES.getlist('image',[]):
                photo= MotelImages(motel=motel_form, image=image)
                photo.save()

            messages.success(request,
                         "Welldone Boy")
            return HttpResponseRedirect('/view_all/')
        else:
            print motelForm.errors, formset.errors

    else:
        motelForm=MotelForm()
        formset= MotelImagesForm()
        return render(request, 'motels/add_motel.html',{'motelForm': motelForm, 'formset':formset})

编辑表单的视图

@login_required
def  edit_motel(request,motel_id=None,slug=None,template_name='motel_edit.html'):
    if id:
         post=get_object_or_404(Motel,id=motel_id,slug=slug)
         images=MotelImages.objects.get(motel=motel_id)
    else:
        post=Motel(user=request.user)
        images=MotelImages(user=request.user)
    if request.POST:
        motelform=MotelForm(request.POST,request.FILES, instance=post)
        formset=MotelImagesForm(request.POST,request.FILES, instance=images)

        if form.is_valid() and formset.is_valid():
            form.save()
            formset.save()
            redirect_url=reverse('moteldetail',kwargs={'motel_id':motel_id,'slug':slug})
            return render(request, 'motels/updatenotice.html')

    else:
        form=MotelForm(instance=post)
        formset= MotelImagesForm(instance=images)
    return render(request, template_name,{'formset':formset,'motelform':motelform})

用于编辑表单的模板

<form id="post_form" method="post" action=""
      enctype="multipart/form-data">

    {% csrf_token %}
    {% for hidden in motelform.hidden_fields %}
        {{ hidden }}
    {% endfor %}

    {% for field in motelform %}
       {{ field.name }}
       {{ field }} <br />
    {% endfor %}

     {{ formset.management_form }}
          {% for form in formset %}
            {{ form }}
    {% endfor %}
  <input type="submit" name="submit" value="Submit" />
 </form>

我错过了什么?

1 个答案:

答案 0 :(得分:0)

images = MotelImages.objects.get(motel=motel_id)

由于get只能返回一个对象,因此您需要使用filter

images = MotelImages.objects.filter(motel__pk=motel_id)

images将是相关图片的列表。