cristhiam
cristhiam

Reputation: 506

How to fix 'str' object is not a mapping error

I will start saying its't a duplicated question. My problem is a little different in an url with Django 2.2.

An view triggers 'str' object is not a mapping error when return HttpResponseRedirect to another view in same application.

I really don't know what's wrong. I use same method in other application in same project and it works.

Project urls.py

urlpatterns = [
    url(r'^$', Home.as_view()),
    path('dashboard/', include('dashboard.urls')),
    path('main/', include('main.urls'))
]

Application urls.py

urlpatterns = [
  path('', views.Section.as_view(), name='main-form')
]

Application views.py

class Home(View):
  def get(self, request):
    return render(request, 'index.html', context={})

  def post(self, request):
    return HttpResponseRedirect(reverse('main-form'))


class Section(View):

  def get(self, request):
    return HttpResponse("Test Ok")

After post home form it should redirect to main-form view (Section view class) but I get error.

It triggers same error if I use the url in a template url {% url 'main-form' %}

If I navigate manually to view from address bar, view renders fine.

Whats wrong?

Upvotes: 8

Views: 17891

Answers (2)

boatcoder
boatcoder

Reputation: 18107

You probably wrote a URL pattern like this:

path('register-sms/', GetPhoneNumberView.as_view(), 'register-sms'),

Instead of like this:

path('register-sms/', GetPhoneNumberView.as_view(), name='register-sms'),

name is a keyword argument, if you leave it out, that string becomes the value for kwargs and you get this error. Simple fix if you know what to look for.

Upvotes: 18

Okayjosh
Okayjosh

Reputation: 31

Try to include an app name for your django app urls.py file like

app_name ='smth'

urlpatterns = [
  path('', views.Section.as_view(), name='main-form')
]

Then in your template view file include: href={% url 'smth:main-form' %}

Upvotes: 3

Related Questions