1

我已经阅读了许多其他抱怨此错误消息的线程,但我仍然无法弄清楚这一点。我尝试删除给出错误的字段,并且下次我尝试提交时错误消息只会移动到另一个字段。它们是 CharField、Foreign Key 和其他类型。

表格.py

class TemporaryresponseForm(forms.ModelForm):    
    gender_custom = forms.CharField(
        required=False,
        label="",        
    )

    ethnicity = forms.ModelChoiceField(
        queryset=Ethnicity.objects.all(),
        widget=forms.RadioSelect(),
        empty_label=None,
        required=True,
        label="Which of the following best describes your ethnicity?"
    )
...
class Meta:
        model = Temporaryresponse
        fields = [...'gender_custom', 'ethnicity',...]

视图.py

def tr(request):
    if request.method == "POST":
        form = TemporaryresponseForm(request.POST)
        if form.is_valid():
            tempresponse = form.save(commit=False)
            tempresponse.ip = "123456"
            tempresponse.save()
            return redirect('politicalpollingapp/index.html')
    else:
        form = TemporaryresponseForm()
    return render(request, 'politicalexperimentpollapp/tr.html', {'form': form})


def nr(request, pk):
    return render(request, 'politicalexperimentpollapp/nr.html', {'tempresponse': tempresponse})

tr.html 模板

{% extends 'politicalexperimentpollapp/base.html' %}
{% block extrahead %}
{% load crispy_forms_tags %}
{{ form.media }}
{% endblock extrahead%} 
...
<form method="POST">
        {% csrf_token %}
        {{ form.as_p }}
        <div><br></div>

        <div class="text-center"><button type="submit" class="save btn btn-primary">CONTINUE</button></div>
    </form>
..

模型.py

class Ethnicity(models.Model):
    ethnicity = models.CharField(max_length=200)

    def __str__(self):
        return '%s' % (self.ethnicity)
...
class Temporaryresponse(models.Model):
    birth_year = models.PositiveIntegerField()
    voting_registration = models.ForeignKey(Voting_registration, models.SET_NULL, null=True)
    party_identification = models.ForeignKey(Party_identification, models.SET_NULL, null=True)
    gender = models.ForeignKey(Gender, models.SET_NULL, null=True)
    gender_custom = models.CharField(max_length=200, blank=True)
    ethnicity = models.ForeignKey(Ethnicity, models.SET_NULL, null=True)
    race = models.ManyToManyField(Race)
    zip_code = models.IntegerField()
    ip = models.CharField(max_length=200, blank=True)
    policy_areas_of_importance = models.ManyToManyField(Policy_category, blank=True)
    likelihood_of_voting = models.PositiveIntegerField(models.SET_NULL, null=True, blank=True)

奇怪的是,我的 Chrome 控制台中没有出现错误——这只是因为我在实际页面上显示了错误。我不确定这是否正常。在此先感谢您的帮助,此时我正在扯掉头发。

4

1 回答 1

1

我发现我在“种族”表单字段中使用了错误的语言。我使用过 ModelChoiceField 但它应该是 ModelMultipleChoiceField 如下:

race = forms.ModelMultipleChoiceField(queryset=Race.objects.all(), widget=forms.CheckboxSelectMultiple, label="5. Which of the following best describes your race? Please select all that apply.")
于 2019-10-16T16:17:37.503 回答