开发者

Django modelmultiplechoicefield unbound all objects that weren't at queryset

I feel my problem is quite obvious and has trivial solution, but I can't find it for few hours...

for realistic example let's imagine I have next models:

class Report(models.Model):
    title = models.CharField(max_length=60)
    author = models.ForeignKey(User)
    posts = models.ManyToManyField(Post)

class Post(models.Model):
    title = models.CharField(max_length=100)
    author = models.ForeignKey(User)

So there are reports and posts. Posts can be associated with some report. And there is following form for bounding/unbounding posts to reports.

class AddPostsToReport(ModelForm):
    def __init__(self, user, *args, **kwargs):
        super(A开发者_如何学JAVAddPostsToReport, self).__init__(*args, **kwargs)
        self.fields['posts'] = forms.ModelMultipleChoiceField(
             queryset=Post.objects.filter(author=user),
             required=False, 
             widget=forms.CheckboxSelectMultiple)

    class Meta:
        model = Report
        fields = ('posts', )

So I pass additional parameter (user) to form and when user opens page with this form he can only bound/unbound his own posts.

Everything works fine except one thing: when user saves form - all other users' posts which were before bound to that report become unbound. That is not what I need. I need that user can bound/unbound only his own posts to the report, but other users' posts don't reset their state.

Thank for any help.

EDIT: here is the view (it's not the real view, but the logic of real view is exactly the same)

@login_required
def report_add_posts(request, report_id):
    report = get_object_or_404(Report, pk = report_id)

    if request.method == 'POST':
        form = AddPostsToReport(request.user, request.POST, instance = report)

        if form.is_valid():
            form.save()

            return HttpResponseRedirect(reverse(...))
    else:
        form = AddPostsToReport(request.user, instance = report)

    return render_to_response('report/page_with_form_to_add_posts.html', 
                              { 'form': form,
                                'report': report }, 
                              context_instance=RequestContext(request))


I do not know of a "very easy" way to solve your problem. I would have used myform.save(commit=False) (from the view) and instead of calling the built in myform.save_m2m(), call a custom AddPostsToReport.save_posts() method that loops through self.instance['posts'], removing posts for the specified user not in self.cleaned_data['posts'] and later add the remaining new posts.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜