Django错误:预期的字符串或缓冲区

时间:2017-04-03 09:51:17

标签: python django forms

当我提交Django表单时,我收到了Django错误:expected string or buffer。我已经根据同样的问题阅读了一些SO问题,但它似乎没有用。

这是我的models.py表格:

class BirthCertificate(models.Model):

    lastname = models.CharField(max_length=30, null=False, verbose_name='Nom de famille')
    firstname = models.CharField(max_length=30, null=False, verbose_name='Prénom(s)')
    sex = models.CharField(max_length=8, choices=SEX_CHOICES, verbose_name='Sexe')
    birthday = models.DateField(null=False, verbose_name='Date de naissance')
    birthhour = models.TimeField(null=True, verbose_name='Heure de naissance')
    birthcity = models.CharField(max_length=30, null=False, verbose_name='Ville de naissance')
    birthcountry = CountryField(blank_label='Sélectionner un pays', verbose_name='Pays de naissance')
    fk_parent1 = models.ForeignKey(Person, related_name='ID_Parent1', verbose_name='ID parent1', null=False)
    fk_parent2 = models.ForeignKey(Person, related_name='ID_Parent2', verbose_name='ID parent2', null=False)
    mairie = models.CharField(max_length=30, null=False, verbose_name='Mairie')
    social_number = models.CharField(max_length=30, null=True, verbose_name='numero social', unique=True)
    created = models.DateTimeField(auto_now_add=True)

这是我的forms.py:

class BirthCertificateForm2(forms.ModelForm):
    fk_parent1 = CustomLabelModelChoiceField(Person.objects.filter(), required=False, label = "Père", label_func=lambda obj: '%s %s %s' % (obj.lastname, obj.firstname, obj.social_number), empty_label=None)
    fk_parent2 = CustomLabelModelChoiceField(Person.objects.filter(), required=False, label = "Mère", label_func=lambda obj: '%s %s %s' % (obj.lastname, obj.firstname, obj.social_number), empty_label=None)
    lastname = CustomLabelModelChoiceField(Person.objects.filter(), required=False, label = "Nom", label_func=lambda obj: '%s' % (obj.lastname), empty_label=None)
    firstname = CustomLabelModelChoiceField(Person.objects.filter(), required=False, label = "Prénom", label_func=lambda obj: '%s' % (obj.firstname), empty_label=None)
    birthday = CustomLabelModelChoiceField(Person.objects.filter(), required=False, label = "Date de Naissance", label_func=lambda obj: '%s' % (obj.birthday), empty_label=None)
    birthcity = CustomLabelModelChoiceField(Person.objects.filter(), required=False, label = "Ville de Naissance", label_func=lambda obj: '%s' % (obj.birthcity), empty_label=None)
    sex = CustomLabelModelChoiceField(Person.objects.filter(), required=False, label = "Sexe", label_func=lambda obj: '%s' % (obj.sex), empty_label=None)
    birthcountry = CustomLabelModelChoiceField(Person.objects.filter(), required=False, label = "Pays de Naissance", label_func=lambda obj: '%s' % (obj.birthcountry), empty_label=None)
    mairie = forms.CharField(widget=forms.HiddenInput(), initial=Mairie.objects.get(id=1).city.encode('utf-8')) 
    social_number = forms.CharField(widget=forms.HiddenInput(),required=False)


    class Meta :
        model = BirthCertificate
        fields = ['lastname', 'firstname', 'sex', 'birthday', 'birthhour', 'birthcity', 'birthcountry','fk_parent1', 'fk_parent2', 'mairie', 'social_number']
        widgets = {'country': CountrySelectWidget()}

        def __init__(self, *args, **kwargs):    
            super(BirthCertificateForm2, self).__init__(*args, **kwargs)
            for key, value in self.fields.iteritems() :
                self.fields[key].widget.attrs.update({'class':'form-fields'})   

最后我在views.py中的功能:

def BirthCertificate_Form_unique_number(request) :

    #User fill some fields
    query_social_number = request.GET.get('social_number')
    query_social_number_father = request.GET.get('social_number_father')
    query_social_number_mother = request.GET.get('social_number_mother')

    if request.method == 'POST':

        form = BirthCertificateForm2(request.POST or None)

        if form.is_valid() :   # Vérification sur la validité des données
            post = form.save()
            return HttpResponseRedirect(reverse('BC_treated', kwargs={'id': post.id}))

    else:

        form = BirthCertificateForm2()

        parent1 = Person.objects.filter(social_number=query_social_number_father)
        parent2 = Person.objects.filter(social_number=query_social_number_mother)
        individu = Person.objects.filter(social_number=query_social_number)

        form = BirthCertificateForm2(request.POST or None)

        form.fields['fk_parent1'].queryset = parent1
        form.fields['fk_parent2'].queryset = parent2
        form.fields['lastname'].queryset = individu
        form.fields['firstname'].queryset = individu
        form.fields['birthday'].queryset = individu
        form.fields['birthcity'].queryset = individu
        form.fields['birthcountry'].queryset = individu
        form.fields['sex'].queryset = individu
        form.fields['social_number'].queryset = individu

        print request.POST

    context = {
        "form" : form,
    }

    return render(request, 'BC_form2.html', context)

我的功能允许最初使用来自其他模型的数据填充我的BirthCertificate表单。

但是当我提交表单时,我收到标题错误。

这是追溯:

Environment:


Request Method: POST
Request URL: http://localhost:8000/BirthCertificate/formulaire2?social_number=1+87+10+STRASBOURG+-+583403&social_number_father=1+99+12+BREST+-+765533&social_number_mother=1+87+10+STRASBOURG+-+583403

Django Version: 1.10.3
Python Version: 2.7.12
Installed Applications:
['django.contrib.admin',
 'django.contrib.auth',
 'django.contrib.contenttypes',
 'django.contrib.sessions',
 'django.contrib.messages',
 'django.contrib.staticfiles',
 'BirthCertificate',
 'Identity',
 'bootstrapform',
 'Accueil',
 'django_countries',
 'log',
 'Mairie',
 'Table',
 'Recensement',
 'Configurations',
 'debug_toolbar',
 'chartit',
 'Mariage']
Installed Middleware:
['django.contrib.sessions.middleware.SessionMiddleware',
 'django.middleware.locale.LocaleMiddleware',
 'django.middleware.common.CommonMiddleware',
 'django.middleware.csrf.CsrfViewMiddleware',
 'django.middleware.gzip.GZipMiddleware',
 'django.contrib.auth.middleware.AuthenticationMiddleware',
 'django.contrib.auth.middleware.SessionAuthenticationMiddleware',
 'django.contrib.messages.middleware.MessageMiddleware',
 'django.middleware.clickjacking.XFrameOptionsMiddleware',
 'django.middleware.security.SecurityMiddleware',
 'debug_toolbar.middleware.DebugToolbarMiddleware']



Traceback:

File "/usr/local/lib/python2.7/site-packages/django/core/handlers/exception.py" in inner
  39.             response = get_response(request)

File "/usr/local/lib/python2.7/site-packages/django/core/handlers/base.py" in _legacy_get_response
  249.             response = self._get_response(request)

File "/usr/local/lib/python2.7/site-packages/django/core/handlers/base.py" in _get_response
  187.                 response = self.process_exception_by_middleware(e, request)

File "/usr/local/lib/python2.7/site-packages/django/core/handlers/base.py" in _get_response
  185.                 response = wrapped_callback(request, *callback_args, **callback_kwargs)

File "/Users/valentinjungbluth/Desktop/Django/Etat_civil/BirthCertificate/views.py" in BirthCertificate_Form_unique_number
  81.         if form.is_valid() :   # Vérification sur la validité des données

File "/usr/local/lib/python2.7/site-packages/django/forms/forms.py" in is_valid
  169.         return self.is_bound and not self.errors

File "/usr/local/lib/python2.7/site-packages/django/forms/forms.py" in errors
  161.             self.full_clean()

File "/usr/local/lib/python2.7/site-packages/django/forms/forms.py" in full_clean
  372.         self._post_clean()

File "/usr/local/lib/python2.7/site-packages/django/forms/models.py" in _post_clean
  398.             self.instance.full_clean(exclude=exclude, validate_unique=False)

File "/usr/local/lib/python2.7/site-packages/django/db/models/base.py" in full_clean
  1210.             self.clean_fields(exclude=exclude)

File "/usr/local/lib/python2.7/site-packages/django/db/models/base.py" in clean_fields
  1252.                 setattr(self, f.attname, f.clean(raw_value, self))

File "/usr/local/lib/python2.7/site-packages/django/db/models/fields/__init__.py" in clean
  590.         value = self.to_python(value)

File "/usr/local/lib/python2.7/site-packages/django/db/models/fields/__init__.py" in to_python
  1237.             parsed = parse_date(value)

File "/usr/local/lib/python2.7/site-packages/django/utils/dateparse.py" in parse_date
  60.     match = date_re.match(value)

Exception Type: TypeError at /BirthCertificate/formulaire2
Exception Value: expected string or buffer

编辑:

我的CustomLabelModelChoiceField类如下所示:

class CustomLabelModelChoiceField(forms.ModelChoiceField):

    def __init__(self, *args, **kwargs):
        self._label_from_instance = kwargs.pop('label_func', force_text)
        super(CustomLabelModelChoiceField, self).__init__(*args, **kwargs)

    def label_from_instance(self, obj):
        return self._label_from_instance(obj)

我的html文件:

{% extends 'Base_BirthCertificate_Naissance.html' %}

{% load staticfiles %}

{% block title %}
    <h3> <span class="glyphicon glyphicon-file"></span>Acte de Naissance à partir d'un numéro unique</align> </h3>
{% endblock %}

{% block content %}

<style>

form > input {
    width:20%;
    }

    form {
        list-style: none;
    }

</style>

    <!-- ############### -->
    <!-- Page principale -->
    <!-- ############### -->

            <form class = "form" method="GET" action="">

                <h4> Numéro unique de l'individu : </h4>

                <input type="text"  name="social_number" placeholder="N° unique de l'individu" value="{{request.GET.social_number}}">&nbsp;

                <h4> Nom de famille du père et de la mère : </h4>

                <input type="text"  name="social_number_father" placeholder="N° unique du père" value="{{ request.GET.social_number_father }}">&nbsp;
                <input type="text"  name="social_number_mother" placeholder="N° unique de la mère" value="{{ request.GET.social_number_mother }}">&nbsp;
                <input class="button" type="submit" value="Valider">

                <br></br>

            </form>

            <form class = "form" method='POST' action=''> {% csrf_token %}
                <br></br>
                {{ form.as_p}} <!-- Display child part formulary -->
                {{ value|date:"%d/%m/%Y" }}
                <br></br>

                <input class="button" type ="submit" value="Valider l'acte de naissance" /> 
            </form>


{% endblock content %}

编辑2:

我从POST数据简历中拍照,这可能是对我的错误expected string or buffer的解释!我有int,我不知道为什么

enter image description here

2 个答案:

答案 0 :(得分:1)

您调用POST方法,检索参数,就好像它们位于GET方法中一样。

但即使在您调用POST方法后,您的request.POST也是空的。

你的form.is_valid()抛出了你得到的错误,这意味着你正在调用POST方法。您需要调试POST为空的原因。

向我们展示您形成请求的代码。

更新

是的,您没有正确形成POST方法。

Request URL: http://localhost:8000/BirthCertificate/formulaire2?social_number=1+87+10+STRASBOURG+-+583403&social_number_father=1+99+12+BREST+-+765533&social_number_mother=1+87+10+STRASBOURG+-+583403
这告诉您在GET方式中以querystring方式传递参数,而在POST中传递参数在body中。

更新2

您需要在html表单中指定action=/formulaire2/action=/BirthCertificate/formulaire2/

答案 1 :(得分:1)

我找到了答案:问题出在我的forms.py文件中。在我的模型中,我有birthday这是一个DateField,在我的表单中它是一个Person ForeignKey ..

所以我必须写:

我的表格/ py文件:

class BirthCertificateForm2(forms.ModelForm):
    fk_parent1 = CustomLabelModelChoiceField(Person.objects.filter(), required=False, label = "Père", label_func=lambda obj: '%s %s %s' % (obj.lastname, obj.firstname, obj.social_number), empty_label=None)
    fk_parent2 = CustomLabelModelChoiceField(Person.objects.filter(), required=False, label = "Mère", label_func=lambda obj: '%s %s %s' % (obj.lastname, obj.firstname, obj.social_number), empty_label=None)
    sex = forms.CharField(required=False, label = "Sexe")
    birthcountry = forms.CharField(required=False, label = "Pays de Naissance")
    mairie = forms.CharField(widget=forms.HiddenInput(), initial=Mairie.objects.get(id=1).city.encode('utf-8')) 


    class Meta :
        model = BirthCertificate
        fields = ['lastname', 'firstname', 'sex', 'birthday', 'birthhour', 'birthcity', 'birthcountry','fk_parent1', 'fk_parent2', 'mairie', 'social_number']
        widgets = {'country': CountrySelectWidget()}

        def __init__(self, *args, **kwargs):    
            super(BirthCertificateForm2, self).__init__(*args, **kwargs)
            for key, value in self.fields.iteritems() :
                self.fields[key].widget.attrs.update({'class':'form-fields'})

我的观点功能:

@login_required
def BirthCertificate_Form_unique_number(request) :

    #User fill some fields
    query_social_number = request.GET.get('social_number')
    query_social_number_father = request.GET.get('social_number_father')
    query_social_number_mother = request.GET.get('social_number_mother')

    if request.method == 'POST':

        form = BirthCertificateForm2(request.POST or None)

        if form.is_valid() :   # Vérification sur la validité des données
            post = form.save()
            return HttpResponseRedirect(reverse('BC_treated2', kwargs={'id': post.id}))

    else:

        form = BirthCertificateForm2()

        parent1 = Person.objects.filter(social_number=query_social_number_father)
        parent2 = Person.objects.filter(social_number=query_social_number_mother)
        individu = get_object_or_404(Person, social_number = query_social_number)

        form.fields['fk_parent1'].queryset = parent1
        form.fields['fk_parent2'].queryset = parent2
        form.fields['lastname'].initial = individu.lastname
        form.fields['firstname'].initial = individu.firstname
        form.fields['birthday'].initial = individu.birthday
        form.fields['birthcity'].initial = individu.birthcity
        form.fields['birthcountry'].initial = individu.birthcountry
        form.fields['sex'].initial = individu.sex
        form.fields['social_number'].initial = individu.social_number


    context = {
        "form" : form,

    }
    print request.POST

    return render(request, 'BC_form2.html', context)

现在它有效:)