选择一个有效的选择。 XXXXXXXX不是可用选项之一

时间:2016-06-10 12:18:41

标签: python django

我想通过管理员端向所选用户表单发送短信多个选项,但是,在管理员完成选择后,我无法从select_users字段获取值。请帮我解决这个问题。

这是我的代码

forms.py

class SendSMSForm(forms.ModelForm):
    select_users = forms.ModelMultipleChoiceField(queryset=SignUp.objects.all(), widget=forms.CheckboxSelectMultiple)
    class Meta:
        model = SendSMS
        fields = ['sms_subject','sms_text']
        widgets = { 
        'sms_text': forms.Textarea()
        }
    def __init__(self, *args, **kwargs):
        super(SendSMSForm, self).__init__(*args, **kwargs)
        self.fields['select_users'].choices = [(str(item.mobile_no), str(item.mobile_no)) for item in SignUp.objects.all()]

admin.py

class SendSMSAdmin(admin.ModelAdmin):
    change_form_template = "admin/sms/SmsMarketing/change_form.html"
    form = SendSMSForm
    list_display = ['sms_subject','sms_text','date1']
    list_filter = ('sms_subject',)
    def get_form(self, request, obj=None, **kwargs):
        if request.method == 'POST':
            form = SendSMSForm(request.POST)
            if form.is_valid():
                subject = form.cleaned_data['sms_subject']
                message = form.cleaned_data['sms_text']
                ***users = form.cleaned_data['select_users']***
                print users
                obj = SendSMS()
                for user in users:
                    result = obj.sendsms(message, user)
                    obj_name = User.objects.get(username=user)
                    if result:
                        SmsHistory.objects.create(
                            number=user,
                            recipient=obj_name.get_full_name(),
                            sms_subject=subject, 
                            sms_text=message,
                            sms_type = "Promotional SMS"
                            )                   
            else:
                return SendSMSForm
        return SendSMSForm  

1 个答案:

答案 0 :(得分:2)

你可以尝试:

select_users = forms.MultipleChoiceField(widget=forms.CheckboxSelectMultiple)