简体   繁体   English

django:如何从CharField和ModelChoiceField获得价值

[英]django: how to get value from CharField and ModelChoiceField

I have a class GroupAdminForm which is used to extend the group admin page in Django. 我有一个GroupAdminForm类,用于扩展Django中的组管理页面。 There are two fields, selected_to_change and print_name. 有两个字段,selected_to_change和print_name。 What I am designing to do is to select a column in "selected_to_change" and enter a char name in "print_name" , in order to make a query like: 我要设计的是在“ selected_to_change”中选择一列,并在“ print_name”中输入字符名称,以便进行如下查询:

UPDATE "annotation" 
SET print_name= "value of print_name" 
WHERE id = "value of selected_to_change";

Here is the GroupAdminForm: 这是GroupAdminForm:

class GroupAdminForm(forms.ModelForm):
    users = forms.ModelMultipleChoiceField(queryset=User.objects.all(),
                                       widget=FilteredSelectMultiple('Users', False),
                                       required=False)

    select_to_change = forms.ModelChoiceField(queryset=Annotation.objects.all(), required=False)
    print_name = forms.CharField(required=False)

    class Meta:
        model = Group

    def __init__(self, *args, **kwargs):
        instance = kwargs.get('instance', None)
        if instance is not None:
            initial = kwargs.get('initial', {})
            initial['users'] = instance.user_set.all()
            initial['locations'] = instance.c_locations.all()
            kwargs['initial'] = initial
        super(GroupAdminForm, self).__init__(*args, **kwargs)

    def save(self, commit=True):
        group = super(GroupAdminForm, self).save(commit=commit)

        if commit:
            group.user_set = self.cleaned_data['users']
        else:
            old_save_m2m = self.save_m2m
            def new_save_m2m():
                old_save_m2m()
                group.user_set = self.cleaned_data['users']
            self.save_m2m = new_save_m2m
        return group

How can I get the values from the CharField and ModelChoiceField to make such queries in the method save()? 如何从CharField和ModelChoiceField中获取值以在方法save()中进行此类查询? Thanks. 谢谢。

You are already using data from the saved form in self.cleaned_data. 您已经在self.cleaned_data中使用保存的表单中的数据。

print self.cleaned_data['select_to_change']
print self.cleaned_data['print_name']

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM