M
M
Maxim Shelkov2020-04-24 18:42:42
Django
Maxim Shelkov, 2020-04-24 18:42:42

Can only concatenate str (not "NoneType") to str in Django, what's wrong?

Views code
from django.shortcuts import render
from django.http import HttpResponse

from .models import Board
# Create your views here.
def index(request):
    s = 'СМР Блог\r\n\r\n\r\n'
    for b in Board.objects.order_by('-published'):
        s += b.title + '\r\n' + b.content + '\r\n'
        return HttpResponse(s, content_type = 'text/plain; charset = utf-8')

Urls code
from django.urls import path

from .views import index

urlpatterns = [
    path('board/', index)#, name = 'index')
]

Code Models
from django.db import models

# Create your models here.
class Board(models.Model):
    title = models.CharField(max_length = 120)
    content = models.TextField(max_length = 6000)
    published = models.DateTimeField(auto_now_add = True, db_index = True)

Mistake
TypeError: can only concatenate str (not "NoneType") to str

What is the problem? Be grateful for the answers

Answer the question

In order to leave comments, you need to log in

2 answer(s)
G
galaxy, 2020-04-24
@galaxy

Does the database have boards whose title or content is null?

V
Vladimir, 2020-04-24
@Realmixer

Traceback probably told everything. Most likely there is a problem: In b.title or in b.content instead of the string None. Use f-strings:
s += b.title + '\r\n' + b.content + '\r\n'
s += f'{b.title}\r\n{b.content}\r\n'

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question