Django UpdateView-从多对多字段获取初始数据,并在保存表单时添加它们 [英] Django UpdateView - get initial data from many-to-many field and add them when saving form

查看:46
本文介绍了Django UpdateView-从多对多字段获取初始数据,并在保存表单时添加它们的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用基于Django类的通用视图.在我的models.py中,我有一个名为MyModel的模型,该模型具有名为m2m的多对多字段.我有多个用户组,他们可以编辑m2m字段.每组用户只能看到他们的部分并将其添加到字段中-使用get_form设置他们在m2m字段中可以看到的内容.我遇到的问题是,当一个用户输入记录时,它将删除m2m字段中的初始记录.我需要以某种方式从m2m字段中获取初始值,然后保存它们,然后在提交表单时将它们添加到新值中.这是我的views.py:

I'm using Django class based generic view. In my models.py I have a model called MyModel with many-to-many field called m2m. I have multiple groups of users they can edit the m2m field. Each group of users can only see and add their portion to the field - using get_form to set what they can see in the m2m field. The problem I'm having is that when one user enter his record it will delete the initial records in the m2m field. I need to somehow get the initial values from the m2m field save them and then add them to the new ones when the form is submitted. Here is my views.py:

class MyModelUpdate(UpdateView):
    model = MyModel
    fields = ['m2m']

    def get_initial(self):
        return initials

    def get_form(self, form_class=None):    
        form = super(MyModelUpdate, self).get_form(form_class)
        form.fields["m2m"].queryset = DiffModel.objects.filter(user = self.request.user)
        return form 

    def form_valid(self, form):
        form.instance.m2m.add( ??? add the initial values) 
        return super(MyModelUpdate, self).form_valid(form)

    def get_success_url(self):
        ...

经过几天的搜索和编码,

推荐答案

我找到了解决方案.

views.py:

from itertools import chain
from .forms import MyForm,

def MyModelUpdate(request, pk):
template_name = 'mytemplate.html'
instance = MyModel.objects.get(pk = pk)

instance_m2m = instance.m2m.exclude(user=request.user) 

if request.method == "GET":
    form = MyForm(instance=instance, user=request.user)
    return render(request, template_name, {'form':form})
else:
    form = MyForm(request.POST or None, instance=instance, user=request.user)
    if form.is_valid():
        post = form.save(commit=False)
        post.m2m = chain(form.cleaned_data['m2m'], instance_m2m)
        post.save()
        return redirect(...)

forms.py:

from django import forms
from .models import MyModel

class MyForm(forms.ModelForm):
class Meta:
    model = MyModel
    fields = ['m2m']

def __init__(self, *args, **kwargs):
    current_user = kwargs.pop('user')
    super(MyForm, self).__init__(*args, **kwargs)
    self.fields['m2m'].queryset = self.fields['m2m'].queryset.filter(user=current_user)

这篇关于Django UpdateView-从多对多字段获取初始数据,并在保存表单时添加它们的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆