form.clean()从表单中删除一些数据

时间:2016-06-13 15:00:36

标签: python django forms

我在视图中发布了帖子请求,当我form.data()时,我会看到所有表单数据,但每当我form.clean()时,都会丢失一些数据。从而使表格无效。

这种行为有原因吗?

错误是:product_name                选择一个有效的选择。这个选择不是可用的选择之一。

views.py

class AddKeywordSet(View):
def load_keyword_set(self, request, org_id=None):
    event_source_id = request.GET.get('event_source_id', None)
    product_name = request.GET.get('product_name', None)
    if org_id:
        form = KeywordSetForm(organization_id=org_id, event_source_id=event_source_id, product_name=product_name)
        org_name = Organization.objects.get(pk=org_id).name
    else:
        form = KeywordSetForm()
    return render(request, 'add_keywordset.html', locals())

def get(self, request, org_id=None, event_source_id=None, product_name=None):
    return self.load_keyword_set(request, org_id)

def post(self, request, org_id=None):
    event_source_id = request.GET.get('event_source_id')
    product_id = request.GET.get('product_id')
    form = KeywordSetForm(request.POST, organization_id=org_id)

    organization_id = form.data['organization']
    if form.data['product_name']:
        product = form.data['product_name']
    else:
        product = None
    event_source_id = form.data['event_source']
    event_source = EventSource.objects.get(pk=event_source_id)
    keyword_set = form.data['keyword_set']

    for keyword in keyword_set.split(','):
        try:
            Keyword.objects.get_or_create(organization_id=organization_id, product_name=product,
                                     event_source=event_source, keyword=keyword.strip())
        except ValidationError as e:
            form._errors['validation'] = form.error_class([e])
    if request.POST.get('button_name') == 'submit_btn':
        return render(request, 'add_keywordset.html', locals())
    else:
        return redirect('/internal/organization/blacklist/add/{}'.format(organization_id))
    return render(request, 'add_keywordset.html', locals())

forms.py

class KeywordSetForm(forms.Form):
organization = forms.ModelChoiceField(
    widget=forms.Select(attrs={'class': 'form-control'}),
    queryset=Organization.objects.filter(deleted=False).order_by('name'), empty_label="(Select a customer)")
product_name = forms.ModelChoiceField(
    widget=forms.Select(attrs={'class': 'form-control'}),
    empty_label="(Select a Product)", required=False, queryset=OrganizationProduct.objects.none(), initial=None)
event_source = forms.ModelChoiceField(
    widget=forms.Select(attrs={'class': 'form-control'}), queryset=EventSource.objects.all(), empty_label="(Select a Keyword Type)")
keyword_set = forms.CharField(widget=forms.Textarea(attrs={'class': 'form-control', 'required': 'True',
                                                           'placeholder': 'Enter comma separated keywords here'}))

def __init__(self, *args, **kwargs):
    organization_id = kwargs.pop('organization_id', None)

    if args:
        for arg in args:
            event_source_id = arg['event_source']
            product_name = arg['product_name']
    else:
        event_source_id = kwargs.pop('event_source_id', None)
        product_name = kwargs.pop('product_name', None)


    print organization_id, event_source_id, product_name

    super(KeywordSetForm, self).__init__(*args, **kwargs)
    if organization_id:
        self.fields['product_name'] = forms.ModelChoiceField(
            widget=forms.Select(attrs={'class': 'form-control'}),
            empty_label="(Select a Product)",
            queryset=OrganizationProduct.objects.filter(organization_id=organization_id).values_list('name', flat=True).distinct(),
            required=True, initial=""
        )
        self.fields['organization'] = forms.ModelChoiceField(
            widget=forms.Select(attrs={'class': 'form-control'}),
            queryset=Organization.objects.filter(deleted=False).order_by('name'),
            empty_label="(Select a customer)",
            initial=Organization.objects.get(pk=organization_id)
        )

        event_source = None
        product = None
        if event_source_id:
            event_source = EventSource.objects.get(pk=event_source_id)
            self.fields['event_source'] = forms.ModelChoiceField(
                widget=forms.Select(attrs={'class': 'form-control'}), queryset=EventSource.objects.all(),
                initial=event_source)

        if product_name:
            print 'product_name', product_name

            self.fields['product_name'] = forms.ModelChoiceField(
                            widget=forms.Select(attrs={'class': 'form-control'}),
                            empty_label="(Select a Product)",
                            queryset=OrganizationProduct.objects.filter(organization_id=organization_id).values_list('name', flat=True).distinct(),
                            required=True, initial=OrganizationProduct.objects.filter(organization_id=organization_id, name=product_name)[0].name)
        keyword_set = (', ').join(Keyword.objects.filter(event_source=event_source, organization_id=organization_id, product_name=product_name).values_list('keyword', flat = True))  
        self.fields['keyword_set'] = forms.CharField(widget=forms.Textarea(attrs={'class': 'form-control'}), initial=keyword_set)

0 个答案:

没有答案