Django - ModelChoiceField验证

时间:2017-10-22 16:52:06

标签: django

我有一个简单的形式女巫ModelChoiceField。这是我的view.py文件的一部分:

def premium(request, id):
    context = {}
    try:
        site = Site.objects.get(id=id)
    except Site.DoesNotExist:
        raise Http404("Nie ma takiej strony")
    if request.method == 'POST':
        premium_form = PremiumForm(request.POST)
        if premium_form.is_valid():
            # group = Group.objects.get(id=request.POST["kod"])
            print('OK')
        else:
            print('NOT OK')
    else:
        premium_form = PremiumForm(site)
        premium_form.fields['group'].queryset = 
premium_form.fields['group'].queryset.exclude(group_name=site.group)

    context['site'] = site
    context['form'] = premium_form
    context['category'] = site.category
    context['subcategory'] = site.subcategory
    return render(request, 'mainapp/premium.html', context)

这是我的表格:

class PremiumForm(forms.Form):
    def __init__(self, site, *args, **kwargs):
        super(PremiumForm, self).__init__(*args, **kwargs)
        self.fields['group'].initial = 2
        self.fields['group'].empty_label = None

    group = forms.ModelChoiceField(
        queryset=Group.objects.filter(is_active=True),
        help_text="<div id='group'></div>",
        label="Some text",
        required=False)

我的premium.html文件:

<form method="post" action="" class="form-horizontal">
            {% csrf_token %}
            {% bootstrap_form form layout='horizontal'%} <br>
            {% bootstrap_button "Submit" size='large' button_type="submit" button_class="btn-primary btn-main-add" %}
        </form>

当我按&#34;提交&#34;按钮我得到&#34;不行&#34;。我无法解决这个问题。我不知道如何验证forms.ModelChoiceField。谢谢你的帮助。

1 个答案:

答案 0 :(得分:1)

表格应该用kwargs初始化:

premium_form = PremiumForm(site=site)

在init中:

def __init__(self, *args, **kwargs):
    site = kwargs['site']

但是,在表单初始化中不使用站点,因此您只需将其删除即可解决问题。