ni8mr
ni8mr

Reputation: 1785

Server Error (500) in accessing a section in Django app

I am following Writing your first Django app, part 3 from Django official documentation.

At one part of the tutorial, i have edited polls/urls.py file like this:

from django.conf.urls import url


from polls import views

urlpatterns = [

     url(r'^$', views.index, name='index'),

     url(r'^(?P<question_id>[0-9]+)/$', views.detail, name='detail'),

     url(r'^(?P<question_id>[0-9]+)/results/$', views.results, name='results'),

     url(r'^(?P<question_id>[0-9]+)/vote/$', views.vote, name='vote'),
     ]

Now for accessing the results section, i have gone into this link:

http://localhost:8000/polls/34/results/

But it is showing Server Error (500)

N.B: Other sections like:

http://localhost:8000/polls/34/
http://localhost:8000/polls/34/vote/

are working well.

I have guessed there may be syntax errors in my code. But i couldn't find any.

EDIT:

Here is my polls directory:

polls/

   admin.py

   __init__.py

  models.py

  tests.py

  urls.py

  views.py    

EDIT 2:

models.py:

 mport datetime

 from django.db import models
 from django.utils import timezone

 # Create your models here.
 class Question(models.Model):
     question_text = models.CharField(max_length=200)
     pub_date = models.DateTimeField('date published')

 def __unicode__(self):
     return u'%s' % (self.question_text)

 def was_published_recently(self):
     return self.pub_date >= timezone.now()-datetime.timedelta(days=1)
     was_published_recently.admin_order_field = "pub_date"
     was_published_recently.boolean = True
     was_published_recently.short_description = "Published recently?"

 class Choice(models.Model):
     question = models.ForeignKey(Question)
     choice_text = models.CharField(max_length=200)
     votes = models.IntegerField(default=0)

 def __unicode__(self):
     return u'%s' % (self.choice_text)

views.py:

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

# Create your views here.

def index(request):
    return HttpResponse("Hello, world. You're at the polls index.")

def detail(request, question_id):
    return HttpResponse("You're looking at question %s." % question_id)

def results(request, question_id):
    response = "You're looking at the results of question %s."
    return HttpRespones(response % question_id)

def vote(request, question_id):
    return HttpResponse("You're voting on question %s." % question_id)

admin.py:

from django.contrib import admin
from polls.models import Choice, Question

# Register your models here.
class ChoiceInline(admin.TabularInline):
    model = Choice
    extra = 3

class QuestionAdmin(admin.ModelAdmin):
    fieldsets= [
     (None, {'fields': ['question_text']}),
     ('Date information', {'fields':['pub_date'], 
                          'classes': ['collapse']}),
     ]
    inlines = [ChoiceInline]
    list_display = ('question_text', 'pub_date', 
    'was_published_recently')
    list_filter = ['pub_date']
    search_fields = ['question_text']

    admin.site.register(Question, QuestionAdmin)

mysite/setting.py:

   # Build paths inside the project like this: os.path.join(BASE_DIR, ...)
import os
BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))


# Quick-start development settings - unsuitable for production
# See https://docs.djangoproject.com/en/dev/howto/deployment/checklist/

# SECURITY WARNING: keep the secret key used in production secret!
SECRET_KEY = '_bl4&0u5ph5=1l**)*8nbgta-sakxt@z8rd$fwj=abt4frj5#6'

# SECURITY WARNING: don't run with debug turned on in production!
DEBUG = False

TEMPLATE_DEBUG = True

ALLOWED_HOSTS = ['localhost']


# Application definition

INSTALLED_APPS = (
    'django.contrib.admin',
    'django.contrib.auth',
    'django.contrib.contenttypes',
    'django.contrib.sessions',
    'django.contrib.messages',
    'django.contrib.staticfiles',
    'polls',
)

MIDDLEWARE_CLASSES = (
    'django.contrib.sessions.middleware.SessionMiddleware',
    'django.middleware.common.CommonMiddleware',
    'django.middleware.csrf.CsrfViewMiddleware',
    'django.contrib.auth.middleware.AuthenticationMiddleware',
    'django.contrib.auth.middleware.SessionAuthenticationMiddleware',
    'django.contrib.messages.middleware.MessageMiddleware',
    'django.middleware.clickjacking.XFrameOptionsMiddleware',
    'django.middleware.security.SecurityMiddleware',
)

ROOT_URLCONF = 'mysite.urls'

WSGI_APPLICATION = 'mysite.wsgi.application'


# Database
# https://docs.djangoproject.com/en/dev/ref/settings/#databases

DATABASES = {
    'default': {
        'ENGINE': 'django.db.backends.mysql',
        'NAME': 'mydatabase',
        'USER': 'root',
        'PASSWORD': '',
        'HOST': 'localhost',
        'PORT': '5432',
    }
}

# Internationalization
# https://docs.djangoproject.com/en/dev/topics/i18n/

LANGUAGE_CODE = 'en-us'

TIME_ZONE = 'Asia/Dhaka'

USE_I18N = True

USE_L10N = True

USE_TZ = True

TEMPLATE_DIRS = [os.path.join(BASE_DIR, 'templates')]

# Static files (CSS, JavaScript, Images)
# https://docs.djangoproject.com/en/dev/howto/static-files/

STATIC_URL = '/static/'

Upvotes: 0

Views: 3413

Answers (2)

feasel0
feasel0

Reputation: 317

You set DEBUG to False in settings.py but you didn't change the ALLOWED_HOSTS variable to include your domain name. As a security measure, whenever you've turned off debugging you must explicitly state which domain name(s) the app is allowed to be called from.

ALLOWED_HOSTS = ['yourdomainname.com']

Upvotes: 0

xnx
xnx

Reputation: 25518

Just a small bug, but if this fixed it I'll take the answer :) : You have return HttpRespones instead of return HttpResponse in the buggy method. By the way, if you're using a "live" server instead of the Django toy one, you should see a SyntaxError in the logs, e.g. at /var/log/apache2/error_log on a Mac.

Upvotes: 1

Related Questions