Как исправить TypeError __str__ вернул не-строку - PullRequest
0 голосов
/ 07 марта 2020

Мой код все равно выдает ошибку __str__ returned non-string (type Contact), несмотря на то, что я произвел инструкцию return с помощью str ()

Моя модель:

class Contact(models.Model):
    name = models.CharField("Contact Name", max_length=50)
    surname = models.CharField("Contact Surname", max_length=50)
    company = models.ForeignKey(Customer, verbose_name='Company',on_delete=models.CASCADE)
    department = models.ForeignKey(Department, verbose_name='Department',on_delete=models.CASCADE)
    position = models.CharField("Position", max_length=50, null=True, blank=True)
    birthday = models.DateField("Birthday", null=True, blank=True)
    remarks = models.TextField("Remarks", max_length=500, null=True, blank=True)
    skype = models.CharField("Spype", max_length=50, null=True, blank=True)

    def clean(self):
        for field in self._meta.fields:
            if isinstance(field, (models.CharField, models.TextField)) and getattr(self, field.name)!=None:
                setattr(self, field.name, getattr(self, field.name).strip())

    class Meta:
        verbose_name = "Contact"
    #####Overide save method to store names and surnames in caps
    def save(self, *args, **kwargs):
        for attr_name in ['name', 'surname', 'position']:
            val = getattr(self, attr_name, False)
        if val:
            setattr(self, attr_name, val.upper())
        super(Contact, self).save(*args, **kwargs)

    def __str__(self):
            return self.surname + " " + self.name

Я также писал функция str выглядит следующим образом:

def __str__(self):
                return str(self.surname + " " + self.name)

, но все равно код возвращает ту же ошибку.

Вот мой traceback

Django Version: 2.2.6
Python Version: 3.5.2
Installed Applications:
('django.contrib.auth',
 'django.contrib.contenttypes',
 'django.contrib.sessions',
 'django.contrib.sites',
 'django.contrib.messages',
 'django.contrib.staticfiles',
 'django.contrib.humanize',
 'adminactions',
 'django.contrib.admin',
 'intranet',
 'daterange_filter',
 'gunicorn',
 'notifications')
Installed Middleware:
('whitenoise.middleware.WhiteNoiseMiddleware',
 'django.middleware.security.SecurityMiddleware',
 'django.contrib.sessions.middleware.SessionMiddleware',
 'django.middleware.common.CommonMiddleware',
 'django.middleware.csrf.CsrfViewMiddleware',
 'django.contrib.auth.middleware.AuthenticationMiddleware',
 'django.contrib.messages.middleware.MessageMiddleware',
 'django.middleware.clickjacking.XFrameOptionsMiddleware')


Template error:
In template /usr/local/lib/python3.5/dist-packages/django/contrib/admin/templates/admin/edit_inline/tabular.html, error at line 33
   __str__ returned non-string (type Contact)
   23 :      <tbody>
   24 :      {% for inline_admin_form in inline_admin_formset %}
   25 :         {% if inline_admin_form.form.non_field_errors %}
   26 :         <tr><td colspan="{{ inline_admin_form|cell_count }}">{{ inline_admin_form.form.non_field_errors }}</td></tr>
   27 :         {% endif %}
   28 :         <tr class="form-row {% cycle "row1" "row2" %} {% if inline_admin_form.original or inline_admin_form.show_url %}has_original{% endif %}{% if forloop.last and inline_admin_formset.has_add_permission %} empty-form{% endif %}"
   29 :              id="{{ inline_admin_formset.formset.prefix }}-{% if not forloop.last %}{{ forloop.counter0 }}{% else %}empty{% endif %}">
   30 :         <td class="original">
   31 :           {% if inline_admin_form.original or inline_admin_form.show_url %}<p>
   32 :           {% if inline_admin_form.original %}
   33 :            {{ inline_admin_form.original }} 
   34 :           {% if inline_admin_form.model_admin.show_change_link and inline_admin_form.model_admin.has_registered_model %}<a href="{% url inline_admin_form.model_admin.opts|admin_urlname:'change' inline_admin_form.original.pk|admin_urlquote %}" class="{% if inline_admin_formset.has_change_permission %}inlinechangelink{% else %}inlineviewlink{% endif %}">{% if inline_admin_formset.has_change_permission %}{% trans "Change" %}{% else %}{% trans "View" %}{% endif %}</a>{% endif %}
   35 :           {% endif %}
   36 :           {% if inline_admin_form.show_url %}<a href="{{ inline_admin_form.absolute_url }}">{% trans "View on site" %}</a>{% endif %}
   37 :             </p>{% endif %}
   38 :           {% if inline_admin_form.needs_explicit_pk_field %}{{ inline_admin_form.pk_field.field }}{% endif %}
   39 :           {% if inline_admin_form.fk_field %}{{ inline_admin_form.fk_field.field }}{% endif %}
   40 :           {% spaceless %}
   41 :           {% for fieldset in inline_admin_form %}
   42 :             {% for line in fieldset %}
   43 :               {% for field in line %}


Traceback:

File "/usr/local/lib/python3.5/dist-packages/django/core/handlers/exception.py" in inner
  34.             response = get_response(request)

File "/usr/local/lib/python3.5/dist-packages/django/core/handlers/base.py" in _get_response
  145.                 response = self.process_exception_by_middleware(e, request)

File "/usr/local/lib/python3.5/dist-packages/django/core/handlers/base.py" in _get_response
  143.                 response = response.render()

File "/usr/local/lib/python3.5/dist-packages/django/template/response.py" in render
  106.             self.content = self.rendered_content

File "/usr/local/lib/python3.5/dist-packages/django/template/response.py" in rendered_content
  83.         content = template.render(context, self._request)

File "/usr/local/lib/python3.5/dist-packages/django/template/backends/django.py" in render
  61.             return self.template.render(context)

File "/usr/local/lib/python3.5/dist-packages/django/template/base.py" in render
  171.                     return self._render(context)

File "/usr/local/lib/python3.5/dist-packages/django/template/base.py" in _render
  163.         return self.nodelist.render(context)

File "/usr/local/lib/python3.5/dist-packages/django/template/base.py" in render
  937.                 bit = node.render_annotated(context)

File "/usr/local/lib/python3.5/dist-packages/django/template/base.py" in render_annotated
  904.             return self.render(context)

File "/usr/local/lib/python3.5/dist-packages/django/template/loader_tags.py" in render
  150.             return compiled_parent._render(context)

File "/usr/local/lib/python3.5/dist-packages/django/template/base.py" in _render
  163.         return self.nodelist.render(context)

File "/usr/local/lib/python3.5/dist-packages/django/template/base.py" in render
  937.                 bit = node.render_annotated(context)

File "/usr/local/lib/python3.5/dist-packages/django/template/base.py" in render_annotated
  904.             return self.render(context)

File "/usr/local/lib/python3.5/dist-packages/django/template/loader_tags.py" in render
  150.             return compiled_parent._render(context)

File "/usr/local/lib/python3.5/dist-packages/django/template/base.py" in _render
  163.         return self.nodelist.render(context)

File "/usr/local/lib/python3.5/dist-packages/django/template/base.py" in render
  937.                 bit = node.render_annotated(context)

File "/usr/local/lib/python3.5/dist-packages/django/template/base.py" in render_annotated
  904.             return self.render(context)

File "/usr/local/lib/python3.5/dist-packages/django/template/loader_tags.py" in render
  62.                 result = block.nodelist.render(context)

File "/usr/local/lib/python3.5/dist-packages/django/template/base.py" in render
  937.                 bit = node.render_annotated(context)

File "/usr/local/lib/python3.5/dist-packages/django/template/base.py" in render_annotated
  904.             return self.render(context)

File "/usr/local/lib/python3.5/dist-packages/django/template/loader_tags.py" in render
  62.                 result = block.nodelist.render(context)

File "/usr/local/lib/python3.5/dist-packages/django/template/base.py" in render
  937.                 bit = node.render_annotated(context)

File "/usr/local/lib/python3.5/dist-packages/django/template/base.py" in render_annotated
  904.             return self.render(context)

File "/usr/local/lib/python3.5/dist-packages/django/template/defaulttags.py" in render
  209.                     nodelist.append(node.render_annotated(context))

File "/usr/local/lib/python3.5/dist-packages/django/template/base.py" in render_annotated
  904.             return self.render(context)

File "/usr/local/lib/python3.5/dist-packages/django/template/loader_tags.py" in render
  188.             return template.render(context)

File "/usr/local/lib/python3.5/dist-packages/django/template/base.py" in render
  173.                 return self._render(context)

File "/usr/local/lib/python3.5/dist-packages/django/template/base.py" in _render
  163.         return self.nodelist.render(context)

File "/usr/local/lib/python3.5/dist-packages/django/template/base.py" in render
  937.                 bit = node.render_annotated(context)

File "/usr/local/lib/python3.5/dist-packages/django/template/base.py" in render_annotated
  904.             return self.render(context)

File "/usr/local/lib/python3.5/dist-packages/django/template/defaulttags.py" in render
  209.                     nodelist.append(node.render_annotated(context))

File "/usr/local/lib/python3.5/dist-packages/django/template/base.py" in render_annotated
  904.             return self.render(context)

File "/usr/local/lib/python3.5/dist-packages/django/template/defaulttags.py" in render
  309.                 return nodelist.render(context)

File "/usr/local/lib/python3.5/dist-packages/django/template/base.py" in render
  937.                 bit = node.render_annotated(context)

File "/usr/local/lib/python3.5/dist-packages/django/template/base.py" in render_annotated
  904.             return self.render(context)

File "/usr/local/lib/python3.5/dist-packages/django/template/defaulttags.py" in render
  309.                 return nodelist.render(context)

File "/usr/local/lib/python3.5/dist-packages/django/template/base.py" in render
  937.                 bit = node.render_annotated(context)

File "/usr/local/lib/python3.5/dist-packages/django/template/base.py" in render_annotated
  904.             return self.render(context)

File "/usr/local/lib/python3.5/dist-packages/django/template/base.py" in render
  993.         return render_value_in_context(output, context)

File "/usr/local/lib/python3.5/dist-packages/django/template/base.py" in render_value_in_context
  972.             value = str(value)

Exception Type: TypeError at /private/intranet/contact/742/change/
Exception Value: __str__ returned non-string (type Contact)

my view

@staff_member_required#login is required
def contact_view(request, intranet_contact_id):
    contact = Contact.objects.get(id = intranet_contact_id)
    emails = Contact_email.objects.filter(contact_name = intranet_contact_id)
    phones = Contact_Phone.objects.filter(contact_name = intranet_contact_id)
    other_company_contacts = Contact.objects.filter(company = contact.company.id).exclude(pk= intranet_contact_id)

    return render(request,'contact/details.html', dict(contact = contact, emails = emails, phones = phones, other_company_contacts = other_company_contacts))

admin.py

class ContactAdmin(ReadPermissionModelAdmin):
    list_display = ['show_name', 'company', 'department', 'position', 'show_details','skype']
    list_filter = ['company']
    search_fields = ('surname', 'name', 'company__customer_name','skype')
    inlines = [Contact_PhoneInline, Contact_emailInline]
    #alphabet_filter = 'remarks'
    #DEFAULT_ALPHABET = u'T'

    formfield_overrides = {
            models.CharField: {'widget': TextInput(attrs={'size':'25'})},
            models.BigIntegerField: {'widget': TextInput(attrs={'size':'25'})},
            models.TextField: {'widget': Textarea(attrs={'rows':6, 'cols':40})},
        }

    fieldsets = (
        (None, {
            'fields': (('name', 'surname'), ('company', 'department'), ('position', 'birthday'), ('skype'), ('remarks'),)
            }),
        )

    list_per_page = 20

    def response_change(self, request, obj, post_url_continue=None):
    #This makes the response go to contact full detail page for an edited order
            return HttpResponseRedirect(reverse('contacts', args=(obj.id,)))
            #return HttpResponseRedirect("../../contacts/%s/" % obj.id)


    def response_add(self, request, obj, post_url_continue=None):
    #This makes the response go to contact full detail page for a newlly added order to inquiry list
            return HttpResponseRedirect(reverse('contacts', args=(obj.id,)))
            #return HttpResponseRedirect("../../contacts/%s/" % obj.id)
    def show_name(self, obj):
        return obj
    show_name.short_description = 'Name'
    show_name.admin_order_field = 'surname'

    def show_details(self, obj):
        #sos
        #return '<a href="/private/intranet/contacts/%s/">Details</a>' % (obj.id)
        return format_html('<a href="/private/intranet/contacts/{}/">Details</a>',str(obj.id))
    show_details.allow_tags = True
    show_details.short_description = 'Details'

admin.site.register(Contact, ContactAdmin)

Как с этим справиться?

Ответы [ 2 ]

0 голосов
/ 07 марта 2020

Поддержка была очень полезной.

Наконец-то я нашел решение.

Произошла ошибка, потому что str функции встроенных классов, связанных с Контактом модель была ложной.

0 голосов
/ 07 марта 2020

Попробуйте изменить функцию show_name на:

def show_name(self, obj):
    return obj.__str__()
show_name.short_description = 'Name'
show_name.admin_order_field = 'surname'

Быстрый тест, который я сделал, кажется, показывает, что, хотя можно ожидать, что связанный объект через внешний ключ отобразит их str хорошо, сам экземпляр, кажется, ломается, когда я пытаюсь либо передать объект обратно.

Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...