Django Formset不会按用户对象进行过滤

时间:2014-09-01 00:25:29

标签: python django formset

无法弄清楚如何过滤formset以仅显示已登录用户的博客帖子。表单呈现正常,但它允许任何用户将照片分配给任何博客帖子,无论谁拥有博客帖子。如何过滤仅适用于登录用户的博客选项?


views.py

@login_required
def addimage(request):
    user = request.user
    blogposts = Blogpost.objects.filter(user=user)
    print blogposts
    imageformset = modelformset_factory(Image, AddImageForm,extra=1) 
    if request.method == "POST":
        formset = imageformset(request.POST, request.FILES)
        if formset.is_valid() :
            for form in formset.cleaned_data:
                    image = form['image']
                    title = form['title']
                    blogpost = form['blogpost']
                    description = form['description']
                    photo = Image(
                        title = title,
                        image= image,
                        blogpost=blogpost,
                        description=description,
                        )
                    photo.user = request.user
                    photo.save()

            messages.success(request, 'We did it. Pictures are on the interwebs!')
            return HttpResponseRedirect("/%s/%s/" % (user, blogpost.slug))


    else:
        formset = imageformset()

    return render_to_response('photos/add_photos.html', {
        'formset' : formset,
        'blogpost' : blogposts,
        },
        context_instance=RequestContext(request))

forms.py

from django import forms 
from .models import *

class AddImageForm(forms.ModelForm):
    class Meta:
        model   = Image
        fields = ('image', 'title', 'blogpost', 'description')

Add_photos.html

{% extends "base.html" %}
{% load static %}
{% block content %}
<div>
    <form action="" method="POST" enctype="multipart/form-data">{% csrf_token %}
    <div id="submit"><input id="submit-btn" type="submit" value="Save"></div>
        {{ formset.management_form }}
        {{ formset.as_p }}

       <input type="submit" value="Save">
    </form>
</div>
{% endblock %}

1 个答案:

答案 0 :(得分:2)

看起来您的blogpost字段是ForeignKey。默认情况下,这由django.forms.ModelChoiceField表示。它继承自ChoiceField,其选择是模型QuerySet。请参阅ModelChoiceField的参考资料。

因此,您希望为字段的queryset属性提供自定义QuerySet。这取决于您的表单的构建方式。我觉得在构造函数中最容易做到但是使用formset工厂会让它变得有点棘手。您可以在构造formset后尝试这个:

formset = imageformset()
for form in formset.forms:
    form.fields['blogpost'].queryset = Blogpost.objects.filter(user=user)

我认为您还需要在request.method ==&#39; POST&#39;中调用formset.is_valid()之前执行此操作。代码的分支。