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
import requests
def pfinfo(u_name):
pf_url = "http://peoplefinder.b1.akshaykarthik.com/"
url = str(pf_url) + "basic/all/" + str(u_name)
......@@ -18,8 +19,8 @@ def pfinfo(u_name):
name = pf_json['results'][0]['name']
return name.split(',')
def create_user(tree):
def create_user(tree):
username = tree[0][0].text
print 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
from django.contrib.auth.models import User
from autoslug import AutoSlugField
from model_utils.models import TimeStampedModel
from django.core.validators import RegexValidator
#from django.core.validators import RegexValidator
from django.core.urlresolvers import reverse
class Student(TimeStampedModel):
user = models.OneToOneField(User)
# django user includes username, password, first name, and last name
# implement ratings later
# rating = models.IntegerField(null=True,default=0)
# implement ratings later
#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):
return reverse('profile', kwargs = {'slug':self.slug})
return reverse('profile', kwargs={'slug': self.slug})
def __unicode__(self):
return '%s' % self.user.username
class Course(TimeStampedModel):
name = models.CharField(max_length = 255)
department = models.CharField(max_length = 255)
departmentAbbreviation = models.CharField(max_length = 4)
#number = models.CharField(max_length=255, validators=RegexValidator('[0-9]{3,}'))
number = models.CharField(max_length = 3)
name = models.CharField(max_length=255)
department = models.CharField(max_length=255)
departmentAbbreviation = models.CharField(max_length=4)
#number = models.CharField(max_length=255,
#validators=RegexValidator('[0-9]{3,}'))
number = models.CharField(max_length=3)
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.models import Student
urlpatterns = patterns('',
url(r'^(?P<slug>[\w-]+)/$',
......
......@@ -5,27 +5,7 @@ from core.models import Student
from lookouts.models import Lookout
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):
model = Student
template_name = 'profile.html'
......
from django.contrib import admin
from .models import Lookout
@admin.register(Lookout)
class LookoutAdmin(admin.ModelAdmin):
list_display = ('id', 'created', 'modified', 'owner', 'isbn')
......
......@@ -4,23 +4,27 @@ from crispy_forms.helper import FormHelper
from crispy_forms.layout import Button, Submit, Layout, Fieldset, HTML, Field
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):
self.helper = FormHelper()
self.helper.label_class='col-md-2 col-md-offset-1 text-center be-bold'
self.helper.field_class='col-sm-8'
self.helper.label_class = 'col-md-2 col-md-offset-1 text-center be-bold'
self.helper.field_class = 'col-sm-8'
self.helper.layout = Layout(
Fieldset("",
Field('isbn', placeholder='0801884039'),
HTML("""<hr/ >"""),
FormActions(
Submit('submit', 'Submit', css_class='btn-primary'),
Button('cancel', 'Never Mind', css_class="btn-default", onclick="history.back()")),
FormActions(Submit('submit', 'Submit',
css_class='btn-primary'),
Button('cancel', 'Never Mind',
css_class="btn-default",
onclick="history.back()")
),
),
)
......@@ -29,4 +33,3 @@ class LookoutForm( forms.ModelForm ):
class Meta:
model = Lookout
from django.db import models
from trades.models import Listing
from core.models import Student, Course
from django.conf import settings
from core.models import Student
from django.core.urlresolvers import reverse
from django.core.validators import RegexValidator
from model_utils.models import TimeStampedModel
from randomslugfield import RandomSlugField
class Lookout(TimeStampedModel):
owner = models.ForeignKey(Student)
isbn = models.CharField(
max_length = 20,
validators = [RegexValidator('[0-9xX-]{10,20}', message = 'Please enter a valid ISBN.')])
max_length=20,
validators=[RegexValidator('[0-9xX-]{10,20}',
message='Please enter a valid ISBN.')])
# would have to load in every conceivable course first
#course = models.ForeignKey(Course)
slug = RandomSlugField(length = 6)
slug = RandomSlugField(length=6)
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 )
return Listing.objects.filter( isbn_listings )
isbn_listings = models.Q(isbn=self.isbn, sold=False, cancelled=False)
return Listing.objects.filter(isbn_listings)
# needs get_absolute_url
def get_absolute_url(self):
return reverse('detail_lookout', kwargs = {'slug':self.slug})
return reverse('detail_lookout', kwargs={'slug': self.slug})
def __unicode__(self):
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.models import Lookout
urlpatterns = patterns('',
......@@ -13,5 +12,4 @@ urlpatterns = patterns('',
url(r'^(?P<slug>[\w-]+)/delete/$',
DeleteLookout.as_view(), name='delete_lookout'),
)
from lookouts.models import Lookout
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 django.contrib.auth.models import User
from core.models import Student
from django.http import Http404, HttpResponseForbidden
from django.http import HttpResponseForbidden
### VIEWS ###
class CreateLookout(LoginRequiredMixin, CreateView):
model = Lookout
fields = ['isbn',]
fields = ['isbn', ]
context_object_name = 'lookout'
template_name = 'create_lookout.html'
login_url = '/'
......@@ -30,6 +29,7 @@ class CreateLookout(LoginRequiredMixin, CreateView):
return context
class DetailLookout(LoginRequiredMixin, DetailView):
model = Lookout
context_object_name = 'lookout'
......@@ -49,6 +49,7 @@ class DetailLookout(LoginRequiredMixin, DetailView):
# updating is not neccessary since it's just literally an isbn and a course
class DeleteLookout(LoginRequiredMixin, DeleteView):
model = Lookout
context_object_name = 'lookout'
......
# Django settings for bookshare project.
import os
BASE_DIR = os.path.dirname(os.path.dirname(__file__))
......@@ -127,9 +125,9 @@ CAS_RESPONSE_CALLBACKS = (
)
HAYSTACK_CONNECTIONS = {
'default' : {
'ENGINE' : 'haystack.backends.whoosh_backend.WhooshEngine',
'PATH' : os.path.join(os.path.dirname(__file__), 'whoosh_index'),
'default': {
'ENGINE': 'haystack.backends.whoosh_backend.WhooshEngine',
'PATH': os.path.join(os.path.dirname(__file__), 'whoosh_index'),
},
}
......
......@@ -15,7 +15,6 @@ handle404 = TemplateView.as_view(template_name="404.html")
handle500 = TemplateView.as_view(template_name="500.html")
urlpatterns = patterns('',
# app-level urls
url(r'^share/', include('trades.urls')),
url(r'^student/', include('core.urls')),
......@@ -25,20 +24,22 @@ urlpatterns = patterns('',
url(r'^search/', include('haystack.urls'), name='search'),
# site-wide pages
url(r'^$', HomepageView.as_view(), name = 'homepage'),
url(r'^charts/?$', ChartsView.as_view(), name = 'charts'),
url(r'^$', HomepageView.as_view(), name='homepage'),
url(r'^charts/?$', ChartsView.as_view(), name='charts'),
### static pages ###
url(r'^about/?$', TemplateView.as_view(template_name='about.html'), name='about'),
url(r'^privacy/?$', TemplateView.as_view(template_name='privacy.html'), name='privacy'),
url(r'^privacy/opt-out/?$', 'core.views.privacy_opt_out', name='privacy_opt_out'),
# static pages
url(r'^about/?$', TemplateView.as_view(template_name='about.html'),
name='about'),
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'^logout/$', 'cas.views.logout', name='logout'),
#### admin pages ####
# admin pages
url(r'^admin/doc/', include('django.contrib.admindocs.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)
......@@ -10,6 +10,7 @@ from django.db.models import Sum
from collections import Counter
class HomepageView(TemplateView):
template_name = 'index.html'
......@@ -19,6 +20,7 @@ class HomepageView(TemplateView):
context['lookouts'] = Lookout.objects.filter(owner=self.request.user.student)
return context
class ChartsView(LoginRequiredMixin, TemplateView):
template_name = 'charts.html'
......@@ -34,18 +36,21 @@ class ChartsView(LoginRequiredMixin, TemplateView):
for isbn in set(all_isbns):
# only want sold listings (not cancelled is assumed)
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]
# add all those together
listing_gross = sum(listing_winning_bids)
# 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)
# 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_bids'] = Bid.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
from django.contrib import admin
from .models import Bid, Listing, Flag
# Register your models here.
@admin.register(Bid)
class BidAdmin(admin.ModelAdmin):
list_display = ('id', 'created', 'modified', 'bidder', 'listing', 'price', 'text')
list_display = ('id', 'created', 'modified', 'bidder', 'listing',
'price', 'text')
list_filter = ('created', 'modified', 'bidder', 'price')
@admin.register(Listing)
class ListingAdmin(admin.ModelAdmin):
list_display = ('id', 'created', 'modified', 'title', 'author', 'isbn', 'year', 'edition', 'condition', 'description',\
list_display = ('id', 'created', 'modified', 'title', 'author', 'isbn',
'year', 'edition', 'condition', 'description',
'price', 'sold', 'cancelled', 'winning_bid', 'date_closed')
list_filter = ('created', 'modified', 'seller', 'condition', 'price', 'cancelled')
list_filter = ('created', 'modified', 'seller', 'condition',
'price', 'cancelled')
# expand this later
admin.site.register(Flag)
......@@ -6,32 +6,39 @@ from crispy_forms.bootstrap import AppendedPrependedText, FormActions
from trades.models import Listing, Bid, Flag
class ListingForm( forms.ModelForm ):
class ListingForm(forms.ModelForm):
def __init__(self, *args, **kwargs):
self.helper = FormHelper()
# bootstrap3 formatting
self.helper.label_class='col-md-3 be-bold'
self.helper.field_class='col-md-9 bottom-padding'
self.helper.label_class = 'col-md-3 be-bold'
self.helper.field_class = 'col-md-9 bottom-padding'
self.helper.layout = Layout(
Fieldset("",
Field('isbn', placeholder='0801884039'),
Field('title', placeholder='Squirrels: The Animal Answer Guide'),
Field('author', placeholder='Richard W. Thorington, Jr., and Katie Ferrell'),
Field('title',
placeholder='Squirrels: The Animal Answer Guide'),
Field('author',
placeholder='Richard W. Thorington, Jr., and Katie Ferrell'),
'edition',
Field('year', placeholder='2006'),
#'course',
'condition',
'access_code',
AppendedPrependedText('price','$', '.00', placeholder="whole numbers"),
AppendedPrependedText('price', '$', '.00',
placeholder="whole numbers"),
'photo',
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.'),
FormActions(
Submit('submit', 'Create', css_class='btn-primary'),
Button('cancel', 'Never Mind', css_class='btn-default', onclick="history.back()")),
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.'),
FormActions(Submit('submit', 'Create',
css_class='btn-primary'),
Button('cancel', 'Never Mind',
css_class='btn-default',
onclick="history.back()")
),
),
)
......@@ -43,49 +50,55 @@ class ListingForm( forms.ModelForm ):
class Meta:
model = Listing
class BidForm( forms.ModelForm ):
class BidForm(forms.ModelForm):
def __init__(self, *args, **kwargs):
self.helper = FormHelper()
# bootstrap3 formatting
self.helper.label_class='be-bold col-md-2'
self.helper.field_class='col-md-10'
self.helper.label_class = 'be-bold col-md-2'
self.helper.field_class = 'col-md-10'
self.helper.layout = Layout(
Fieldset("",
'listing',
HTML("<div class='col-md-4'>"),
AppendedPrependedText('price','$', '.00', placeholder="whole numbers"),
AppendedPrependedText('price', '$', '.00',
placeholder="whole numbers"),
HTML("</div><div class='col-md-6'>"),
'text',
HTML("</div><div class='col-md-2'>"),
FormActions(Submit('submit', 'Submit', css_class='btn-primary')),
FormActions(Submit('submit', 'Submit',
css_class='btn-primary')
),
HTML("</div>"),
),
)
super(BidForm, self).__init__(*args, **kwargs)
self.fields['text'].label = "Comments"
class Meta:
model = Bid
class FlagForm( forms.ModelForm ):
class FlagForm(forms.ModelForm):
def __init__(self, *args, **kwargs):
self.helper = FormHelper()
# bootstrap3 formatting
self.helper.label_class='be-bold'
self.helper.label_class = 'be-bold'
self.helper.layout = Layout(
Fieldset("",
'reason',
HTML("""<hr/ >"""),
FormActions(
Submit('submit', 'Create', css_class='btn-primary'),
Button('cancel', 'Never Mind', css_class='btn-default', onclick="history.back()")),
FormActions(Submit('submit', 'Create',
css_class='btn-primary'),
Button('cancel', 'Never Mind',
css_class='btn-default',
onclick="history.back()")
),
),
)
super(FlagForm, self).__init__(*args, **kwargs)
......@@ -95,83 +108,36 @@ class FlagForm( forms.ModelForm ):
#class EditListingForm( forms.ModelForm ):
class SellListingForm( forms.ModelForm ):
class SellListingForm(forms.ModelForm):
def __init__(self, *args, **kwargs):
self.helper = FormHelper()
self.helper.label_class='be-bold'
self.helper.label_class = 'be-bold'
self.helper.layout = Layout(
Fieldset("",
'winning_bid',
HTML("""<hr/ >"""),
HTML("""<strong>Your Email to Your Bidder</strong>"""),
HTML("""<div class="well"><em><p>Hey there!</p><p>Seller {{ listing.seller.user.first_name }} {{ listing.seller.user.last_name }} has picked your bid for {{ listing.title }} on SRCT Bookshare. They're the cc'ed email address-- {{ listing.seller.user.email }}.</p><p>Watch your email to arrange all the final touches to get your book.</p></em>"""),
Field('email_message', placeholder='Do you want to meet tomorrow by the JC Info Desk at 4?'),
Field('email_message',
placeholder='Do you want to meet tomorrow by the JC Info Desk at 4?'),
HTML("""<em><p>Thanks for using SRCT Bookshare!</p><p>Mason SRCT</p></em></div>"""),
HTML("""<hr/ >"""),
FormActions(
Submit('submit', 'Email and Sell', css_class='btn-primary'),
Button('cancel', 'Never Mind', css_class='btn-default', onclick="history.back()")),
FormActions(Submit('submit', 'Email and Sell',
css_class='btn-primary'),
Button('cancel', 'Never Mind',
css_class='btn-default',
onclick="history.back()")
),
),
)
super(SellListingForm, self).__init__(*args, **kwargs)
self.fields['email_message'].label = "Custom Message"
self.fields['winning_bid'].required = True
class Meta:
model = Listing
# not necessary
class UnSellListingForm( forms.ModelForm ):
def __init__(self, *args, **kwargs):
self.helper = FormHelper()
self.helper.layout = Layout(
Fieldset("",
FormActions(
Submit('submit', 'Back on the Market', css_class='btn-primary'),
Button('cancel', 'Never Mind', css_class='btn-default', onclick="history.back()")),
),
)
super(UnSellListingForm, self).__init__(*args, **kwargs)
class Meta:
model = Listing
# not neccessary
class CancelListingForm( forms.ModelForm ):
def __init__(self, *args, **kwargs):
self.helper = FormHelper()
self.helper.layout = Layout(
Fieldset("",
FormActions(
Submit('submit', 'Cancel Your Listing', css_class='btn-primary'),
Button('cancel', 'Never Mind', css_class='btn-default', onclick="history.back()")),
),
)
super(CancelListingForm, self).__init__(*args, **kwargs)
class Meta:
model = Listing
# not neccesary
class ReopenListingForm( forms.ModelForm ):