1

Very new to Django, so I apologize as I'm sure this has an easy answer.

I have a PHP background, and so I guessing that I am trying to force a structure I am used to, and not one that is native in Django.

Here is my Project's urls.py

from django.conf.urls import patterns, include, url

from django.contrib import admin
admin.autodiscover()

urlpatterns = patterns('',
    url(r'^admin/', include(admin.site.urls)),
    url(r'^', include('pm.urls', namespace='pm')),
)

Here is my App's urls.py

from django.conf.urls import patterns, url
from pm import views

urlpatterns = patterns('',
    url(r'^$', views.index, name='index'),
    url(r'^label/add/$', views.add_label, name='label_add'),
)

I am doing an AJAX Post request to /label/add/, but it's coming back with a 500 error.

This is the views.py:

from django.shortcuts import render
from pm.models import Label
import json

# Create your views here.
def index(request):
    labels_list = Label.objects.order_by('name')
    return render(request, 'pm/index.html', {
        'labels' : labels_list
    })


""" Labels """
def add_label(request):
    if request.is_ajax():
        response = {
            'success': True
       }
    else:
        response = {
            'success': False,
            'error': "Invalid request"
        }

    return json.dumps(response)

Any advise or references would be great.


UPDATE

Here's the first couple of lines from the traceback I am getting:

AttributeError at /label/add/
'str' object has no attribute 'get'
Kerry Jones
  • 21,806
  • 12
  • 62
  • 89
  • 1
    put `DEBUG = True` to your settings and then check the response for your ajax request with Firebug or similar tool to see the full traceback of the error. I think the problem is that you've to return `HttpResponse`, not just serialized json. – yedpodtrzitko Jun 04 '14 at 18:12
  • yup, you've the problem I described - your `view` returns just string, but you have to return `HttpResponse` object – yedpodtrzitko Jun 04 '14 at 18:18
  • I want to return just serialized JSON, how do I make that happen? – Kerry Jones Jun 04 '14 at 18:19
  • 1
    idk, probably something like `return HttpReponse(json.dumps(response),mimetype='application/json')` – yedpodtrzitko Jun 04 '14 at 18:20
  • Thank you -- if you put that as the answer, I will accept it. – Kerry Jones Jun 04 '14 at 18:21
  • I referenced this: http://stackoverflow.com/questions/2428092/creating-a-json-response-using-django-and-python – Kerry Jones Jun 04 '14 at 18:22

1 Answers1

5

you have to return HttpResponse instead of string:

return HttpReponse(json.dumps(response), content_type='application/json')
Kerry Jones
  • 21,806
  • 12
  • 62
  • 89
yedpodtrzitko
  • 9,035
  • 2
  • 40
  • 42