Implement some HackerNews functions in the Python Django framework-Python tutorial

Source: Internet
Author: User
Tags install django pip install django
This article mainly introduces some features of HackerNews in the Python Django framework, including voting "top" comment and other features. For more information, see Step-by-step instructions

This is the video text version provided to those who prefer reading. We will create a social news website similar to Hacker News or Reddit. It will be called "steel rumors" as a place to share interesting stories about "Iron Man" and vote on it.

Overview of the first part of screen recording:

  • Target
  • Virtual environment-from scratch!
  • Model Management-dream work #78
  • Basic template
  • General view-News List View and News Details View
  • Paging-free !!


Set virtual environment

We will use virtualenv and virtualenvwrapper to establish a virtual development environment. First, confirm that you have installed them:

mkvirtualenv djangorocks

I used a Ubuntu system named Xubuntu in the screen recording. But you should be able to repeat these steps with minimal changes in other operating systems.

Install Django (make sure you have installed pip ):

  pip install Django==1.5

You can also use Django 1.5.1. these methods and code have not been tested in the latest Django version, so it is best to follow the version used in this tutorial.

Create projects and applications

Create a project named steelrumors:

The code is as follows:


Cd ~ /Projects
Django-admin.py startproject steelrumors
Cd steelrumors
Chmod + x manage. py

Open the steelrumors/settings. py file in your favorite editor. Locate and change the following content (changed in bold ):

The code is as follows:

'Engine': 'Django. db. backends. sqlite3'
'Name': 'database. db ',


Last INSTALLED_APPS = ('Django. contrib. admin ',

Next, modify steelrumors/urls. py to cancel the comments of the following lines:

from django.contrib import admin  admin.autodiscover()     urlpatterns = patterns('',    url(r'^admin/', include(admin.site.urls)),  )

Create Management objects synchronously and go to management details:

 ./manage.py syncdb

Open a new tag or a new terminal and keep the server instance running (do not forget to publish a workable djangorocks on this terminal ):

  ./manage.py runserver

Access the management page (generally http: // 127.0.0.1: 8000/admin/) and log on.

Create a linked application:

  ./manage.py startapp links

Enter the following two model classes in the links/models. py file:

 from django.db import models  from django.contrib.auth.models import User     class Link(models.Model):    title = models.CharField("Headline", max_length=100)    submitter = models.ForeignKey(User)    submitted_on = models.DateTimeField(auto_now_add=True)    rank_score = models.FloatField(default=0.0)    url = models.URLField("URL", max_length=250, blank=True)    description = models.TextField(blank=True)       def __unicode__(self):      return self.title     class Vote(models.Model):    voter = models.ForeignKey(User)    link = models.ForeignKey(Link)       def __unicode__(self):      return "%s upvoted %s" % (self.voter.username, self.link.title)

Create a management class. Enter the following content in links/admin. py:

 from django.contrib import admin  from .models import Link, Vote     class LinkAdmin(admin.ModelAdmin): pass  admin.site.register(Link, LinkAdmin)     class VoteAdmin(admin.ModelAdmin): pass  admin.site.register(Vote, VoteAdmin)

Enter the following content to links/views. py:

 from django.views.generic import ListView  from .models import Link, Vote     class LinkListView(ListView):    model = Link  Insert following lines intosteelrumor/urls.py:   from links.views import LinkListView  ...  urlpatterns = patterns('',    url(r'^$', LinkListView.as_view(), name='home'),

Create a new template folder and enter the following content in steelrumors/templates/links/link_list.html:

 
 
    {% for link in object_list %}
  1. {{ link.title }}
  2. {% endfor %}

Edit settings. py and add your two applications to the end of INSTALLED_APPS =:

  'links',  'steelrumors',  )

Create a link object synchronously and enter some data in the management interface:

  ./manage.py syncdb

Add brand

Create a general basic template steelrumors/templates/base.html:

     Steel Rumors     {% block content %}  {% endblock %}       

Modify steelrumors/templates/links/link_list.html to wrap the original code in this way:

   {% extends "base.html" %}     {% block content %}  ...  {% endblock %}

Voting number model manager

We need to add a count in our general ListView. Add these to links/models. py:

  from django.db.models import Count     class LinkVoteCountManager(models.Manager):    def get_query_set(self):      return super(LinkVoteCountManager, self).get_query_set().annotate(        votes=Count('vote')).order_by('-votes')  Insert these two lines into the Link class inlinks/models.py:   class Link(models.Model):  ...       with_votes = LinkVoteCountManager()    objects = models.Manager() #default manager

Edit links/views. py and add the two rows to the LinkListView class:

 class LinkListView(ListView):  ...       queryset = Link.with_votes.all()    paginate_by = 3

Carnival (cheating)

You can use the following line in django shell to add 100 votes to a random Title:

$ ./manage.py shell>>> from links.models import Link>>> for i in xrange(100): Vote(link=Link.objects.order_by('?')[0],voter=a).save()

Final comment

Maybe you want to know if this version of this website is useful. I 'd like to say that it works well as a private beta version. Any new user must be manually added on the management interface. If you want them to log on to the management interface, they must be employees. Employees can manually create voting objects to vote.

The public part of the site still shows rumors of the highest voter turnout among employees. Based on the question of how to design a template, this version can also be used to obtain feedback on the website design and brand.

Summarize the first part. If you want to get some updates later, please add me one @ arocks on Twitter.

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.