English 中文(简体)
Django 窗体内图像变化/删除
原标题:Change/delete images within Django formset

我使用一个表单上传图像, 并将其链接到使用多个多层关系的模型中。 我将表单显示在状态表下面, 这样用户就可以填充状态字段 + 添加图像, 然后单击“ 保存” 或“ 保存” 并添加另一个图像 。

最后一种情况是,它应该显示预填状态表,然后在块框内设置一个通常内容的块,以处理上传文件(一个链接到图像,一个要删除的复选框和一个上传不同图像的文件输入),最后显示一个空白文件输入,上传第二个图像。现在,我有两个空白文件输入。

窗体板知道已经上传了一张图像, 但是它没有显示管理它所需的任何东西 。 这是在窗体框中的图像字段的正常行为吗? 还是这里的图像字段的正常行为 与我提供窗体板数据的方式有问题?

这是代码:

# Models
class Image(models.Model):
    image = ImageField(upload_to= uploads/status/images/ ,)


class Status(models.Model):
    author = models.ForeignKey(User,)
    images = models.ManyToManyField(Image, blank=True, null=True)
    body = models.TextField()

# Forms
class StatusForm(forms.ModelForm):
    class Meta:
        model = Status
        fields = [ body ,]


class ImageForm(forms.ModelForm):
    class Meta:
        model = Image
        fields = [ image ,]

# View
@csrf_protect
def form(request, id=None, template_name= status/form.html ):
    if id:
        status = get_object_or_404(Status, pk=id)
        images = status.images.all().values()
    else:
        status = Status(author=request.user)
        images = None

    if request.method ==  POST :
        form = StatusForm(request.POST, instance=status)
        formset = ImageFormSet(request.POST, request.FILES, initial=images)

        if form.is_valid():
            try:
                status = form.save()

                if formset.is_valid():
                    try:
                        for form in formset:
                            image = form.save()
                            status.images.add(image)
                            status.save()

                        if request.POST.get( _add_image , None):
                            return HttpResponseRedirect(reverse( status_edit , args=[status.id]))
                        else:
                            messages.success(request,  Status saved )
                            return HttpResponseRedirect(request.POST.get( next ,  / ))
                    except:
                        messages.error(request,  Technical error )
            except:
                messages.error(request,  Technical error )
    else:
        form = StatusForm(instance=status)
        formset = ImageFormSet(initial=images)

    return render_to_response(template_name, {
         form : form,
         formset : formset,
         next : request.GET.get( next ,  / ),
    }, context_instance=RequestContext(request))

模板 :

<form action="" method="post" enctype="multipart/form-data">
    {% csrf_token %}
    {{ form.non_field_errors }}
    <input type="hidden" name="next" value="{{ next }}" />
    {{ form.body }}
    {{ form.body.errors }}
    <hr />
    {{ formset }}
    <hr />
    <div class="pull-right">
        <input name="_add_image" class="btn" type="submit" value="Add another image">
        <input name="_complete" class="btn btn-primary" type="submit" value="Save">
    </div>
</form>
最佳回答

M2M 关系为“ 正常 ” 。 目前设计时, 内线型号要求有一个外国密钥返回正在编辑的主对象。 唯一存在的地方是 M2M 关系的连接桌( Django Pallance 中的“ 通过”模式 ) 。 该模式本身通常由两个外国密钥组成, 每一边都由两个外国密钥组成 。

我玩弄了创建自定义格式的想法, 该格式包含您想要编辑的模型上的所有字段, 以及通常的选择字段, 以选择一个已有的字段, 然后将逻辑从字段中创建新实例, 并将其指定为唯一的真实字段, 即外国密钥。 然而, 它是一个要写入的代码的 < em> lot < / em >, 大部分是每个使用场景所独有和特有的, 并且它非常模糊( 您必须认识到总是要保持格式和模型同步 ) 。 我最终放弃了这个想法 。 也许有一天, 决哥会为此提供某种机制, 但现在, 它最好只是处理一下 。

问题回答

暂无回答




相关问题
How to get two random records with Django

How do I get two distinct random records using Django? I ve seen questions about how to get one but I need to get two random records and they must differ.

Moving (very old) Zope/Plone Site to Django

I am ask to move data from a (now offline) site driven by Plone to a new Django site. These are the version informations I have: Zope Version (unreleased version, python 2.1.3 ) Python Version 2.1....

Can Django models use MySQL functions?

Is there a way to force Django models to pass a field to a MySQL function every time the model data is read or loaded? To clarify what I mean in SQL, I want the Django model to produce something like ...

Flexible pagination in Django

I d like to implement pagination such that I can allow the user to choose the number of records per page such as 10, 25, 50 etc. How should I go about this? Is there an app I can add onto my project ...

is it convenient to urlencode all next parameters? - django

While writing code, it is pretty common to request a page with an appended "next" query string argument. For instance, in the following template code next points back to the page the user is on: &...

Pragmatically adding give-aways/freebies to an online store

Our business currently has an online store and recently we ve been offering free specials to our customers. Right now, we simply display the special and give the buyer a notice stating we will add the ...

热门标签