Rakesh K
Rakesh K

Reputation: 8515

Unable to retrieve data in django

I am writing a weblog application in django. As part of this, I have a view function that fetches an object from the database corresponding to a single blog post. The field that I am using to query the database is the published date (pub_date) which is of type DateTime (Python). I have a MySQL database and the type of the column for this field is datetime. But I am not able to fetch the object from the database though I am passing the correct date attributes. I am getting a 404 error.The following is my view function:

def entry_detail(request,year,month,day,slug):
    import datetime,time
    date_stamp =  time.strptime(year+month+day,"%Y%b%d")
    pub_date = datetime.date(*date_stamp[:3])
    entry = get_object_or_404(Entry,pub_date__year=pub_date.year,pub_date__month=pub_date.month,pub_date__day=pub_date.day,slug=slug)
    return render_to_response('coltrane/entry_detail.html',{'entry':entry})

The following is the URL of the individual post that I want to fetch:

http://127.0.0.1:8000/weblog/2014/oct/28/third-post/

And this is how the pub_date column value for the third-post in the database looks like:

 2014-10-28 13:26:39

The following is the URL pattern:

url(r'^weblog/(?P<year>\d{4})/(?P<month>\w{3})/(?P<day>\d{2})/(?P<slug>[-\w]+)/$','coltrane.views.entry_detail'),

Upvotes: 0

Views: 147

Answers (1)

Daniel Roseman
Daniel Roseman

Reputation: 600051

You're doing some odd things here: you're converting to a time, then converting that to a datetime.date, then extracting the year, month and day as integers and passing them to the query. You could bypass almost the whole process: the only thing you need is to convert the month, the other parameters can be passed directly:

month_no = datetime.datetime.strptime(month, '%b').month
entry = get_object_or_404(Entry, pub_date__year=year, pub_date__month=month_no, pub_date__day=day, slug=slug)

Upvotes: 1

Related Questions