0

Mysql:

DATABASES = {
    'default': {
        'NAME': 'ch01',
        'ENGINE': 'mysql.connector.django',
        'HOST':'172.17.100.18',
        'USER': 'test',
        'PASSWORD': '123456',
        'OPTIONS': {
          'autocommit': True,
        },
    }
}

sqlite:

DATABASES = {
    'default': {
        'ENGINE': 'django.db.backends.sqlite3',
        'NAME': os.path.join(BASE_DIR, 'db.sqlite3'),
    }
}

blog/urls.py:

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

urlpatterns = [
    #url(r'^$', views.post_list, name='post_list'),
    url(r'^$', views.PostListView.as_view(), name='post_list'),
    url(r'^(?P<year>\d{4})/(?P<month>\d{2})/(?P<day>\d{2})/(?P<post>[-\w]+)/$',
        views.post_detail,
        name='post_detail'),
]

When I run server with second database settings project works fine, but when I run first settings file with mysql, django returns 404 error for all urls.

views a blog application:

from .models import Post
import logging

def post_list(request):
    object_list = Post.published.all()
    paginator = Paginator(object_list, 3) # 3 posts in each page
    page = request.GET.get('page')
    try:
        posts = paginator.page(page)
    except PageNotAnInteger:
        # If page is not an integer deliver the first page
        posts = paginator.page(1)
    except EmptyPage:
        # If page is out of range deliver last page of results
        posts = paginator.page(paginator.num_pages)
    #logging.console(page)
    return render(request, 'blog/post/list.html', {'posts': posts})

class PostListView(ListView):
    queryset = Post.published.all()
    context_object_name = 'posts'
    paginate_by = 4
    template_name = 'blog/post/list.html'

def post_detail(request, year, month, day, post):
    post = get_object_or_404(Post, slug=post, status='published',
                             publish__year=year, publish__month=month,
                             publish__day=day)
    return render(request, 'blog/post/detail.html', {'post': post})

Data in mysql:

+----+-------+-------+------+---------------------+---------------------+---------------------+-----------+-----------+
| id | title | slug  | body | publish             | created             | updated             | status    | author_id |
+----+-------+-------+------+---------------------+---------------------+---------------------+-----------+-----------+
|  1 | Test1 | test1 | ??   | 2016-10-24 03:46:04 | 2016-10-24 03:46:16 | 2016-10-24 03:46:16 | published |         1 |
+----+-------+-------+------+---------------------+---------------------+---------------------+-----------+-----------+

Error info:

Page not found (404) Request Method: GET Request URL: http://172.17.100.19/blog/2016/10/24/test1/ Raised by: blog.views.post_detail

No Post matches the given query.

You're seeing this error because you have DEBUG = True in your Django settings file. Change that to False, and Django will display a standard 404 page.

models.py

from django.contrib.auth.models import User
from django.core.urlresolvers import reverse


class PublishedManager(models.Manager):

    def get_queryset(self):
        return super(PublishedManager, self).get_queryset()\
                .filter(status='published')

class Post(models.Model):
    STATUS_CHOICES = (
            ('draft', 'Draft'),
            ('published', 'Published'),
            )
    title = models.CharField(max_length=250)
    slug = models.SlugField(max_length=250, unique_for_date="publish")
    author = models.ForeignKey(User, related_name='blog_posts')
    body = models.TextField()
    publish = models.DateTimeField(default=timezone.now)
    created = models.DateTimeField(auto_now_add=True)
    updated = models.DateTimeField(auto_now=True)
    status = models.CharField(max_length=10, choices=STATUS_CHOICES, default="draft")

    objects = models.Manager()
    published = PublishedManager()


    class Meta:
        ordering = ('-publish', )

    def __str__(self):
        return self.title

    def get_absolute_url(self):
        return reverse('blog:post_detail', args=[self.publish.year,
            self.publish.strftime('%m'),
            self.publish.strftime('%d'),
            self.slug])
user2106796
  • 51
  • 1
  • 1
  • 6

1 Answers1

1

USE_TZ = False, Everything is ok.

When USE_TZ = True it stores the time based on time zone specified in settings.py i.e if TIME_ZONE = 'UTC' it stores in UTC and while displaying it templates it will be in local zone.

The reason for error 404 is the date in URL is not matching with right date due to timezone settings.To avoid this you can set USE_TZ = False

refer: Difference between USE_TZ = False and USE_TZ = True

Chandan
  • 704
  • 7
  • 20
user2106796
  • 51
  • 1
  • 1
  • 6