从具有多个图像的帖子编辑图像,Image_titles,Image_description

时间:2018-05-06 00:49:48

标签: django python-3.x django-models django-forms django-views

你好Djangonauts,                   我创建了一个包含多个图像的帖子。它工作得很好但是当我尝试用多个图像编辑帖子时,我得到了一个AttributeError。问题末尾发布的错误消息的图像。以下是我的     的 models.py

class Post(models.Model):
    user = models.ForeignKey(User, related_name='posts')
    title = models.CharField(max_length=250, unique=True)
    slug = models.SlugField(allow_unicode=True, unique=True)
    message = models.TextField()
    post_image = models.ImageField()

    def get_absolute_url(self):
        return reverse('posts:single', kwargs={'username': self.user.username,
                                           'slug': self.slug})

class Prep (models.Model): #(Images)
    post = models.ForeignKey(Post, on_delete=models.CASCADE, related_name='post_prep')
    image = models.ImageField(upload_to='images/', blank=True, null=True, default='')
    image_title = models.CharField(max_length=100, default='')
    image_description = models.CharField(max_length=250, default='')

    def __str__(self):
        return self.post.title + " Image"

现在我已经成功创建了 post_create ,因为您可以在下面看到这项工作完美无缺,并在我的帖子中添加了多个图片,以及image_title和image_description

@login_required
def post_create(request):
    ImageFormSet = modelformset_factory(Prep, fields=('image', 'image_title', 'image_description'), extra=7)
    if request.method == "POST":
        form = PostForm(request.POST or None, request.FILES or None)
        formset = ImageFormSet(request.POST or None, request.FILES or None)
        if form.is_valid() and formset.is_valid():
            instance = form.save(commit=False)
            instance.user = request.user
            instance.save()
            print(formset.cleaned_data)
            for f in formset.cleaned_data:
                try:
                    photo = Prep(post=instance, image=f['image'], image_title=f['image_title'], image_description=f['image_description'])
                    photo.save()
                except Exception as e:
                    break
            return redirect('posts:single', username=instance.user.username, slug=instance.slug)
    else:
        form = PostForm()
        formset = ImageFormSet(queryset=Prep.objects.none())
    context = {
        'form': form,
        'formset': formset,
    }
    return render(request, 'posts/post_form.html', context)

但我的post_edit视图给我一个错误,请参阅代码下方的图片以查看错误消息的图像。以下是 post_edit

的代码
def post_edit(request, slug):
    post = get_object_or_404(Post, slug=slug)
    ImageFormSet = modelformset_factory(Prep, fields=('image', 'image_title', 'image_description'), extra=7, max_num=7)
    if post.user != request.user:
        raise Http404()
    if request.method == "POST":
        form = PostEditForm(request.POST or None, request.FILES or None, instance=post)
        formset = ImageFormSet(request.POST or None, request.FILES or None)

        if form.is_valid() and formset.is_valid():
            form.save()
            print(formset.cleaned_data)
            data = Prep.objects.filter(post=post)
            for index, f in enumerate(formset):
                if f.cleaned_data:
                    if f.cleaned_data['id'] is None:
                        photo = Prep(post=post, image=f.cleaned_data.get('image'), image_title=f.cleaned_data.get('image_title'),
                                     image_description=f.cleaned_data.get('image_description'))
                        photo.save()
# I believe the code below this the "elif" and "else" part may have some error but can't seem to find where the problem is
                    elif (f.cleaned_data['image'], f.cleaned_data['image_title'], f.cleaned_data['image_description']) is False:
                        photo = Prep.objects.get(id=request.POST.get('form-' + str(index) + '-id'))
                        photo.delete()
                    else:
                        photo = Prep(post=post, image=f.cleaned_data.get('image'), image_title=f.cleaned_data.get('image_title'),
                                     image_description=f.cleaned_data.get('image_description'))
                        d = Prep.objects.get(id=data[index].id)
                        d.image=photo.image,
                        d.image_title=photo.image_title,
                        d.image_description=photo.image_description
                        d.save()


            return HttpResponseRedirect(post.get_absolute_url())
    else:
        form = PostEditForm(instance=post)
        formset = ImageFormSet(queryset=Prep.objects.filter(post=post))
    context = {'form': form, 'post': post, 'formset': formset}
    return render(request, 'posts/post_edit.html', context)

如果我尝试编辑具有多个Prep图像的帖子,则会出现以下错误消息。 。 ,enter image description here

1 个答案:

答案 0 :(得分:1)

尝试在这些行中编辑代码; 最后添加逗号,Python将此行为视为元组

d = Prep.objects.get(id=data[index].id)
d.image=photo.image #, # remove comma
d.image_title=photo.image_title #, # remove comma

对于elif子句: 而不是Variable is False,请执行此操作not Variable

elif not f.cleaned_data['image'] or not f.cleaned_data['image_title'] or not f.cleaned_data['image_description']:
    photo = Prep.objects.get(id=request.POST.get('form-' + str(index) + '-id'))
    photo.delete()