Cleanup of the Reddit app, now uses Class views

This commit is contained in:
2011-09-09 14:20:13 +01:00
parent 0b6d97e2f6
commit 8f914a98ac
7 changed files with 102 additions and 56 deletions

View File

@@ -0,0 +1,11 @@
VERSION = (0, 1)
# Dynamically calculate the version based on VERSION tuple
if len(VERSION)>2 and VERSION[2] is not None:
str_version = "%d.%d_%s" % VERSION[:3]
else:
str_version = "%d.%d" % VERSION[:2]
__version__ = str_version

View File

@@ -1,8 +1,6 @@
from django.contrib import admin
from reddit.models import RedditAccount
from reddit.forms import RedditAccountForm
from datetime import date
class RedditAccountAdmin(admin.ModelAdmin):
list_display = ('username', 'user', 'date_created', 'link_karma', 'comment_karma', 'last_update', 'validated', 'is_valid')

View File

@@ -1,14 +1,11 @@
from django import forms
from django.contrib.auth.models import User
from reddit.models import RedditAccount
class RedditAccountForm(forms.Form):
class RedditAccountForm(forms.ModelForm):
""" Basic Reddit account input form """
username = forms.CharField(label = u'Reddit Username', max_length=64)
def clean(self):
try:
eaccount = RedditAccount.objects.get(username=self.cleaned_data['username'])
@@ -16,3 +13,8 @@ class RedditAccountForm(forms.Form):
return self.cleaned_data
else:
raise forms.ValidationError("This User ID is already registered")
class Meta:
model = RedditAccount
fields = ('username', 'user')
widgets = {'user': forms.HiddenInput()}

View File

@@ -0,0 +1,19 @@
{% extends "base.html" %}
{% block title %}Add Reddit Account{% endblock %}
{% block content %}
<h1>Add Reddit Account</h1>
<p>This will bind a Reddit account to your Auth Gateway login, this is usually required for application to the
corporation</p>
<p>Please note, you will be forever tied to this account and posts and comments made on this account will be checked
on from time to time</p>
<form action="{% url reddit-addaccount %}" method="post">
<table>
{{ form.as_table }}
</table>
{% csrf_token %}
<br />
<input type="submit" value="Add Account" />
</form>
{% endblock %}

View File

@@ -0,0 +1,12 @@
{% extends "base.html" %}
{% block title %}Delete Reddit Account{% endblock %}
{% block content %}
<h1>Delete Reddit Account</h1>
<p>Do you wish to delete the Reddit account {{ account.username }} from Auth?</p>
<form action="{% url reddit-delaccount account.id %}" method="post">
<input type="submit" value="Delete Account" />
{% csrf_token %}
</form>
{% endblock %}

View File

@@ -1,12 +1,9 @@
from django.conf.urls.defaults import *
from django.contrib.auth.decorators import login_required
from reddit import views
urlpatterns = patterns('',
(r'^profile/add/reddit', views.reddit_add),
(r'^profile/del/reddit/$', views.reddit_del),
(r'^profile/del/reddit/(?P<redditid>\d+)/$', views.reddit_del),
url(r'^profile/add/reddit', login_required(views.RedditAddAccount.as_view()), name='reddit-addaccount'),
url(r'^profile/del/reddit/(?P<slug>\d+)/$', login_required(views.RedditDeleteAccount.as_view()), name='reddit-delaccount'),
url(r'^reddit/comments.json$', views.RedditCommentsJSON.as_view(), name='reddit-commentsjson'),
)

View File

@@ -1,62 +1,73 @@
from django.contrib.auth.decorators import login_required
from django.shortcuts import render_to_response, redirect
from django.template import RequestContext
from django.views.generic import TemplateView
from django.http import HttpResponse
import django.utils.simplejson as json
from django.views.generic import TemplateView, DeleteView, CreateView
from django.http import HttpResponse, HttpResponseRedirect
from django.utils import simplejson as json
from django.core.urlresolvers import reverse
from django.contrib import messages
from django.contrib.auth.models import User
from django.contrib.auth.decorators import login_required
from gargoyle.decorators import switch_is_active
from reddit.forms import RedditAccountForm
from reddit.models import RedditAccount
@login_required
@switch_is_active('reddit')
def reddit_add(request):
""" Add a Reddit account to a user's account """
class RedditAddAccount(CreateView):
"""
Adds a reddit account to the system
"""
if request.method == 'POST':
form = RedditAccountForm(request.POST)
if form.is_valid():
acc = RedditAccount()
acc.user = request.user
acc.username = form.cleaned_data['username']
try:
acc.api_update()
except RedditAccount.DoesNotExist:
messages.add_message(request, messages.ERROR, "Error, user %s does not exist on Reddit" % acc.username )
return render_to_response('reddit/add_reddit_account.html', locals(), context_instance=RequestContext(request))
acc.save()
model = RedditAccount
template_name = 'reddit/add.html'
form_class = RedditAccountForm
messages.add_message(request, messages.INFO, "Reddit account %s successfully added." % acc.username)
return redirect('sso.views.profile') # Redirect after POST
else:
defaults = { 'username': request.user.username, }
form = RedditAccountForm(defaults) # An unbound form
def get_success_url(self):
return reverse('sso.views.profile')
return render_to_response('reddit/add_reddit_account.html', locals(), context_instance=RequestContext(request))
def get_initial(self):
initial = super(RedditAddAccount, self).get_initial()
initial['username'] = self.request.user.username
initial['user'] = self.request.user
return initial
@login_required
@switch_is_active('reddit')
def reddit_del(request, redditid=0):
""" Delete a Reddit account from a user's account """
if redditid > 0 :
def form_valid(self, form):
acc = form.save(commit=False)
acc.user = self.request.user
try:
acc = RedditAccount.objects.get(id=redditid)
acc.api_update()
except RedditAccount.DoesNotExist:
return redirect('sso.views.profile')
messages.add_message(self.request, messages.ERROR, "Error, user %s does not exist on Reddit" % acc.username )
else:
acc.save()
messages.add_message(self.request, messages.INFO, "Reddit account %s successfully added." % acc.username)
return HttpResponseRedirect(self.get_success_url())
if acc.user == request.user:
acc.delete()
messages.add_message(request, messages.INFO, "Reddit account successfully deleted.")
return redirect('sso.views.profile')
class RedditDeleteAccount(DeleteView):
"""
Deletes an existing Reddit account stored in the system
"""
slug_field = 'id'
model = RedditAccount
template_name = 'reddit/delete.html'
context_object_name = 'account'
def get_success_url(self):
return reverse('sso.views.profile')
def delete(self, request, *args, **kwargs):
self.object = self.get_object()
if self.object.user == self.request.user:
self.object.delete()
messages.add_message(self.request, messages.INFO, "Reddit account successfully deleted.")
return HttpResponseRedirect(self.get_success_url())
class JSONResponseMixin(object):
"""
Renders the template context as a JSON response
"""
def render_to_response(self, context):
"Returns a JSON response containing 'context' as payload"
return self.get_json_response(self.convert_context_to_json(context))
@@ -69,10 +80,6 @@ class JSONResponseMixin(object):
def convert_context_to_json(self, context):
"Convert the context dictionary into a JSON object"
# Note: This is *EXTREMELY* naive; in reality, you'll need
# to do much more complex handling to ensure that arbitrary
# objects -- such as Django model instances or querysets
# -- can be serialized as JSON.
return json.dumps(context)