diff options
author | Evgeny Fadeev <evgeny.fadeev@gmail.com> | 2009-07-10 19:11:34 -0400 |
---|---|---|
committer | Evgeny Fadeev <evgeny.fadeev@gmail.com> | 2009-07-10 19:11:34 -0400 |
commit | bb801f2bbd9f26bebca846b71e8947a1951f86a5 (patch) | |
tree | cd4f7417cdbabc6834aeb45f73f09208a738ac2d /forum | |
parent | d3b7efc1eba6f38fba8d5110c7155f477d1459e6 (diff) | |
download | askbot-bb801f2bbd9f26bebca846b71e8947a1951f86a5.tar.gz askbot-bb801f2bbd9f26bebca846b71e8947a1951f86a5.tar.bz2 askbot-bb801f2bbd9f26bebca846b71e8947a1951f86a5.zip |
english translation
Diffstat (limited to 'forum')
-rw-r--r-- | forum/const.py | 74 | ||||
-rw-r--r-- | forum/feed.py | 12 | ||||
-rw-r--r-- | forum/forms.py | 87 | ||||
-rw-r--r-- | forum/management/commands/once_award_badges.py | 37 | ||||
-rw-r--r-- | forum/managers.py | 55 | ||||
-rw-r--r-- | forum/models.py | 12 | ||||
-rw-r--r-- | forum/templatetags/extra_tags.py | 72 | ||||
-rw-r--r-- | forum/user.py | 43 | ||||
-rw-r--r-- | forum/views.py | 143 |
9 files changed, 236 insertions, 299 deletions
diff --git a/forum/const.py b/forum/const.py index d285de7d..f6649cc4 100644 --- a/forum/const.py +++ b/forum/const.py @@ -1,18 +1,19 @@ -# encoding:utf-8 +# encoding:utf-8 +from django.utils.translation import ugettext as _ """ All constants could be used in other modules For reasons that models, views can't have unicode text in this project, all unicode text go here. """ CLOSE_REASONS = ( - (1, u'完全重复的问题'), - (2, u'不是编程技术问题'), - (3, u'太主观性、引起争吵的问题'), - (4, u'不是一个可以回答的“问题”'), - (5, u'问题已经解决,已得到正确答案'), - (6, u'已经过时、不可重现的问题'), - (7, u'太局部、本地化的问题'), - (8, u'恶意言论'), - (9, u'垃圾广告'), + (1, _('duplicate question')), + (2, _('question if off-topic or not relevant')), + (3, _('too subjective and argumentative')), + (4, _('is not an answer to the question')), + (5, _('the question is answered, right answer was accepted')), + (6, _('problem is not reproducible or outdated')), + #(7, u'太局部、本地化的问题',) + (7, _('question contains offensive inappropriate, or malicious remarks')), + (8, _('spam or advertising')), ) TYPE_REPUTATION = ( @@ -52,38 +53,35 @@ TYPE_ACTIVITY_USER_FULL_UPDATED = 17 #TYPE_ACTIVITY_EDIT_ANSWER=18 TYPE_ACTIVITY = ( - (TYPE_ACTIVITY_ASK_QUESTION, u'提问'), - (TYPE_ACTIVITY_ANSWER, u'回答'), - (TYPE_ACTIVITY_COMMENT_QUESTION, u'评论问题'), - (TYPE_ACTIVITY_COMMENT_ANSWER, u'评论回答'), - (TYPE_ACTIVITY_UPDATE_QUESTION, u'修改问题'), - (TYPE_ACTIVITY_UPDATE_ANSWER, u'修改回答'), - (TYPE_ACTIVITY_PRIZE, u'获奖'), - (TYPE_ACTIVITY_MARK_ANSWER, u'标记最佳答案'), - (TYPE_ACTIVITY_VOTE_UP, u'投赞成票'), - (TYPE_ACTIVITY_VOTE_DOWN, u'投反对票'), - (TYPE_ACTIVITY_CANCEL_VOTE, u'撤销投票'), - (TYPE_ACTIVITY_DELETE_QUESTION, u'删除问题'), - (TYPE_ACTIVITY_DELETE_ANSWER, u'删除回答'), - (TYPE_ACTIVITY_MARK_OFFENSIVE, u'标记垃圾帖'), - (TYPE_ACTIVITY_UPDATE_TAGS, u'更新标签'), - (TYPE_ACTIVITY_FAVORITE, u'收藏'), - (TYPE_ACTIVITY_USER_FULL_UPDATED, u'完成个人所有资料'), - #(TYPE_ACTIVITY_EDIT_QUESTION, u'编辑问题'), - #(TYPE_ACTIVITY_EDIT_ANSWER, u'编辑答案'), + (TYPE_ACTIVITY_ASK_QUESTION, _('question')), + (TYPE_ACTIVITY_ANSWER, _('answer')), + (TYPE_ACTIVITY_COMMENT_QUESTION, _('commented question')), + (TYPE_ACTIVITY_COMMENT_ANSWER, _('commented answer')), + (TYPE_ACTIVITY_UPDATE_QUESTION, _('edited question')), + (TYPE_ACTIVITY_UPDATE_ANSWER, _('edited answer')), + (TYPE_ACTIVITY_PRIZE, _('received award')), + (TYPE_ACTIVITY_MARK_ANSWER, _('marked best answer')), + (TYPE_ACTIVITY_VOTE_UP, _('upvoted')), + (TYPE_ACTIVITY_VOTE_DOWN, _('downvoted')), + (TYPE_ACTIVITY_CANCEL_VOTE, _('canceled vote')), + (TYPE_ACTIVITY_DELETE_QUESTION, _('deleted question')), + (TYPE_ACTIVITY_DELETE_ANSWER, _('deleted answer')), + (TYPE_ACTIVITY_MARK_OFFENSIVE, _('marked offensive')), + (TYPE_ACTIVITY_UPDATE_TAGS, _('updated tags')), + (TYPE_ACTIVITY_FAVORITE, _('selected favorite')), + (TYPE_ACTIVITY_USER_FULL_UPDATED, _('completed user profile')), ) TYPE_RESPONSE = { - 'QUESTION_ANSWERED' : u'回答问题', - 'QUESTION_COMMENTED': u'问题评论', - 'ANSWER_COMMENTED' : u'回答评论', - 'ANSWER_ACCEPTED' : u'最佳答案', + 'QUESTION_ANSWERED' : 'question_answered', + 'QUESTION_COMMENTED': 'question_commented', + 'ANSWER_COMMENTED' : 'answer_commented', + 'ANSWER_ACCEPTED' : 'answer_accepted', } CONST = { - 'closed' : u' [已关闭]', - 'deleted' : u' [已删除]', - 'default_version' : u'初始版本', - 'retagged' : u'更新了标签', - + 'closed' : _('[closed]'), + 'deleted' : _('[deleted]'), + 'default_version' : _('initial version'), + 'retagged' : _('retagged'), } diff --git a/forum/feed.py b/forum/feed.py index d75f3be6..a4218630 100644 --- a/forum/feed.py +++ b/forum/feed.py @@ -11,13 +11,15 @@ # Licence: GPL V2
#-------------------------------------------------------------------------------
from django.contrib.syndication.feeds import Feed, FeedDoesNotExist
+from django.utils.translation import ugettext as _
from models import Question
class RssLastestQuestionsFeed(Feed):
- title = u"CNProg程序员问答社区-最新问题"
- link = u"http://www.cnprog.com/questions/"
- description = u"中国程序员的编程技术问答社区。我们做专业的、可协作编辑的技术问答社区。"
+ title = _('site title') + _(' - ') + _('site slogan') + _(' - ')+ _('latest questions')
+ #EDIT!!!
+ link = 'http://where.com/questions/'
+ description = _('meta site content')
#ttl = 10
- copyright = u'Copyright(c)2009.CNPROG.COM'
+ copyright = _('copyright message')
def item_link(self, item):
return '/questions/%s/' % item.id
@@ -38,4 +40,4 @@ def main(): pass
if __name__ == '__main__':
- main()
\ No newline at end of file + main()
diff --git a/forum/forms.py b/forum/forms.py index 70a44f28..1b811ad9 100644 --- a/forum/forms.py +++ b/forum/forms.py @@ -1,8 +1,9 @@ -import re
+import re
from datetime import date
from django import forms
from models import *
from const import *
+from django.utils.translation import ugettext as _
class TitleField(forms.CharField):
def __init__(self, *args, **kwargs):
@@ -10,13 +11,13 @@ class TitleField(forms.CharField): self.required = True
self.widget = forms.TextInput(attrs={'size' : 70, 'autocomplete' : 'off'})
self.max_length = 255
- self.label = u'标题'
- self.help_text = u'请输入对问题具有描述性质的标题 - “帮忙!紧急求助!”不是建议的提问方式。'
+ self.label = _('title')
+ self.help_text = _('please enter a descriptive title for your question')
self.initial = ''
def clean(self, value):
if len(value) < 10:
- raise forms.ValidationError(u"标题的长度必须大于10")
+ raise forms.ValidationError(_('title must be > 10 characters'))
return value
@@ -25,13 +26,13 @@ class EditorField(forms.CharField): super(EditorField, self).__init__(*args, **kwargs)
self.required = True
self.widget = forms.Textarea(attrs={'id':'editor'})
- self.label = u'内容'
+ self.label = _('content')
self.help_text = u''
self.initial = ''
def clean(self, value):
if len(value) < 10:
- raise forms.ValidationError(u"内容至少要10个字符")
+ raise forms.ValidationError(_('question content must be > 10 characters'))
return value
@@ -41,39 +42,37 @@ class TagNamesField(forms.CharField): self.required = True
self.widget = forms.TextInput(attrs={'size' : 50, 'autocomplete' : 'off'})
self.max_length = 255
- self.label = u'标签'
- self.help_text = u'多个标签请用空格间隔-最多5个标签。(优先使用自动匹配的英文标签。)'
+ self.label = _('tags')
+ self.help_text = _('please use space to separate tags (this enables autocomplete feature)')
self.initial = ''
- def clean(self, value):
- value = super(TagNamesField, self).clean(value)
- data = value.strip()
- if len(data) < 1:
- raise forms.ValidationError(u'标签不能为空')
- list = data.split(' ')
- list_temp = []
- if len(list) > 5:
- raise forms.ValidationError(u'最多只能有5个标签')
- for tag in list:
- if len(tag) > 20:
- raise forms.ValidationError(u'每个标签的长度不超过20')
-
- #TODO: regex match not allowed characters here
-
- if tag.find('/') > -1 or tag.find('\\') > -1 or tag.find('<') > -1 or tag.find('>') > -1 or tag.find('&') > -1 or tag.find('\'') > -1 or tag.find('"') > -1:
- #if not tagname_re.match(tag):
- raise forms.ValidationError(u'标签请使用英文字母,中文或者数字字符串(. - _ # 也可以)')
- # only keep one same tag
- if tag not in list_temp and len(tag.strip()) > 0:
- list_temp.append(tag)
- return u' '.join(list_temp)
+ def clean(self, value):
+ value = super(TagNamesField, self).clean(value)
+ data = value.strip()
+ if len(data) < 1:
+ raise forms.ValidationError(_('tags are required'))
+ list = data.split(' ')
+ list_temp = []
+ if len(list) > 5:
+ raise forms.ValidationError(_('please use 5 tags or less'))
+ for tag in list:
+ if len(tag) > 20:
+ raise forms.ValidationError(_('tags must be shorter than 20 characters'))
+ #take tag regex from settings
+ tagname_re = re.compile(r'[a-z0-9]+')
+ if not tagname_re.match(tag):
+ raise forms.ValidationError(_('please use following characters in tags: letters \'a-z\', numbers, and characters \'.-_#\''))
+ # only keep one same tag
+ if tag not in list_temp and len(tag.strip()) > 0:
+ list_temp.append(tag)
+ return u' '.join(list_temp)
class WikiField(forms.BooleanField):
def __init__(self, *args, **kwargs):
super(WikiField, self).__init__(*args, **kwargs)
self.required = False
- self.label = u'社区wiki模式'
- self.help_text = u'选择社区wiki模式,问答不计算积分,签名也不显示作者信息'
+ self.label = _('community wiki')
+ self.help_text = _('if you choose community wiki option, the question and answer do not generate points and name of author will not be shown')
class SummaryField(forms.CharField):
@@ -82,8 +81,8 @@ class SummaryField(forms.CharField): self.required = False
self.widget = forms.TextInput(attrs={'size' : 50, 'autocomplete' : 'off'})
self.max_length = 300
- self.label = u'更新概要:'
- self.help_text = u'输入本次修改的简单概述(如:修改了别字,修正了语法,改进了样式等。非必填项。)'
+ self.label = _('update summary:')
+ self.help_text = _('enter a brief summary of your revision (e.g. fixed spelling, grammar, improved style, this field is optional)')
class AskForm(forms.Form):
title = TitleField()
@@ -158,12 +157,12 @@ class EditAnswerForm(forms.Form): self.fields['text'].initial = revision.text
class EditUserForm(forms.Form):
- email = forms.EmailField(label=u'Email', help_text=u'不会公开,用于头像显示服务', required=False, max_length=255, widget=forms.TextInput(attrs={'size' : 35}))
- realname = forms.CharField(label=u'真实姓名', required=False, max_length=255, widget=forms.TextInput(attrs={'size' : 35}))
- website = forms.URLField(label=u'个人网站', required=False, max_length=255, widget=forms.TextInput(attrs={'size' : 35}))
- city = forms.CharField(label=u'城市', required=False, max_length=255, widget=forms.TextInput(attrs={'size' : 35}))
- birthday = forms.DateField(label=u'生日', help_text=u'不会公开,只会显示您的年龄,格式为:YYYY-MM-DD', required=True, widget=forms.TextInput(attrs={'size' : 35}))
- about = forms.CharField(label=u'个人简介', required=False, widget=forms.Textarea(attrs={'cols' : 60}))
+ email = forms.EmailField(label=u'Email', help_text=_('this email does not have to be linked to gravatar'), required=False, max_length=255, widget=forms.TextInput(attrs={'size' : 35}))
+ realname = forms.CharField(label=_('Real name'), required=False, max_length=255, widget=forms.TextInput(attrs={'size' : 35}))
+ website = forms.URLField(label=_('Website'), required=False, max_length=255, widget=forms.TextInput(attrs={'size' : 35}))
+ city = forms.CharField(label=_('Location'), required=False, max_length=255, widget=forms.TextInput(attrs={'size' : 35}))
+ birthday = forms.DateField(label=_('Date of birth'), help_text=_('will not be shown, used to calculate age, format: YYYY-MM-DD'), required=False, widget=forms.TextInput(attrs={'size' : 35}))
+ about = forms.CharField(label=_('Profile'), required=False, widget=forms.Textarea(attrs={'cols' : 60}))
def __init__(self, user, *args, **kwargs):
super(EditUserForm, self).__init__(*args, **kwargs)
@@ -173,7 +172,7 @@ class EditUserForm(forms.Form): self.fields['city'].initial = user.location
if user.date_of_birth is not None:
- self.fields['birthday'].initial = user.date_of_birth.date()
+ self.fields['birthday'].initial = user.date_of_birth
else:
self.fields['birthday'].initial = '1990-01-01'
self.fields['about'].initial = user.about
@@ -188,7 +187,7 @@ class EditUserForm(forms.Form): except User.DoesNotExist:
return self.cleaned_data['email']
except User.MultipleObjectsReturned:
- raise forms.ValidationError(u'该电子邮件已被注册,请选择另一个再试。')
- raise forms.ValidationError("该电子邮件帐号已被注册,请选择另一个再试。")
+ raise forms.ValidationError(_('this email has already been registered, please use another one'))
+ raise forms.ValidationError(_('this email has already been registered, please use another one'))
else:
- return self.cleaned_data['email']
\ No newline at end of file + return self.cleaned_data['email']
diff --git a/forum/management/commands/once_award_badges.py b/forum/management/commands/once_award_badges.py index c26251d7..011c28fd 100644 --- a/forum/management/commands/once_award_badges.py +++ b/forum/management/commands/once_award_badges.py @@ -157,8 +157,7 @@ class Command(BaseCommand): """
activity_types = ','.join('%s' % item for item in BADGE_AWARD_TYPE_FIRST.keys())
# ORDER BY user_id, activity_type
- query = "SELECT id, user_id, activity_type, content_type_id, object_id "+
- "FROM activity WHERE is_auditted = 0 AND activity_type IN (%s) ORDER BY user_id, activity_type" % activity_types
+ query = "SELECT id, user_id, activity_type, content_type_id, object_id FROM activity WHERE is_auditted = 0 AND activity_type IN (%s) ORDER BY user_id, activity_type" % activity_types
cursor = connection.cursor()
try:
@@ -206,10 +205,7 @@ class Command(BaseCommand): (13, '学生', 3, '学生', '第一次提问并且有一次以上赞成票', 0, 0),
"""
- query = "SELECT act.user_id, q.vote_up_count, act.object_id FROM "+
- "activity act, question q WHERE act.activity_type = %s AND "+
- "act.object_id = q.id AND "+
- "act.user_id NOT IN (SELECT distinct user_id FROM award WHERE badge_id = %s)" % (TYPE_ACTIVITY_ASK_QUESTION, 13)
+ query = "SELECT act.user_id, q.vote_up_count, act.object_id FROM activity act, question q WHERE act.activity_type = %s AND act.object_id = q.id AND act.user_id NOT IN (SELECT distinct user_id FROM award WHERE badge_id = %s)" % (TYPE_ACTIVITY_ASK_QUESTION, 13)
cursor = connection.cursor()
try:
cursor.execute(query)
@@ -236,10 +232,7 @@ class Command(BaseCommand): (15, '教师', 3, '教师', '第一次回答问题并且得到一个以上赞成票', 0, 0),
"""
- query = "SELECT act.user_id, a.vote_up_count, act.object_id FROM "+
- "activity act, answer a WHERE act.activity_type = %s AND "+
- "act.object_id = a.id AND "+
- "act.user_id NOT IN (SELECT distinct user_id FROM award WHERE badge_id = %s)" % (TYPE_ACTIVITY_ANSWER, 15)
+ query = "SELECT act.user_id, a.vote_up_count, act.object_id FROM activity act, answer a WHERE act.activity_type = %s AND act.object_id = a.id AND act.user_id NOT IN (SELECT distinct user_id FROM award WHERE badge_id = %s)" % (TYPE_ACTIVITY_ANSWER, 15)
cursor = connection.cursor()
try:
cursor.execute(query)
@@ -264,11 +257,7 @@ class Command(BaseCommand): """
(32, '学问家', 2, '学问家', '第一次回答被投赞成票10次以上', 0, 0)
"""
- query = "SELECT act.user_id, act.object_id FROM "+
- "activity act, answer a WHERE act.object_id = a.id AND "+
- "act.activity_type = %s AND "+
- "a.vote_up_count >= 10 AND "+
- "act.user_id NOT IN (SELECT user_id FROM award WHERE badge_id = %s)" % (TYPE_ACTIVITY_ANSWER, 32)
+ query = "SELECT act.user_id, act.object_id FROM activity act, answer a WHERE act.object_id = a.id AND act.activity_type = %s AND a.vote_up_count >= 10 AND act.user_id NOT IN (SELECT user_id FROM award WHERE badge_id = %s)" % (TYPE_ACTIVITY_ANSWER, 32)
cursor = connection.cursor()
try:
cursor.execute(query)
@@ -292,11 +281,7 @@ class Command(BaseCommand): """
(26, '优秀市民', 2, '优秀市民', '投票300次以上', 0, 0)
"""
- query = "SELECT count(*) vote_count, user_id FROM activity WHERE "+
- "activity_type = %s OR "+
- "activity_type = %s AND "+
- "user_id NOT IN (SELECT user_id FROM award WHERE badge_id = %s) "+
- "GROUP BY user_id HAVING vote_count >= 300" % (TYPE_ACTIVITY_VOTE_UP, TYPE_ACTIVITY_VOTE_DOWN, 26)
+ query = "SELECT count(*) vote_count, user_id FROM activity WHERE activity_type = %s OR activity_type = %s AND user_id NOT IN (SELECT user_id FROM award WHERE badge_id = %s) GROUP BY user_id HAVING vote_count >= 300" % (TYPE_ACTIVITY_VOTE_UP, TYPE_ACTIVITY_VOTE_DOWN, 26)
self.__award_for_count_num(query, 26)
@@ -304,11 +289,7 @@ class Command(BaseCommand): """
(27, '编辑主任', 2, '编辑主任', '编辑了100个帖子', 0, 0)
"""
- query = "SELECT count(*) vote_count, user_id FROM activity WHERE "+
- "activity_type = %s OR "+
- "activity_type = %s AND "+
- "user_id NOT IN (SELECT user_id FROM award WHERE badge_id = %s) "+
- "GROUP BY user_id HAVING vote_count >= 100" % (TYPE_ACTIVITY_UPDATE_QUESTION, TYPE_ACTIVITY_UPDATE_ANSWER, 27)
+ query = "SELECT count(*) vote_count, user_id FROM activity WHERE activity_type = %s OR activity_type = %s AND user_id NOT IN (SELECT user_id FROM award WHERE badge_id = %s) GROUP BY user_id HAVING vote_count >= 100" % (TYPE_ACTIVITY_UPDATE_QUESTION, TYPE_ACTIVITY_UPDATE_ANSWER, 27)
self.__award_for_count_num(query, 27)
@@ -316,11 +297,7 @@ class Command(BaseCommand): """
(5, '评论家', 3, '评论家', '评论10次以上', 0, 0),
"""
- query = "SELECT count(*) vote_count, user_id FROM activity WHERE "+
- "activity_type = %s OR "+
- "activity_type = %s AND "+
- "user_id NOT IN (SELECT user_id FROM award WHERE badge_id = %s) "+
- "GROUP BY user_id HAVING vote_count >= 10" % (TYPE_ACTIVITY_COMMENT_QUESTION, TYPE_ACTIVITY_COMMENT_ANSWER, 5)
+ query = "SELECT count(*) vote_count, user_id FROM activity WHERE activity_type = %s OR activity_type = %s AND user_id NOT IN (SELECT user_id FROM award WHERE badge_id = %s) GROUP BY user_id HAVING vote_count >= 10" % (TYPE_ACTIVITY_COMMENT_QUESTION, TYPE_ACTIVITY_COMMENT_ANSWER, 5)
self.__award_for_count_num(query, 5)
def __award_for_count_num(self, query, badge):
diff --git a/forum/managers.py b/forum/managers.py index 0f22c59c..94f58ea7 100644 --- a/forum/managers.py +++ b/forum/managers.py @@ -4,29 +4,8 @@ from django.contrib.auth.models import User, UserManager from django.db import connection, models, transaction
from django.db.models import Q
from forum.models import *
-from urllib import quote, unquote
class QuestionManager(models.Manager):
- def get_translation_questions(self, orderby, page_size):
- questions = self.filter(deleted=False, author__id__in=[28,29]).order_by(orderby)[:page_size]
- return questions
-
- def get_questions_by_pagesize(self, orderby, page_size):
- questions = self.filter(deleted=False).order_by(orderby)[:page_size]
- return questions
-
- def get_questions_by_tag(self, tagname, orderby):
- questions = self.filter(deleted=False, tags__name = unquote(tagname)).order_by(orderby)
- return questions
-
- def get_unanswered_questions(self, orderby):
- questions = self.filter(deleted=False, answer_count=0).order_by(orderby)
- return questions
-
- def get_questions(self, orderby):
- questions = self.filter(deleted=False).order_by(orderby)
- return questions
-
def update_tags(self, question, tagnames, user):
"""
Updates Tag associations for a question to match the given
@@ -113,12 +92,7 @@ class TagManager(models.Manager): 'WHERE tag_id = tag.id'
') '
'WHERE id IN (%s)')
-
- def get_valid_tags(self, page_size):
- from forum.models import Tag
- tags = Tag.objects.all().filter(deleted=False).exclude(used_count=0).order_by("-id")[:page_size]
- return tags
-
+
def get_or_create_multiple(self, names, user):
"""
Fetches a list of Tags with the given names, creating any Tags
@@ -149,19 +123,6 @@ class TagManager(models.Manager): query = self.UPDATE_USED_COUNTS_QUERY % ','.join(['%s'] * len(tags))
cursor.execute(query, [tag.id for tag in tags])
transaction.commit_unless_managed()
-
- def get_tags_by_questions(self, questions):
- question_ids = []
- for question in questions:
- question_ids.append(question.id)
-
- question_ids_str = ','.join([str(id) for id in question_ids])
- related_tags = self.extra(
- tables=['tag', 'question_tags'],
- where=["tag.id = question_tags.tag_id AND question_tags.question_id IN (" + question_ids_str + ")"]
- ).distinct()
-
- return related_tags
class AnswerManager(models.Manager):
GET_ANSWERS_FROM_USER_QUESTIONS = u'SELECT answer.* FROM answer INNER JOIN question ON answer.question_id = question.id WHERE question.author_id =%s AND answer.author_id <> %s'
@@ -244,16 +205,4 @@ class ReputeManager(models.Manager): return row[0]
else:
- return 0
-class AwardManager(models.Manager):
- def get_recent_awards(self):
- awards = super(AwardManager, self).extra(
- select={'badge_id': 'badge.id', 'badge_name':'badge.name',
- 'badge_description': 'badge.description', 'badge_type': 'badge.type',
- 'user_id': 'auth_user.id', 'user_name': 'auth_user.username'
- },
- tables=['award', 'badge', 'auth_user'],
- order_by=['-awarded_at'],
- where=['auth_user.id=award.user_id AND badge_id=badge.id'],
- ).values('badge_id', 'badge_name', 'badge_description', 'badge_type', 'user_id', 'user_name')
- return awards
+ return 0
\ No newline at end of file diff --git a/forum/models.py b/forum/models.py index 290c9d56..aba2bf0b 100644 --- a/forum/models.py +++ b/forum/models.py @@ -10,6 +10,7 @@ from django.contrib.contenttypes import generic from django.contrib.contenttypes.models import ContentType
from django.template.defaultfilters import slugify
from django.db.models.signals import post_delete, post_save, pre_save
+from django.utils.translation import ugettext as _
import django.dispatch
from forum.managers import *
@@ -312,9 +313,9 @@ class Badge(models.Model): SILVER = 2
BRONZE = 3
TYPE_CHOICES = (
- (GOLD, u'金牌'),
- (SILVER, u'银牌'),
- (BRONZE, u'铜牌'),
+ (GOLD, _('gold')),
+ (SILVER, _('silver')),
+ (BRONZE, _('bronze')),
)
name = models.CharField(max_length=50)
@@ -350,8 +351,7 @@ class Award(models.Model): content_object = generic.GenericForeignKey('content_type', 'object_id')
awarded_at = models.DateTimeField(default=datetime.datetime.now)
notified = models.BooleanField(default=False)
- objects = AwardManager()
-
+
def __unicode__(self):
return u'[%s] is awarded a badge [%s] at %s' % (self.user.username, self.badge.name, self.awarded_at)
@@ -650,4 +650,4 @@ mark_offensive.connect(record_mark_offensive, sender=Question) mark_offensive.connect(record_mark_offensive, sender=Answer)
tags_updated.connect(record_update_tags, sender=Question)
post_save.connect(record_favorite_question, sender=FavoriteQuestion)
-user_updated.connect(record_user_full_updated, sender=User)
\ No newline at end of file +user_updated.connect(record_user_full_updated, sender=User)
diff --git a/forum/templatetags/extra_tags.py b/forum/templatetags/extra_tags.py index 7c53c2cb..de853135 100644 --- a/forum/templatetags/extra_tags.py +++ b/forum/templatetags/extra_tags.py @@ -1,4 +1,4 @@ -import time
+import time
import datetime
import math
import re
@@ -8,6 +8,7 @@ from django.utils.encoding import smart_unicode from django.utils.safestring import mark_safe
from django.utils.timesince import timesince
from forum.const import *
+from django.utils.translation import ugettext as _
register = template.Library()
@@ -49,10 +50,10 @@ def tag_font_size(max_size, min_size, current_size): weight = 0
return MIN_FONTSIZE + round((MAX_FONTSIZE - MIN_FONTSIZE) * weight)
-
+
LEADING_PAGE_RANGE_DISPLAYED = TRAILING_PAGE_RANGE_DISPLAYED = 5
LEADING_PAGE_RANGE = TRAILING_PAGE_RANGE = 4
-NUM_PAGES_OUTSIDE_RANGE = 1
+NUM_PAGES_OUTSIDE_RANGE = 1
ADJACENT_PAGES = 2
@register.inclusion_tag("paginator.html")
def cnprog_paginator(context):
@@ -64,10 +65,10 @@ def cnprog_paginator(context): " Initialize variables "
in_leading_range = in_trailing_range = False
pages_outside_leading_range = pages_outside_trailing_range = range(0)
-
+
if (context["pages"] <= LEADING_PAGE_RANGE_DISPLAYED):
in_leading_range = in_trailing_range = True
- page_numbers = [n for n in range(1, context["pages"] + 1) if n > 0 and n <= context["pages"]]
+ page_numbers = [n for n in range(1, context["pages"] + 1) if n > 0 and n <= context["pages"]]
elif (context["page"] <= LEADING_PAGE_RANGE):
in_leading_range = True
page_numbers = [n for n in range(1, LEADING_PAGE_RANGE_DISPLAYED + 1) if n > 0 and n <= context["pages"]]
@@ -76,11 +77,11 @@ def cnprog_paginator(context): in_trailing_range = True
page_numbers = [n for n in range(context["pages"] - TRAILING_PAGE_RANGE_DISPLAYED + 1, context["pages"] + 1) if n > 0 and n <= context["pages"]]
pages_outside_trailing_range = [n + 1 for n in range(0, NUM_PAGES_OUTSIDE_RANGE)]
- else:
+ else:
page_numbers = [n for n in range(context["page"] - ADJACENT_PAGES, context["page"] + ADJACENT_PAGES + 1) if n > 0 and n <= context["pages"]]
pages_outside_leading_range = [n + context["pages"] for n in range(0, -NUM_PAGES_OUTSIDE_RANGE, -1)]
pages_outside_trailing_range = [n + 1 for n in range(0, NUM_PAGES_OUTSIDE_RANGE)]
-
+
extend_url = context.get('extend_url', '')
return {
"base_url": context["base_url"],
@@ -110,23 +111,23 @@ def cnprog_pagesize(context): "pagesize" : context["pagesize"],
"is_paginated": context["is_paginated"]
}
-
+
@register.simple_tag
def get_score_badge(user):
- BADGE_TEMPLATE = '<span class="score" title="%(reputation)s用户积分">%(reputation)s</span>'
+ BADGE_TEMPLATE = '<span class="score" title="%(reputation)s %(reputationword)s">%(reputation)s</span>'
if user.gold > 0 :
- BADGE_TEMPLATE = '%s%s' % (BADGE_TEMPLATE, ' <span title="%(gold)s枚金牌">'
- '<span class="badge1">●</span>'
+ BADGE_TEMPLATE = '%s%s' % (BADGE_TEMPLATE, '<span title="%(gold)s %(badgesword)s">'
+ '<span class="badge1">●</span>'
'<span class="badgecount">%(gold)s</span>'
'</span>')
if user.silver > 0:
- BADGE_TEMPLATE = '%s%s' % (BADGE_TEMPLATE, ' <span title="%(silver)s枚银牌">'
- '<span class="silver">●</span>'
+ BADGE_TEMPLATE = '%s%s' % (BADGE_TEMPLATE, '<span title="%(silver)s %(badgesword)s">'
+ '<span class="silver">●</span>'
'<span class="badgecount">%(silver)s</span>'
'</span>')
if user.bronze > 0:
- BADGE_TEMPLATE = '%s%s' % (BADGE_TEMPLATE, ' <span title="%(bronze)s枚铜牌">'
- '<span class="bronze">●</span>'
+ BADGE_TEMPLATE = '%s%s' % (BADGE_TEMPLATE, '<span title="%(bronze)s %(badgesword)s">'
+ '<span class="bronze">●</span>'
'<span class="badgecount">%(bronze)s</span>'
'</span>')
BADGE_TEMPLATE = smart_unicode(BADGE_TEMPLATE, encoding='utf-8', strings_only=False, errors='strict')
@@ -135,24 +136,26 @@ def get_score_badge(user): 'gold' : user.gold,
'silver' : user.silver,
'bronze' : user.bronze,
+ 'badgesword' : _('badges'),
+ 'reputationword' : _('reputation points'),
})
-
+
@register.simple_tag
def get_score_badge_by_details(rep, gold, silver, bronze):
- BADGE_TEMPLATE = '<span class="reputation-score" title="%(reputation)s用户积分">%(reputation)s</span>'
+ BADGE_TEMPLATE = '<span class="reputation-score" title="%(reputation)s %(repword)s">%(reputation)s</span>'
if gold > 0 :
- BADGE_TEMPLATE = '%s%s' % (BADGE_TEMPLATE, '<span title="%(gold)s枚金牌">'
- '<span class="badge1">●</span>'
+ BADGE_TEMPLATE = '%s%s' % (BADGE_TEMPLATE, '<span title="%(gold)s %(badgeword)s">'
+ '<span class="badge1">●</span>'
'<span class="badgecount">%(gold)s</span>'
'</span>')
if silver > 0:
- BADGE_TEMPLATE = '%s%s' % (BADGE_TEMPLATE, '<span title="%(silver)s枚银牌">'
- '<span class="badge2">●</span>'
+ BADGE_TEMPLATE = '%s%s' % (BADGE_TEMPLATE, '<span title="%(silver)s %(badgeword)s">'
+ '<span class="badge2">●</span>'
'<span class="badgecount">%(silver)s</span>'
'</span>')
if bronze > 0:
- BADGE_TEMPLATE = '%s%s' % (BADGE_TEMPLATE, '<span title="%(bronze)s枚铜牌">'
- '<span class="badge3">●</span>'
+ BADGE_TEMPLATE = '%s%s' % (BADGE_TEMPLATE, '<span title="%(bronze)s %(badgeword)s">'
+ '<span class="badge3">●</span>'
'<span class="badgecount">%(bronze)s</span>'
'</span>')
BADGE_TEMPLATE = smart_unicode(BADGE_TEMPLATE, encoding='utf-8', strings_only=False, errors='strict')
@@ -161,19 +164,24 @@ def get_score_badge_by_details(rep, gold, silver, bronze): 'gold' : gold,
'silver' : silver,
'bronze' : bronze,
- })
-
+ 'repword' : _('reputation points'),
+ 'badgeword' : _('badges'),
+ })
+
@register.simple_tag
def get_user_vote_image(dic, key, arrow):
if dic.has_key(key):
if int(dic[key]) == int(arrow):
return '-on'
return ''
-
+
@register.simple_tag
def get_age(birthday):
current_time = datetime.datetime(*time.localtime()[0:6])
- diff = current_time - birthday
+ year = birthday.year
+ month = birthday.month
+ day = birthday.day
+ diff = current_time - datetime.datetime(year,month,day,0,0,0)
return diff.days / 365
@register.simple_tag
@@ -197,12 +205,12 @@ def format_number(value): m = re.match(pattern, strValue)
return first + result
-@register.simple_tag
+@register.simple_tag
def convert2tagname_list(question):
question['tagnames'] = [name for name in question['tagnames'].split(u' ')]
return ''
-@register.simple_tag
+@register.simple_tag
def diff_date(date, limen=2):
current_time = datetime.datetime(*time.localtime()[0:6])
diff = current_time - date
@@ -210,8 +218,8 @@ def diff_date(date, limen=2): if diff_days > limen:
return date
else:
- return timesince(date) + u'前'
-
+ return timesince(date) + _(' ago')
+
@register.simple_tag
def get_latest_changed_timestamp():
try:
@@ -229,4 +237,4 @@ def get_latest_changed_timestamp(): timestr = strftime("%H:%M %b-%d-%Y %Z", localtime(latest))
except:
timestr = ''
- return timestr
\ No newline at end of file + return timestr
diff --git a/forum/user.py b/forum/user.py index 2461e073..13e9be30 100644 --- a/forum/user.py +++ b/forum/user.py @@ -1,4 +1,3 @@ -# coding=utf-8
from django.utils.translation import ugettext as _
class UserView:
def __init__(self, id, tab_title, tab_description, page_title, view_name, template_file, data_size=0):
@@ -14,61 +13,61 @@ class UserView: USER_TEMPLATE_VIEWS = (
UserView(
id = 'stats',
- tab_title = _("Overview"),
- tab_description = _('User overview'),
- page_title = _('Overview - User Profile'),
+ tab_title = _('overview'),
+ tab_description = _('user profile'),
+ page_title = _('user profile overview'),
view_name = 'user_stats',
template_file = 'user_stats.html'
),
UserView(
id = 'recent',
- tab_title = _('Recent'),
- tab_description = _("Recent activities"),
- page_title = _('Recent - User Profile'),
+ tab_title = _('recent activity'),
+ tab_description = _('recent user activity'),
+ page_title = _('profile - recent activity'),
view_name = 'user_recent',
template_file = 'user_recent.html',
data_size = 50
),
UserView(
id = 'responses',
- tab_title = _("Response"),
- tab_description = _("Responses from others"),
- page_title = _("Response - User Profile"),
+ tab_title = _('responses'),
+ tab_description = _('comments and answers to others questions'),
+ page_title = _('profile - responses'),
view_name = 'user_responses',
template_file = 'user_responses.html',
data_size = 50
),
UserView(
id = 'reputation',
- tab_title = _("Reputation"),
- tab_description = _("Community reputation"),
- page_title = _("Reputation - User Profile"),
+ tab_title = _('reputation'),
+ tab_description = _('user reputation in the community'),
+ page_title = _('profile - user reputation'),
view_name = 'user_reputation',
template_file = 'user_reputation.html'
),
UserView(
id = 'favorites',
- tab_title = _("Favorites"),
- tab_description = _("User's favorite questions"),
- page_title = _("Favorites - User Profile"),
+ tab_title = _('favorite questions'),
+ tab_description = _('users favorite questions'),
+ page_title = _('profile - favorite questions'),
view_name = 'user_favorites',
template_file = 'user_favorites.html',
data_size = 50
),
UserView(
id = 'votes',
- tab_title = _("Votes"),
- tab_description = _("Votes history"),
- page_title = _("Votes - User Profile"),
+ tab_title = _('casted votes'),
+ tab_description = _('user vote record'),
+ page_title = _('profile - votes'),
view_name = 'user_votes',
template_file = 'user_votes.html',
data_size = 50
),
UserView(
id = 'preferences',
- tab_title = _("Preferences"),
- tab_description = _("User preferences"),
- page_title = _("Preferences - User Profile"),
+ tab_title = _('preferences'),
+ tab_description = _('user preference settings'),
+ page_title = _('profile - user preferences'),
view_name = 'user_preferences',
template_file = 'user_preferences.html'
)
diff --git a/forum/views.py b/forum/views.py index 8252304e..25574e0b 100644 --- a/forum/views.py +++ b/forum/views.py @@ -15,6 +15,7 @@ from django.utils import simplejson from django.core import serializers
from django.db import transaction
from django.contrib.contenttypes.models import ContentType
+from django.utils.translation import ugettext as _
from utils.html import sanitize_html
from markdown2 import Markdown
@@ -76,17 +77,29 @@ def index(request): orderby = "-last_activity_at"
# group questions by author_id of 28,29
if view_id == 'trans':
- questions = Question.objects.get_translation_questions(orderby, INDEX_PAGE_SIZE)
+ questions = Question.objects.filter(deleted=False, author__id__in=[28,29]).order_by(orderby)[:INDEX_PAGE_SIZE]
else:
- questions = Question.objects.get_questions_by_pagesize(orderby, INDEX_PAGE_SIZE)
+ questions = Question.objects.filter(deleted=False).order_by(orderby)[:INDEX_PAGE_SIZE]
# RISK - inner join queries
- questions = questions.select_related()
- tags = Tag.objects.get_valid_tags(INDEX_TAGS_SIZE)
+ questions = questions.select_related();
+ tags = Tag.objects.all().filter(deleted=False).exclude(used_count=0).order_by("-id")[:INDEX_TAGS_SIZE]
- awards = Award.objects.get_recent_awards()
+ awards = Award.objects.extra(
+ select={'badge_id': 'badge.id', 'badge_name':'badge.name',
+ 'badge_description': 'badge.description', 'badge_type': 'badge.type',
+ 'user_id': 'auth_user.id', 'user_name': 'auth_user.username'
+ },
+ tables=['award', 'badge', 'auth_user'],
+ order_by=['-awarded_at'],
+ where=['auth_user.id=award.user_id AND badge_id=badge.id'],
+ ).values('badge_id', 'badge_name', 'badge_description', 'badge_type', 'user_id', 'user_name')
+
+ class testvar:
+ content = 'haha'
return render_to_response('index.html', {
"questions" : questions,
+ 'testvar':testvar,
"tab_id" : view_id,
"tags" : tags,
"awards" : awards[:INDEX_AWARD_SIZE],
@@ -114,11 +127,29 @@ def questions(request, tagname=None, unanswered=False): # Set flag to False by default. If it is equal to True, then need to be saved.
pagesize_changed = False
# get pagesize from session, if failed then get default value
- pagesize = request.session.get("pagesize")
+ user_page_size = request.session.get("pagesize", QUESTIONS_PAGE_SIZE)
+ # set pagesize equal to logon user specified value in database
+ if request.user.is_authenticated() and request.user.questions_per_page > 0:
+ user_page_size = request.user.questions_per_page
+
try:
page = int(request.GET.get('page', '1'))
+ # get new pagesize from UI selection
+ pagesize = int(request.GET.get('pagesize', user_page_size))
+ if pagesize <> user_page_size:
+ pagesize_changed = True
+
except ValueError:
page = 1
+ pagesize = user_page_size
+
+ # save this pagesize to user database
+ if pagesize_changed:
+ request.session["pagesize"] = pagesize
+ if request.user.is_authenticated():
+ user = request.user
+ user.questions_per_page = pagesize
+ user.save()
view_id = request.GET.get('sort', None)
view_dic = {"latest":"-added_at", "active":"-last_activity_at", "hottest":"-answer_count", "mostvoted":"-score" }
@@ -130,24 +161,29 @@ def questions(request, tagname=None, unanswered=False): # check if request is from tagged questions
if tagname is not None:
- objects = Question.objects.get_questions_by_tag(tagname, orderby)
+ #print datetime.datetime.now()
+ objects = Question.objects.filter(deleted=False, tags__name = unquote(tagname)).order_by(orderby)
+ #print datetime.datetime.now()
elif unanswered:
#check if request is from unanswered questions
template_file = "unanswered.html"
- objects = Question.objects.get_unanswered_questions(orderby)
+ objects = Question.objects.filter(deleted=False, answer_count=0).order_by(orderby)
else:
- objects = Question.objects.get_questions(orderby)
+ objects = Question.objects.filter(deleted=False).order_by(orderby)
# RISK - inner join queries
- objects = objects.select_related(depth=1);
+ objects = objects.select_related();
objects_list = Paginator(objects, pagesize)
questions = objects_list.page(page)
# Get related tags from this page objects
- if questions.object_list.count() > 0:
- related_tags = Tag.objects.get_tags_by_questions(questions.object_list)
- else:
- related_tags = None
+ related_tags = []
+ for question in questions.object_list:
+ tags = list(question.tags.all())
+ for tag in tags:
+ if tag not in related_tags:
+ related_tags.append(tag)
+
return render_to_response(template_file, {
"questions" : questions,
"tab_id" : view_id,
@@ -986,7 +1022,6 @@ def user_stats(request, user_id, user_view): 'title',
'author_id',
'accepted',
- 'vote_count',
'answer_count',
'vote_up_count',
'vote_down_count')[:100]
@@ -1055,8 +1090,7 @@ def user_recent(request, user_id, user_view): 'activity_type' : 'activity.activity_type'
},
tables=['activity', 'question'],
- where=['activity.content_type_id = %s AND activity.object_id = ' +
- 'question.id AND activity.user_id = %s AND activity.activity_type = %s'],
+ where=['activity.content_type_id = %s AND activity.object_id = question.id AND activity.user_id = %s AND activity.activity_type = %s'],
params=[question_type_id, user_id, TYPE_ACTIVITY_ASK_QUESTION],
order_by=['-activity.active_at']
).values(
@@ -1080,8 +1114,8 @@ def user_recent(request, user_id, user_view): 'activity_type' : 'activity.activity_type'
},
tables=['activity', 'answer', 'question'],
- where=['activity.content_type_id = %s AND activity.object_id = answer.id AND ' +
- 'answer.question_id=question.id AND activity.user_id=%s AND activity.activity_type=%s'],
+ where=['activity.content_type_id = %s AND activity.object_id = answer.id '
+ 'AND answer.question_id=question.id AND activity.user_id=%s AND activity.activity_type=%s'],
params=[answer_type_id, user_id, TYPE_ACTIVITY_ANSWER],
order_by=['-activity.active_at']
).values(
@@ -1106,9 +1140,7 @@ def user_recent(request, user_id, user_view): },
tables=['activity', 'question', 'comment'],
- where=['activity.content_type_id = %s AND activity.object_id = comment.id AND '+
- 'activity.user_id = comment.user_id AND comment.object_id=question.id AND '+
- 'comment.content_type_id=%s AND activity.user_id = %s AND activity.activity_type=%s'],
+ where=['activity.content_type_id = %s AND activity.object_id = comment.id AND activity.user_id = comment.user_id AND comment.object_id=question.id AND comment.content_type_id=%s AND activity.user_id = %s AND activity.activity_type=%s'],
params=[comment_type_id, question_type_id, user_id, TYPE_ACTIVITY_COMMENT_QUESTION],
order_by=['-comment.added_at']
).values(
@@ -1134,10 +1166,7 @@ def user_recent(request, user_id, user_view): },
tables=['activity', 'question', 'answer', 'comment'],
- where=['activity.content_type_id = %s AND activity.object_id = comment.id AND '+
- 'activity.user_id = comment.user_id AND comment.object_id=answer.id AND '+
- 'comment.content_type_id=%s AND question.id = answer.question_id AND '+
- 'activity.user_id = %s AND activity.activity_type=%s'],
+ where=['activity.content_type_id = %s AND activity.object_id = comment.id AND activity.user_id = comment.user_id AND comment.object_id=answer.id AND comment.content_type_id=%s AND question.id = answer.question_id AND activity.user_id = %s AND activity.activity_type=%s'],
params=[comment_type_id, answer_type_id, user_id, TYPE_ACTIVITY_COMMENT_ANSWER],
order_by=['-comment.added_at']
).values(
@@ -1163,9 +1192,7 @@ def user_recent(request, user_id, user_view): 'summary' : 'question_revision.summary'
},
tables=['activity', 'question_revision'],
- where=['activity.content_type_id = %s AND activity.object_id = question_revision.id AND '+
- 'activity.user_id = question_revision.author_id AND activity.user_id = %s AND '+
- 'activity.activity_type=%s'],
+ where=['activity.content_type_id = %s AND activity.object_id = question_revision.id AND activity.user_id = question_revision.author_id AND activity.user_id = %s AND activity.activity_type=%s'],
params=[question_revision_type_id, user_id, TYPE_ACTIVITY_UPDATE_QUESTION],
order_by=['-activity.active_at']
).values(
@@ -1193,10 +1220,7 @@ def user_recent(request, user_id, user_view): },
tables=['activity', 'answer_revision', 'question', 'answer'],
- where=['activity.content_type_id = %s AND activity.object_id = answer_revision.id AND '+
- 'activity.user_id = answer_revision.author_id AND activity.user_id = %s AND '+
- 'answer_revision.answer_id=answer.id AND answer.question_id = question.id AND '+
- 'activity.activity_type=%s'],
+ where=['activity.content_type_id = %s AND activity.object_id = answer_revision.id AND activity.user_id = answer_revision.author_id AND activity.user_id = %s AND answer_revision.answer_id=answer.id AND answer.question_id = question.id AND activity.activity_type=%s'],
params=[answer_revision_type_id, user_id, TYPE_ACTIVITY_UPDATE_ANSWER],
order_by=['-activity.active_at']
).values(
@@ -1222,9 +1246,7 @@ def user_recent(request, user_id, user_view): 'activity_type' : 'activity.activity_type',
},
tables=['activity', 'answer', 'question'],
- where=['activity.content_type_id = %s AND activity.object_id = answer.id AND '+
- 'activity.user_id = question.author_id AND activity.user_id = %s AND '+
- 'answer.question_id=question.id AND activity.activity_type=%s'],
+ where=['activity.content_type_id = %s AND activity.object_id = answer.id AND activity.user_id = question.author_id AND activity.user_id = %s AND answer.question_id=question.id AND activity.activity_type=%s'],
params=[answer_type_id, user_id, TYPE_ACTIVITY_MARK_ANSWER],
order_by=['-activity.active_at']
).values(
@@ -1245,8 +1267,7 @@ def user_recent(request, user_id, user_view): 'activity_type' : 'activity.activity_type'
},
tables=['activity', 'award', 'badge'],
- where=['activity.user_id = award.user_id AND activity.user_id = %s AND '+
- 'award.badge_id=badge.id AND activity.object_id=award.id AND activity.activity_type=%s'],
+ where=['activity.user_id = award.user_id AND activity.user_id = %s AND award.badge_id=badge.id AND activity.object_id=award.id AND activity.activity_type=%s'],
params=[user_id, TYPE_ACTIVITY_PRIZE],
order_by=['-activity.active_at']
).values(
@@ -1299,8 +1320,7 @@ def user_responses(request, user_id, user_view): },
select_params=[user_id],
tables=['answer', 'question', 'auth_user'],
- where=['answer.question_id = question.id AND answer.deleted=0 AND question.deleted = 0 AND '+
- 'question.author_id = %s AND answer.author_id <> %s AND answer.author_id=auth_user.id'],
+ where=['answer.question_id = question.id AND answer.deleted=0 AND question.deleted = 0 AND question.author_id = %s AND answer.author_id <> %s AND answer.author_id=auth_user.id'],
params=[user_id, user_id],
order_by=['-answer.id']
).values(
@@ -1329,8 +1349,7 @@ def user_responses(request, user_id, user_view): 'user_id' : 'auth_user.id'
},
tables=['question', 'auth_user', 'comment'],
- where=['question.deleted = 0 AND question.author_id = %s AND comment.object_id=question.id AND '+
- 'comment.content_type_id=%s AND comment.user_id <> %s AND comment.user_id = auth_user.id'],
+ where=['question.deleted = 0 AND question.author_id = %s AND comment.object_id=question.id AND comment.content_type_id=%s AND comment.user_id <> %s AND comment.user_id = auth_user.id'],
params=[user_id, question_type_id, user_id],
order_by=['-comment.added_at']
).values(
@@ -1359,9 +1378,7 @@ def user_responses(request, user_id, user_view): 'user_id' : 'auth_user.id'
},
tables=['answer', 'auth_user', 'comment', 'question'],
- where=['answer.deleted = 0 AND answer.author_id = %s AND comment.object_id=answer.id AND '+
- 'comment.content_type_id=%s AND comment.user_id <> %s AND comment.user_id = auth_user.id '+
- 'AND question.id = answer.question_id'],
+ where=['answer.deleted = 0 AND answer.author_id = %s AND comment.object_id=answer.id AND comment.content_type_id=%s AND comment.user_id <> %s AND comment.user_id = auth_user.id AND question.id = answer.question_id'],
params=[user_id, answer_type_id, user_id],
order_by=['-comment.added_at']
).values(
@@ -1392,8 +1409,7 @@ def user_responses(request, user_id, user_view): },
select_params=[user_id],
tables=['answer', 'question', 'auth_user'],
- where=['answer.question_id = question.id AND answer.deleted=0 AND question.deleted = 0 AND '+
- 'answer.author_id = %s AND answer.accepted=1 AND question.author_id=auth_user.id'],
+ where=['answer.question_id = question.id AND answer.deleted=0 AND question.deleted = 0 AND answer.author_id = %s AND answer.accepted=1 AND question.author_id=auth_user.id'],
params=[user_id],
order_by=['-answer.id']
).values(
@@ -1437,8 +1453,7 @@ def user_votes(request, user_id, user_view): },
select_params=[user_id],
tables=['vote', 'question', 'auth_user'],
- where=['vote.content_type_id = %s AND vote.user_id = %s AND vote.object_id = question.id '+
- 'AND vote.user_id=auth_user.id'],
+ where=['vote.content_type_id = %s AND vote.user_id = %s AND vote.object_id = question.id AND vote.user_id=auth_user.id'],
params=[question_type_id, user_id],
order_by=['-vote.id']
).values(
@@ -1461,8 +1476,7 @@ def user_votes(request, user_id, user_view): },
select_params=[user_id],
tables=['vote', 'answer', 'question', 'auth_user'],
- where=['vote.content_type_id = %s AND vote.user_id = %s AND vote.object_id = answer.id '+
- 'AND answer.question_id = question.id AND vote.user_id=auth_user.id'],
+ where=['vote.content_type_id = %s AND vote.user_id = %s AND vote.object_id = answer.id AND answer.question_id = question.id AND vote.user_id=auth_user.id'],
params=[answer_type_id, user_id],
order_by=['-vote.id']
).values(
@@ -1487,8 +1501,7 @@ def user_votes(request, user_id, user_view): def user_reputation(request, user_id, user_view):
user = get_object_or_404(User, id=user_id)
reputation = Repute.objects.extra(
- select={'positive': 'sum(positive)', 'negative': 'sum(negative)', 'question_id':'question_id',
- 'title': 'question.title'},
+ select={'positive': 'sum(positive)', 'negative': 'sum(negative)', 'question_id':'question_id', 'title': 'question.title'},
tables=['repute', 'question'],
order_by=['-reputed_at'],
where=['user_id=%s AND question_id=question.id'],
@@ -1497,7 +1510,6 @@ def user_reputation(request, user_id, user_view): reputation.query.group_by = ['question_id']
-
rep_list = []
for rep in Repute.objects.filter(user=user).order_by('reputed_at'):
dic = '[%s,%s]' % (calendar.timegm(rep.reputed_at.timetuple()) * 1000, rep.reputation)
@@ -1519,8 +1531,7 @@ def user_favorites(request, user_id, user_view): questions = Question.objects.extra(
select={
'vote_count' : 'question.vote_up_count + question.vote_down_count',
- 'favorited_myself' : 'SELECT count(*) FROM favorite_question f WHERE f.user_id = %s '+
- 'AND f.question_id = question.id',
+ 'favorited_myself' : 'SELECT count(*) FROM favorite_question f WHERE f.user_id = %s AND f.question_id = question.id',
'la_user_id' : 'auth_user.id',
'la_username' : 'auth_user.username',
'la_user_gold' : 'auth_user.gold',
@@ -1530,8 +1541,7 @@ def user_favorites(request, user_id, user_view): },
select_params=[user_id],
tables=['question', 'auth_user', 'favorite_question'],
- where=['question.deleted = 0 AND question.last_activity_by_id = auth_user.id '+
- 'AND favorite_question.question_id = question.id AND favorite_question.user_id = %s'],
+ where=['question.deleted = 0 AND question.last_activity_by_id = auth_user.id AND favorite_question.question_id = question.id AND favorite_question.user_id = %s'],
params=[user_id],
order_by=['-vote_count', '-question.id']
).values('vote_count',
@@ -1662,12 +1672,7 @@ def badges(request): def badge(request, id):
badge = get_object_or_404(Badge, id=id)
awards = Award.objects.extra(
- select={'id': 'auth_user.id',
- 'name': 'auth_user.username',
- 'rep':'auth_user.reputation',
- 'gold': 'auth_user.gold',
- 'silver': 'auth_user.silver',
- 'bronze': 'auth_user.bronze'},
+ select={'id': 'auth_user.id', 'name': 'auth_user.username', 'rep':'auth_user.reputation', 'gold': 'auth_user.gold', 'silver': 'auth_user.silver', 'bronze': 'auth_user.bronze'},
tables=['award', 'auth_user'],
where=['badge_id=%s AND user_id=auth_user.id'],
params=[id]
@@ -1722,13 +1727,13 @@ def upload(request): result = xml_template % ('Good', '', default_storage.url(new_file_name))
except UploadPermissionNotAuthorized:
- result = xml_template % ('', u"上传图片只限于积分+60以上注册用户!", '')
+ result = xml_template % ('', _('uploading images is limited to users with >60 reputation points'), '')
except FileTypeNotAllow:
- result = xml_template % ('', u"只允许上传'jpg', 'jpeg', 'gif', 'bmp', 'png', 'tiff'类型的文件!", '')
+ result = xml_template % ('', _("allowed file types are 'jpg', 'jpeg', 'gif', 'bmp', 'png', 'tiff'"), '')
except FileSizeNotAllow:
- result = xml_template % ('', u"只允许上传%sK大小的文件!" % settings.ALLOW_MAX_FILE_SIZE / 1024, '')
- except Exception:
- result = xml_template % ('', u"在文件上传过程中产生了错误,请联系管理员,谢谢^_^", '')
+ result = xml_template % ('', _("maximum upload file size is %sK") % settings.ALLOW_MAX_FILE_SIZE / 1024, '')
+ except Exception as e:
+ result = xml_template % ('', _('Error uploading file. Please contact the site administrator. Thank you. %s' % e), '')
return HttpResponse(result, mimetype="application/xml")
|