Commit 64ff8ce5 authored by Daniel W Bond's avatar Daniel W Bond
Browse files

PEP8 NSDAPing

parent 0ec2465e
...@@ -5,6 +5,7 @@ from .models import Student ...@@ -5,6 +5,7 @@ from .models import Student
import requests import requests
def pfinfo(u_name): def pfinfo(u_name):
pf_url = "http://peoplefinder.b1.akshaykarthik.com/" pf_url = "http://peoplefinder.b1.akshaykarthik.com/"
url = str(pf_url) + "basic/all/" + str(u_name) url = str(pf_url) + "basic/all/" + str(u_name)
...@@ -18,8 +19,8 @@ def pfinfo(u_name): ...@@ -18,8 +19,8 @@ def pfinfo(u_name):
name = pf_json['results'][0]['name'] name = pf_json['results'][0]['name']
return name.split(',') return name.split(',')
def create_user(tree):
def create_user(tree):
username = tree[0][0].text username = tree[0][0].text
print username print username
user, user_created = User.objects.get_or_create(username=username) user, user_created = User.objects.get_or_create(username=username)
......
from haystack.forms import SearchForm
class StyledSearchForm( SearchForm ):
q = forms.CharField(
required = False,
label = 'Search',
widget = forms.TextInput(attrs={
'class': 'form-control',
'placeholder': 'ISBN, Title, Author',
'autofocus': 'autofocus',
}),
)
...@@ -2,30 +2,33 @@ from django.db import models ...@@ -2,30 +2,33 @@ from django.db import models
from django.contrib.auth.models import User from django.contrib.auth.models import User
from autoslug import AutoSlugField from autoslug import AutoSlugField
from model_utils.models import TimeStampedModel from model_utils.models import TimeStampedModel
from django.core.validators import RegexValidator #from django.core.validators import RegexValidator
from django.core.urlresolvers import reverse from django.core.urlresolvers import reverse
class Student(TimeStampedModel): class Student(TimeStampedModel):
user = models.OneToOneField(User) user = models.OneToOneField(User)
# django user includes username, password, first name, and last name # django user includes username, password, first name, and last name
# implement ratings later # implement ratings later
# rating = models.IntegerField(null=True,default=0) #rating = models.IntegerField(null=True, default=0)
slug = AutoSlugField(populate_from = 'user', unique = True) slug = AutoSlugField(populate_from='user', unique=True)
def get_absolute_url(self): def get_absolute_url(self):
return reverse('profile', kwargs = {'slug':self.slug}) return reverse('profile', kwargs={'slug': self.slug})
def __unicode__(self): def __unicode__(self):
return '%s' % self.user.username return '%s' % self.user.username
class Course(TimeStampedModel): class Course(TimeStampedModel):
name = models.CharField(max_length = 255) name = models.CharField(max_length=255)
department = models.CharField(max_length = 255) department = models.CharField(max_length=255)
departmentAbbreviation = models.CharField(max_length = 4) departmentAbbreviation = models.CharField(max_length=4)
#number = models.CharField(max_length=255, validators=RegexValidator('[0-9]{3,}')) #number = models.CharField(max_length=255,
number = models.CharField(max_length = 3) #validators=RegexValidator('[0-9]{3,}'))
number = models.CharField(max_length=3)
def __unicode__(self):
return "%s %s" % (self.departmentAbbreviation, self.number) def __unicode__(self):
return "%s %s" % (self.departmentAbbreviation, self.number)
from django.contrib.auth.models import User
from django.db.models.signals import post_save
from django.core.validators import MinValueValidator, RegexValidator
from django.db import models
# Create your models here.
class Seller( models.Model ):
user = models.OneToOneField(User)
# name = models.CharField(max_length = 200, primary_key=True)
# username = models.CharField(max_length = 200)
# email = models.CharField(max_length = 200)
rating = models.IntegerField(null=True,default=0)
# object call
def __unicode__(self):
return '%s' % self.user
def get_absolute_url(self):
from django.core.urlresolvers import reverse
return reverse('profile', args=[self.user.username])
def create_user_profile(sender, instance, created, **kwargs):
if created:
Seller.objects.create(user=instance)
post_save.connect(create_user_profile, sender=User)
from django.conf.urls import patterns, include, url from django.conf.urls import patterns, url
from core.views import DetailStudent from core.views import DetailStudent
from core.models import Student
urlpatterns = patterns('', urlpatterns = patterns('',
url(r'^(?P<slug>[\w-]+)/$', url(r'^(?P<slug>[\w-]+)/$',
......
...@@ -5,27 +5,7 @@ from core.models import Student ...@@ -5,27 +5,7 @@ from core.models import Student
from lookouts.models import Lookout from lookouts.models import Lookout
from trades.models import Listing, Bid from trades.models import Listing, Bid
# seller's rating
"""def ratingsAverage(seller):
sellerRating = Seller.objects.filter(user__username=seller)
ratingNumber = 0
ratingTotal = 0
ratingAverage = 0
for rating in sellerRating:
ratingNumber += 1
ratingTotal += rating
ratingAverage = ratingTotal/ratingNumber
return ratingNumber"""
### VIEWS ###
def privacy_opt_out(request):
# merely forms
return render(request, 'privacy_opt_out.html', {
},
)
# User profile page
class DetailStudent(LoginRequiredMixin, DetailView): class DetailStudent(LoginRequiredMixin, DetailView):
model = Student model = Student
template_name = 'profile.html' template_name = 'profile.html'
......
from django.contrib import admin from django.contrib import admin
from .models import Lookout from .models import Lookout
@admin.register(Lookout) @admin.register(Lookout)
class LookoutAdmin(admin.ModelAdmin): class LookoutAdmin(admin.ModelAdmin):
list_display = ('id', 'created', 'modified', 'owner', 'isbn') list_display = ('id', 'created', 'modified', 'owner', 'isbn')
list_filter = ('created', 'modified', 'owner') list_filter = ('created', 'modified', 'owner')
...@@ -4,24 +4,28 @@ from crispy_forms.helper import FormHelper ...@@ -4,24 +4,28 @@ from crispy_forms.helper import FormHelper
from crispy_forms.layout import Button, Submit, Layout, Fieldset, HTML, Field from crispy_forms.layout import Button, Submit, Layout, Fieldset, HTML, Field
from crispy_forms.bootstrap import FormActions from crispy_forms.bootstrap import FormActions
from lookouts.models import Lookout from .models import Lookout
class LookoutForm( forms.ModelForm ):
class LookoutForm(forms.ModelForm):
def __init__(self, *args, **kwargs): def __init__(self, *args, **kwargs):
self.helper = FormHelper() self.helper = FormHelper()
self.helper.label_class='col-md-2 col-md-offset-1 text-center be-bold' self.helper.label_class = 'col-md-2 col-md-offset-1 text-center be-bold'
self.helper.field_class='col-sm-8' self.helper.field_class = 'col-sm-8'
self.helper.layout = Layout( self.helper.layout = Layout(
Fieldset("", Fieldset("",
Field('isbn', placeholder='0801884039'), Field('isbn', placeholder='0801884039'),
HTML("""<hr/ >"""), HTML("""<hr/ >"""),
FormActions( FormActions(Submit('submit', 'Submit',
Submit('submit', 'Submit', css_class='btn-primary'), css_class='btn-primary'),
Button('cancel', 'Never Mind', css_class="btn-default", onclick="history.back()")), Button('cancel', 'Never Mind',
), css_class="btn-default",
onclick="history.back()")
),
),
) )
super(LookoutForm, self).__init__(*args, **kwargs) super(LookoutForm, self).__init__(*args, **kwargs)
...@@ -29,4 +33,3 @@ class LookoutForm( forms.ModelForm ): ...@@ -29,4 +33,3 @@ class LookoutForm( forms.ModelForm ):
class Meta: class Meta:
model = Lookout model = Lookout
from django.db import models from django.db import models
from trades.models import Listing from trades.models import Listing
from core.models import Student, Course from core.models import Student
from django.conf import settings
from django.core.urlresolvers import reverse from django.core.urlresolvers import reverse
from django.core.validators import RegexValidator from django.core.validators import RegexValidator
from model_utils.models import TimeStampedModel from model_utils.models import TimeStampedModel
from randomslugfield import RandomSlugField from randomslugfield import RandomSlugField
class Lookout(TimeStampedModel): class Lookout(TimeStampedModel):
owner = models.ForeignKey(Student) owner = models.ForeignKey(Student)
isbn = models.CharField( isbn = models.CharField(
max_length = 20, max_length=20,
validators = [RegexValidator('[0-9xX-]{10,20}', message = 'Please enter a valid ISBN.')]) validators=[RegexValidator('[0-9xX-]{10,20}',
message='Please enter a valid ISBN.')])
# would have to load in every conceivable course first # would have to load in every conceivable course first
#course = models.ForeignKey(Course) #course = models.ForeignKey(Course)
slug = RandomSlugField(length = 6) slug = RandomSlugField(length=6)
def get_listings(self): def get_listings(self):
# may be reason to resurrect active as an actual field, possibly can call function? isbn_listings = models.Q(isbn=self.isbn, sold=False, cancelled=False)
isbn_listings = models.Q( isbn = self.isbn, sold = False, cancelled = False ) return Listing.objects.filter(isbn_listings)
return Listing.objects.filter( isbn_listings )
# needs get_absolute_url
def get_absolute_url(self): def get_absolute_url(self):
return reverse('detail_lookout', kwargs = {'slug':self.slug}) return reverse('detail_lookout', kwargs={'slug': self.slug})
def __unicode__(self): def __unicode__(self):
return '%s %s' % (self.owner.user.username, self.isbn) return '%s %s' % (self.owner.user.username, self.isbn)
......
from django.conf.urls import patterns, include, url from django.conf.urls import patterns, url
from lookouts.views import DetailLookout, CreateLookout, DeleteLookout from lookouts.views import DetailLookout, CreateLookout, DeleteLookout
from lookouts.models import Lookout
urlpatterns = patterns('', urlpatterns = patterns('',
...@@ -13,5 +12,4 @@ urlpatterns = patterns('', ...@@ -13,5 +12,4 @@ urlpatterns = patterns('',
url(r'^(?P<slug>[\w-]+)/delete/$', url(r'^(?P<slug>[\w-]+)/delete/$',
DeleteLookout.as_view(), name='delete_lookout'), DeleteLookout.as_view(), name='delete_lookout'),
) )
from lookouts.models import Lookout from lookouts.models import Lookout
from lookouts.forms import LookoutForm from lookouts.forms import LookoutForm
from django.views.generic import CreateView, DetailView, UpdateView, DeleteView from django.views.generic import CreateView, DetailView, DeleteView
from braces.views import LoginRequiredMixin from braces.views import LoginRequiredMixin
from django.contrib.auth.models import User
from core.models import Student from core.models import Student
from django.http import Http404, HttpResponseForbidden from django.http import HttpResponseForbidden
### VIEWS ###
class CreateLookout(LoginRequiredMixin, CreateView): class CreateLookout(LoginRequiredMixin, CreateView):
model = Lookout model = Lookout
fields = ['isbn',] fields = ['isbn', ]
context_object_name = 'lookout' context_object_name = 'lookout'
template_name = 'create_lookout.html' template_name = 'create_lookout.html'
login_url = '/' login_url = '/'
...@@ -30,6 +29,7 @@ class CreateLookout(LoginRequiredMixin, CreateView): ...@@ -30,6 +29,7 @@ class CreateLookout(LoginRequiredMixin, CreateView):
return context return context
class DetailLookout(LoginRequiredMixin, DetailView): class DetailLookout(LoginRequiredMixin, DetailView):
model = Lookout model = Lookout
context_object_name = 'lookout' context_object_name = 'lookout'
...@@ -49,6 +49,7 @@ class DetailLookout(LoginRequiredMixin, DetailView): ...@@ -49,6 +49,7 @@ class DetailLookout(LoginRequiredMixin, DetailView):
# updating is not neccessary since it's just literally an isbn and a course # updating is not neccessary since it's just literally an isbn and a course
class DeleteLookout(LoginRequiredMixin, DeleteView): class DeleteLookout(LoginRequiredMixin, DeleteView):
model = Lookout model = Lookout
context_object_name = 'lookout' context_object_name = 'lookout'
......
# Django settings for bookshare project.
import os import os
BASE_DIR = os.path.dirname(os.path.dirname(__file__)) BASE_DIR = os.path.dirname(os.path.dirname(__file__))
...@@ -127,9 +125,9 @@ CAS_RESPONSE_CALLBACKS = ( ...@@ -127,9 +125,9 @@ CAS_RESPONSE_CALLBACKS = (
) )
HAYSTACK_CONNECTIONS = { HAYSTACK_CONNECTIONS = {
'default' : { 'default': {
'ENGINE' : 'haystack.backends.whoosh_backend.WhooshEngine', 'ENGINE': 'haystack.backends.whoosh_backend.WhooshEngine',
'PATH' : os.path.join(os.path.dirname(__file__), 'whoosh_index'), 'PATH': os.path.join(os.path.dirname(__file__), 'whoosh_index'),
}, },
} }
......
...@@ -15,7 +15,6 @@ handle404 = TemplateView.as_view(template_name="404.html") ...@@ -15,7 +15,6 @@ handle404 = TemplateView.as_view(template_name="404.html")
handle500 = TemplateView.as_view(template_name="500.html") handle500 = TemplateView.as_view(template_name="500.html")
urlpatterns = patterns('', urlpatterns = patterns('',
# app-level urls # app-level urls
url(r'^share/', include('trades.urls')), url(r'^share/', include('trades.urls')),
url(r'^student/', include('core.urls')), url(r'^student/', include('core.urls')),
...@@ -25,20 +24,22 @@ urlpatterns = patterns('', ...@@ -25,20 +24,22 @@ urlpatterns = patterns('',
url(r'^search/', include('haystack.urls'), name='search'), url(r'^search/', include('haystack.urls'), name='search'),
# site-wide pages # site-wide pages
url(r'^$', HomepageView.as_view(), name = 'homepage'), url(r'^$', HomepageView.as_view(), name='homepage'),
url(r'^charts/?$', ChartsView.as_view(), name = 'charts'), url(r'^charts/?$', ChartsView.as_view(), name='charts'),
### static pages ### # static pages
url(r'^about/?$', TemplateView.as_view(template_name='about.html'), name='about'), url(r'^about/?$', TemplateView.as_view(template_name='about.html'),
url(r'^privacy/?$', TemplateView.as_view(template_name='privacy.html'), name='privacy'), name='about'),
url(r'^privacy/opt-out/?$', 'core.views.privacy_opt_out', name='privacy_opt_out'), url(r'^privacy/?$', TemplateView.as_view(template_name='privacy.html'),
name='privacy'),
### user authentication ### # user authentication
url(r'^login/$', 'cas.views.login', name='login'), url(r'^login/$', 'cas.views.login', name='login'),
url(r'^logout/$', 'cas.views.logout', name='logout'), url(r'^logout/$', 'cas.views.logout', name='logout'),
#### admin pages #### # admin pages
url(r'^admin/doc/', include('django.contrib.admindocs.urls')), url(r'^admin/doc/', include('django.contrib.admindocs.urls')),
url(r'^admin/', include(admin.site.urls)), url(r'^admin/', include(admin.site.urls)),
# location of user-uploaded media files from settings.py
) + static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT) ) + static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT)
...@@ -10,15 +10,17 @@ from django.db.models import Sum ...@@ -10,15 +10,17 @@ from django.db.models import Sum
from collections import Counter from collections import Counter
class HomepageView(TemplateView): class HomepageView(TemplateView):
template_name = 'index.html' template_name = 'index.html'
def get_context_data(self, **kwargs): def get_context_data(self, **kwargs):
context = super(HomepageView, self).get_context_data(**kwargs) context = super(HomepageView, self).get_context_data(**kwargs)
if self.request.user.is_authenticated(): if self.request.user.is_authenticated():
context['lookouts'] = Lookout.objects.filter(owner=self.request.user.student) context['lookouts'] = Lookout.objects.filter(owner=self.request.user.student)
return context return context
class ChartsView(LoginRequiredMixin, TemplateView): class ChartsView(LoginRequiredMixin, TemplateView):
template_name = 'charts.html' template_name = 'charts.html'
...@@ -34,18 +36,21 @@ class ChartsView(LoginRequiredMixin, TemplateView): ...@@ -34,18 +36,21 @@ class ChartsView(LoginRequiredMixin, TemplateView):
for isbn in set(all_isbns): for isbn in set(all_isbns):
# only want sold listings (not cancelled is assumed) # only want sold listings (not cancelled is assumed)
listings = Listing.objects.exclude(sold=False).filter(isbn=isbn) listings = Listing.objects.exclude(sold=False).filter(isbn=isbn)
# make a list of all of that listing's final prices (assuming no Nones) # make list of all of that listing's final prices (assume no Nones)
listing_winning_bids = [listing.final_price() for listing in listings] listing_winning_bids = [listing.final_price() for listing in listings]
# add all those together # add all those together
listing_gross = sum(listing_winning_bids) listing_gross = sum(listing_winning_bids)
# make a tuple of the isbn and gross and add it to the list # make a tuple of the isbn and gross and add it to the list
grossing.append( (isbn, listing_gross) ) grossing.append((isbn, listing_gross))
total_proceeds = Listing.objects.aggregate(sum_price=Sum('winning_bid__price'))['sum_price']
context['most_popular'] = Counter(all_isbns).most_common(20) context['most_popular'] = Counter(all_isbns).most_common(20)
# sort by the second element of the tuple, descending # sort by the second element of the tuple, descending
context['highest_grossing'] = sorted(grossing, key=lambda li: li[1], reverse=True)[:20] context['highest_grossing'] = sorted(grossing, key=lambda li: li[1],
reverse=True)[:20]
context['total_listings'] = all_listings.count() context['total_listings'] = all_listings.count()
context['total_bids'] = Bid.objects.count() context['total_bids'] = Bid.objects.count()
context['total_students'] = Student.objects.count() context['total_students'] = Student.objects.count()
context['total_proceeds'] = Listing.objects.aggregate(sum_price=Sum('winning_bid__price'))['sum_price'] context['total_proceeds'] = total_proceeds
return context return context
from django.contrib import admin from django.contrib import admin
from .models import Bid, Listing, Flag from .models import Bid, Listing, Flag
# Register your models here.
@admin.register(Bid) @admin.register(Bid)
class BidAdmin(admin.ModelAdmin): class BidAdmin(admin.ModelAdmin):
list_display = ('id', 'created', 'modified', 'bidder', 'listing', 'price', 'text') list_display = ('id', 'created', 'modified', 'bidder', 'listing',
list_filter = ('created', 'modified', 'bidder', 'price') 'price', 'text')
list_filter = ('created', 'modified', 'bidder', 'price')
@admin.register(Listing) @admin.register(Listing)
class ListingAdmin(admin.ModelAdmin): class ListingAdmin(admin.ModelAdmin):
list_display = ('id', 'created', 'modified', 'title', 'author', 'isbn', 'year', 'edition', 'condition', 'description',\ list_display = ('id', 'created', 'modified', 'title', 'author', 'isbn',
'price', 'sold', 'cancelled', 'winning_bid', 'date_closed') 'year', 'edition', 'condition', 'description',
list_filter = ('created', 'modified', 'seller', 'condition', 'price', 'cancelled') 'price', 'sold', 'cancelled', 'winning_bid', 'date_closed')
list_filter = ('created', 'modified', 'seller', 'condition',
'price', 'cancelled')
# expand this later
admin.site.register(Flag) admin.site.register(Flag)
...@@ -6,34 +6,41 @@ from crispy_forms.bootstrap import AppendedPrependedText, FormActions ...@@ -6,34 +6,41 @@ from crispy_forms.bootstrap import AppendedPrependedText, FormActions
from trades.models import Listing, Bid, Flag from trades.models import Listing, Bid, Flag
class ListingForm( forms.ModelForm ):
class ListingForm(forms.ModelForm):
def __init__(self, *args, **kwargs): def __init__(self, *args, **kwargs):
self.helper = FormHelper() self.helper = FormHelper()
# bootstrap3 formatting # bootstrap3 formatting
self.helper.label_class='col-md-3 be-bold' self.helper.label_class = 'col-md-3 be-bold'
self.helper.field_class='col-md-9 bottom-padding' self.helper.field_class = 'col-md-9 bottom-padding'
self.helper.layout = Layout( self.helper.layout = Layout(
Fieldset("", Fieldset("",
Field('isbn', placeholder='0801884039'), Field('isbn', placeholder='0801884039'),
Field('title', placeholder='Squirrels: The Animal Answer Guide'), Field('title',
Field('author', placeholder='Richard W. Thorington, Jr., and Katie Ferrell'), placeholder='Squirrels: The Animal Answer Guide'),
'edition', Field('author',
Field('year', placeholder='2006'), placeholder='Richard W. Thorington, Jr., and Katie Ferrell'),
#'course', 'edition',
'condition', Field('year', placeholder='2006'),
'access_code', #'course',
AppendedPrependedText('price','$', '.00', placeholder="whole numbers"), 'condition',
'photo', 'access_code',
Field('description', placeholder='I would be willing to exchange this textbook for one that I need next semester. /// This is for Professor Smith\'s section ONLY. /// I can give you the workbook as well.'),