0

別の開発者のコ​​ードを編集しようとしています。このエラーが発生するまで、すべてがうまくいきました:

/berichten/registreren/ の ValueError 「u」を割り当てられません: 「Bericht.beller」は「Beller」インスタンスでなければなりません。

トレースバックから始めます。

Environment:
Request Method: POST
Request URL: http://127.0.0.1:8000/berichten/registreren/

Django Version: 1.4.3
Python Version: 2.7.2
Installed Applications:
('django.contrib.auth',
'django.contrib.contenttypes',


'django.contrib.sessions',
 'django.contrib.sites',
 'django.contrib.messages',
 'django.contrib.staticfiles',
 'south',
 'mm')
Installed Middleware:
('django.middleware.common.CommonMiddleware',
 'django.contrib.sessions.middleware.SessionMiddleware',
 'django.contrib.auth.middleware.AuthenticationMiddleware',
 'mm.middleware.LoginRequiredMiddleware',
 'django.middleware.csrf.CsrfViewMiddleware',
 'django.contrib.messages.middleware.MessageMiddleware')


Traceback:
File "/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/site-packages/django/core/handlers/base.py" in get_response
  111.                         response = callback(request, *callback_args, **callback_kwargs)
File "/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/site-packages/django/views/generic/base.py" in view
  48.             return self.dispatch(request, *args, **kwargs)
File "/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/site-packages/django/views/generic/base.py" in dispatch
  69.         return handler(request, *args, **kwargs)
File "/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/site-packages/django/views/generic/edit.py" in post
  172.         return super(BaseCreateView, self).post(request, *args, **kwargs)
File "/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/site-packages/django/views/generic/edit.py" in post
  137.         if form.is_valid():
File "/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/site-packages/django/forms/forms.py" in is_valid
  124.         return self.is_bound and not bool(self.errors)
File "/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/site-packages/django/forms/forms.py" in _get_errors
  115.             self.full_clean()
File "/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/site-packages/django/forms/forms.py" in full_clean
  272.         self._post_clean()
File "/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/site-packages/django/forms/models.py" in _post_clean
  309.         self.instance = construct_instance(self, self.instance, opts.fields, opts.exclude)
File "/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/site-packages/django/forms/models.py" in construct_instance
  51.             f.save_form_data(instance, cleaned_data[f.name])
File "/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/site-packages/django/db/models/fields/__init__.py" in save_form_data
  454.         setattr(instance, self.name, data)
File "/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/site-packages/django/db/models/fields/related.py" in __set__
  366.                                  self.field.name, self.field.rel.to._meta.object_name))

Exception Type: ValueError at /berichten/registreren/
Exception Value: Cannot assign "u''": "Bericht.beller" must be a "Beller" instance.

モデル.py

class Beller(models.Model):
    titel = models.CharField(max_length=10, blank=True)
    naam = models.CharField(max_length=30)
    voornaam = models.CharField(max_length=30)
    bedrijf = models.CharField(max_length=50, blank=True, null=True)
    adres = models.CharField(max_length=50)
    plaats = models.ForeignKey(Plaats, blank=True, null=True)
    telefoon = models.CharField(max_length=20, blank=True)
    email = models.EmailField(blank=True)
    taal = models.CharField(max_length=1, choices=TAAL)

    class Meta:
        ordering = ['naam', 'voornaam']

    def __unicode__(self):
        return u"{0} {1}".format(self.naam, self.voornaam)

class Bericht(models.Model):
    klant = models.ForeignKey(Klant)
    lijn = models.ForeignKey(Lijn)
    contact = models.ForeignKey(Contact)
    beller = models.ForeignKey(Beller)

    tijdstip = models.DateTimeField(auto_now_add=True)
    bericht = models.TextField(blank=True)
    status = models.CharField(max_length=1, choices=BERICHT_STATUS)
    gebruiker = models.ForeignKey(User)

フォーム.py

class BerichtForm(forms.ModelForm):
    lijn = forms.ModelChoiceField(queryset=Lijn.objects.filter(datum_tot__exact=None))
    contact_naam = forms.CharField(required=True, max_length=50)
    contact_pk = forms.CharField(required=True, widget=forms.HiddenInput())
    beller = forms.CharField(required=False, max_length=50, widget=forms.HiddenInput())
    titel = forms.CharField(required=False, max_length=10)
    naam = forms.CharField(required=True, max_length=50)
    voornaam = forms.CharField(required=False, max_length=50)
    bedrijf = forms.CharField(required=False, max_length=50)
    adres = forms.CharField(required=False)
    plaats_pk = forms.CharField(required=False, widget=forms.HiddenInput())
    plaats = forms.CharField(required=False, max_length=50)
    email = forms.EmailField(required=False)
    telefoon = forms.CharField(required=False)
    taal = forms.CharField(widget=forms.Select(choices=TAAL))

    class Meta:
        model = Bericht
        fields = ('lijn', 'contact_naam', 'beller', 'naam', 'titel', 'voornaam', 'bedrijf', 'adres', 'plaats', 'email', 'telefoon', 'taal', 'bericht',)

ビュー.py

class BerichtCreateView(CreateView):
    model = Bericht
    template_name = "mm/bericht/form.html"
    form_class = BerichtForm
    context_object_name = "bericht"
    success_url = reverse_lazy('mm-berichten-registreren')

    def get_context_data(self, **kwargs):
        context = super(BerichtCreateView, self).get_context_data(**kwargs)
        cb = self.request.GET.get('cb', None)
        if cb:
            context['cb'] = cb
        return context

    def get_success_url(self):
        if self.cb:
            return self.success_url + "?cb=" + self.cb
        else:
            return self.success_url

    def form_valid(self, form):
        """Valideer het formulier, maar voeg eerst de klant toe aan de instance """
        self.cb = None
        self.object = form.save(commit=False)
        self.object.klant = self.object.lijn.klant

        # Verwerk contact info
        contact_pk = form.cleaned_data['contact_pk']
        try:
            contact = int(contact_pk)
        except:
            contact = None
        if contact:
            self.object.contact = Contact.objects.get(pk=contact)
        else:
            self.object.contact = Contact()

        # Verwerk beller info
        beller = form.cleaned_data['beller']
        if beller:
            try:
                beller = Beller.objects.get(pk=beller)
            except Beller.DoesNotExist:
                beller = Beller()
        else:
            beller = Beller()

        beller.titel = form.cleaned_data['titel']
        beller.naam = form.cleaned_data['naam']
        beller.voornaam = form.cleaned_data['voornaam']
        beller.bedrijf = form.cleaned_data['bedrijf']
        beller.adres = form.cleaned_data['adres']
        if form.cleaned_data['plaats_pk']:
            beller.plaats = Plaats.objects.get(pk=form.cleaned_data['plaats_pk'])
        else:
            beller.plaats = None
        beller.email = form.cleaned_data['email']
        beller.telefoon = form.cleaned_data['telefoon']
        beller.taal = form.cleaned_data['taal']
        beller.save()
        #self.object.beller = beller
        self.object.gebruiker = self.request.user
        self.object.save()

        if self.request.POST.get('versturen', None):
            self.cb = None

            # Verwerk e-mail communicatie
            if self.object.contact.contact_medium == 'E':
                self.object.send_email()

                if self.object.status == "N":
                    messages.add_message(self.request, messages.WARNING, 'Het bericht kon niet via e-mail worden verstuurd.')
                else:
                    messages.add_message(self.request, messages.SUCCESS, 'Het bericht is verstuurd naar de contactpersoon.')

            else:
                # Add a callback for print to success url
                self.cb = reverse('mm-bericht-afdrukken', args=[self.object.id])
                self.object.status = 'P'

        else:
            self.object.status = 'D'
            messages.add_message(self.request, messages.INFO, 'Het bericht is opgeslagen maar is nog niet verstuurd.')

        self.object.save()

        return super(BerichtCreateView, self).form_valid(form)

ご覧のとおり、Beller() インスタンスを送信しようとしていますが、送信されません。

私を助けてくれてありがとう。

4

1 に答える 1

0

メソッドではなく、検証中にエラーが発生していますform_valid()bellerオブジェクトの " " フィールドへの文字列を検証しようとしていBerichtます。Django がこれを行っているのは、これがモデルと共に自動的に保存されるフィールドの 1 つであると言われているためです。

のメタ内のフィールドには、HTML から直接取得したデータを入力する にBerichtForm存在するフィールドのみを含めます。Bericht何かのようなもの:

class Meta:
    model = Bericht
    fields = ('lijn', 'tijdstip', 'bericht')

PS: ここで役立つ可能性があるもう 1 つの情報は、リクエストの POST 本文の内容です。

于 2013-03-01T00:16:06.740 に答える