尽管从下拉列表中选择了某些内容,Django仍会显示错误消息

时间:2015-07-08 02:43:02

标签: django django-forms django-views

我有一个Django模型:

class Account(models.Model):
    name = models.CharField(max_length=50, blank=True)
    number = models.CharField(max_length=16, blank=True)

我想创建一个表单,用户可以从下拉列表中选择现有帐户的电话号码。所以在forms.py,我有:

class AccountSelectForm(forms.Form):
    phone_num_err_msgs = {'required': "You must select a phone number to send this message."}

    phone_number = forms.CharField(required=True, error_messages=phone_num_err_msgs)
    selected_group_ids = forms.CharField(required=True, widget=forms.HiddenInput)
    launch_datetime = forms.CharField(required=True)

views.py中,我有:

class AccountSelectView(LoginRequiredMixin, FormView):
    template_name = 'campaigns/send.html'
    form_class = AccountSelectForm
    success_url = reverse_lazy('campaigns:taskq_list')

    def get_context_data(self, **kwargs):
        data = super(AccountSelectView, self).get_context_data(**kwargs)
        data['groups'] = Group.objects.all()
        data['campaign'] = Campaign.objects.get(id=self.request.GET['cam_id'])
        data['accounts'] = Account.objects.all()
        return data

    def form_valid(self, form):
        # If we insert pdb, we never reach here
        #import pdb
        #pdb.set_trace()

        data = form.cleaned_data
        campaign_id = self.request.GET['cam_id']
        # ... do other form validation stuff here
        return super(ConversationSendView, self).form_valid(form)

send.html中,我有:

<form action="" method="post">
    {% csrf_token %}
    <!-- A couple of other fields to collect user input -->
    <div class="form-group">
        <p><b>Step 3: Select aphone number to send the message FROM:</b></p>
        {{ form.phone_number.errors }}
        <select id="phone" style="width: 380px;">
            <option value="">--------</option>
            {% for a in accounts %}
                <option value="{{ a.id }}">{{ a.number }}</option>
            {% endfor %}
        </select>
    <div class="page-btns">
        <input type="submit" class="btn btn-primary" value="Send Message to Selected Group(s)" />
    </div>
</form>

但是,尽管在提交之前从下拉列表中选择了条目(以及所有其他必需的表单),但我仍然会在HTML页面 [please see the screenshot here]上看到phone_num_err_msgs

我有什么遗失的东西吗?哪个(哪个文件)可以导入pdb并查看它返回错误的原因?我是Django的新手,所以这很可能是一个愚蠢的错误/忽视。感谢先进的答案!

1 个答案:

答案 0 :(得分:1)

这里有一些问题。直接原因是您在select标签中缺少name="phone_number ",因此浏览器不会发送该元素的任何数据。

但目前尚不清楚为什么要手动构建该元素。您应该使用ModelChoiceField,而不是定义CharField并忽略它,它会自动为您提供一个包含所有帐户的选择框。

class AccountSelectForm(forms.Form):
    ...
    phone_number = forms. ModelChoiceField(queryset=Account.objects.all())

...

{{ form.phone_number.errors }}
{{ form.phone_number }}