Esempio n. 1
0
def edit(request):
    # TODO: Clean up this messy method.

    # Require login.
    if not (request.user.is_authenticated()):
        return redirect_to_login(request.get_full_path())

    recs = Recommendation.objects.filter(user=request.user)
    category_types = CategoryType.objects.all()
    all_categories = Category.objects.all()
    context = {
        'recs': recs,
        'category_types': category_types,
        'cat_check_htmls': []
    }
    books_in_c = {}
    for c in all_categories:
        books_in_c[c] = [r for r in recs.filter(book__category=c) \
                                        .distinct()]
    print >> sys.stderr, repr(books_in_c)
    for rec in recs:
        b = ''
        for ct in category_types:
            b += '<p style="font-weight: bold">%s</p>' % ct.description
            for c in ct.get_categories():
                b += '<input type="checkbox" name="{0}" id="{1}{0}"'.format(
                    c.slug, rec.id)
                if rec in books_in_c[c]:
                    b += 'checked="checked" '
                b += '/><label for="%d%s">%s</label><br />' % (rec.id, c.slug,
                                                               c.name)
        context['cat_check_htmls'].append(b)

    if 'keywords' in request.GET:
        context['results'] = gbooks.search(request.GET['keywords'])
    elif 'gid' in request.POST:
        if 'action' in request.POST:
            b = Book.objects.get(gid=request.POST['gid'])
            r = Recommendation.objects.get(user=request.user, book=b)
            if request.POST['action'] == 'update':
                for c in Category.objects.all():
                    if c.slug in request.POST:
                        c.books.add(b)
                    else:
                        c.books.remove(b)
                r.comment = request.POST['blurb']
                r.save()
                print >> sys.stderr, repr(request.POST)
            elif request.POST['action'] == 'delete':
                if len(Recommendation.objects.filter(book=r.book)) == 1:
                    os.unlink(
                        os.path.join('/opt/infxbooklist/bookcovers/',
                                     r.book.cover_image))
                    r.book.delete()
                r.delete()
        else:
            # Make the book if doesn't exist, update if does
            gb = gbooks.get(request.POST['gid'])
            b = Book.objects.get_or_create(gid=gb.gid)[0]
            b.title = gb.title
            b.authors = gb.authors
            b.isbn = gb.isbn
            try:
                # Download the thumbnail image from Google
                req = urllib2.Request(gb.thumbnail_url)
                req.add_header("User-Agent", "Mozilla")
                try:
                    # TODO: These images are never deleted. Write a cron script to
                    #       scrub the dir of images that tables no longer reference.
                    image_link = urllib2.urlopen(req)
                    img_data = image_link.read()
                    image_link.close()
                    rand_fn = datetime.datetime.utcnow().isoformat(
                    ) + '__' + str(random.randint(0, sys.maxint))
                    rand_pth = os.path.join('/opt/infxbooklist/bookcovers',
                                            rand_fn)
                    with open(rand_pth, 'w') as f:
                        f.write(img_data)
                    b.cover_image = rand_fn
                except Exception, e:
                    print >> sys.stderr, "Tried to save thumbnail, but got exception:", repr(
                        e)
            finally:
                b.save()
            # Create a Recommendation, which links User and Book
            Recommendation(user=request.user, book=b).save()
        # Redirect to avoid refresh issues
        return HttpResponseRedirect("/edit/")
    # Go.
    return render_to_response('edit.html', context)
Esempio n. 2
0
def edit(request):
    # Require login.
    if not (request.user.is_authenticated()):
        return redirect_to_login(request.get_full_path())

    recs = Recommendation.objects.filter(user=request.user).order_by('-added')
    category_types = CategoryType.objects.all()
    all_categories = Category.objects.all()
    context = {
        'recs': recs,
        'category_types': category_types,
        'user': request.user,
        'cat_check_htmls': []
    }
    books_in_c = {}
    for c in all_categories:
        books_in_c[c] = [r for r in recs.filter(book__category=c) \
                                              .distinct()]
    print >> sys.stderr, repr(books_in_c)
    for rec in recs:
        b = ''
        for ct in category_types:
            b += '<h4>%s</h4>' % ct.description
            for c in ct.get_categories():
                b += '<span class="checkbox-container"><input class="form-update-checkbox-' + rec.book.gid + '" type="checkbox" name="{0}" id="{1}{0}"'.format(
                    c.slug, rec.id)
                if rec in books_in_c[c]:
                    b += 'checked="checked" '
                b += '/><label for="%d%s">%s</label></span>' % (rec.id, c.slug,
                                                                c.name)
        context['cat_check_htmls'].insert(0, b)

    if 'keywords' in request.GET:
        context['results'] = gbooks.search(request.GET['keywords'])
    elif 'gid' in request.POST:
        if 'action' in request.POST:
            if request.POST['action'] == 'update':
                b = Book.objects.get(gid=request.POST['gid'])
                r = Recommendation.objects.get(user=request.user, book=b)
                for c in Category.objects.all():
                    if c.slug in request.POST:
                        c.books.add(b)
                    else:
                        c.books.remove(b)
                r.comment = request.POST['blurb']
                r.save()
                print >> sys.stderr, repr(request.POST)
            elif request.POST['action'] == 'delete':
                b = Book.objects.get(gid=request.POST['gid'])
                r = Recommendation.objects.get(user=request.user, book=b)
                if len(Recommendation.objects.filter(book=r.book)) == 1:
                    os.unlink(os.path.join(BOOK_COVERS, r.book.cover_image))
                    r.book.delete()
                r.delete()
            # Redirect to avoid refresh issues
            return HttpResponseRedirect("/edit/")
    elif 'profileaction' in request.POST:
        if request.POST['profileaction'] == 'update':
            profile_form = ProfileForm(request.POST,
                                       request.FILES,
                                       instance=request.user.profile)

            request.user.first_name = request.POST['first_name']
            request.user.last_name = request.POST['last_name']
            request.user.email = request.POST['email']
            request.user.save()

            if profile_form.is_valid():
                profile_form.save()
                return HttpResponseRedirect('/edit/')

            else:
                profile_form = ProfileForm(instance=request.user.profile)
                return HttpResponseRedirect('/edit/')

            #return render_to_response('edit.html', { 'form' : profile_form })
    profile_form = ProfileForm(instance=request.user.profile)
    # Go.
    context['form'] = profile_form
    if request.user.profile.picture:
        context['pictureurl'] = request.user.profile.picture.url
    context['siteurl'] = request.user.profile.site
    context['firstname'] = request.user.first_name
    context['lastname'] = request.user.last_name
    context['email'] = request.user.email
    context['sitename'] = settings.SITE_NAME
    return render_to_response('edit.html',
                              context,
                              context_instance=RequestContext(request))
Esempio n. 3
0
def edit(request):
    # TODO: Clean up this messy method.
    
    # Require login.
    if not (request.user.is_authenticated()):
        return redirect_to_login(request.get_full_path())

    recs = Recommendation.objects.filter(user=request.user)
    category_types = CategoryType.objects.all()
    all_categories = Category.objects.all()
    context = {'recs': recs,
               'category_types': category_types,
               'cat_check_htmls': []}
    books_in_c = {}
    for c in all_categories:
        books_in_c[c] = [r for r in recs.filter(book__category=c) \
                                        .distinct()]
    print >>sys.stderr, repr(books_in_c)
    for rec in recs:
	    b = ''
	    for ct in category_types:
	        b += '<p style="font-weight: bold">%s</p>' % ct.description
	        for c in ct.get_categories():
	            b += '<input type="checkbox" name="{0}" id="{1}{0}"'.format(c.slug, rec.id)
	            if rec in books_in_c[c]:
	                b += 'checked="checked" '
	            b += '/><label for="%d%s">%s</label><br />' % (rec.id, c.slug, c.name)
	    context['cat_check_htmls'].append(b)
             
    if 'keywords' in request.GET:
        context['results'] = gbooks.search(request.GET['keywords'])
    elif 'gid' in request.POST:
        if 'action' in request.POST:
            b = Book.objects.get(gid=request.POST['gid'])
            r = Recommendation.objects.get(user=request.user,
                                           book=b)
            if request.POST['action'] == 'update':
                for c in Category.objects.all():
                    if c.slug in request.POST:
                        c.books.add(b)
                    else:
                        c.books.remove(b)
                r.comment = request.POST['blurb']
                r.save()
                print >>sys.stderr, repr(request.POST)
            elif request.POST['action'] == 'delete':
                if len(Recommendation.objects.filter(book=r.book)) == 1:
                    os.unlink(os.path.join('/opt/infxbooklist/bookcovers/', r.book.cover_image))
                    r.book.delete()
                r.delete()
        else:
            # Make the book if doesn't exist, update if does
            gb = gbooks.get(request.POST['gid'])
            b = Book.objects.get_or_create(gid=gb.gid)[0]
            b.title = gb.title
            b.authors = gb.authors
            b.isbn = gb.isbn
            try:
                # Download the thumbnail image from Google
                req = urllib2.Request(gb.thumbnail_url)
                req.add_header("User-Agent", "Mozilla")
                try:
                    # TODO: These images are never deleted. Write a cron script to
                    #       scrub the dir of images that tables no longer reference.
                    image_link = urllib2.urlopen(req)
                    img_data = image_link.read()
                    image_link.close()
                    rand_fn = datetime.datetime.utcnow().isoformat()+'__'+str(random.randint(0, sys.maxint))
                    rand_pth = os.path.join('/opt/infxbooklist/bookcovers', rand_fn)
                    with open(rand_pth, 'w') as f:
                        f.write(img_data)
                    b.cover_image = rand_fn
                except Exception, e:
                    print >>sys.stderr, "Tried to save thumbnail, but got exception:", repr(e)
            finally:
                b.save()
            # Create a Recommendation, which links User and Book
            Recommendation(user=request.user, book=b).save()
        # Redirect to avoid refresh issues
        return HttpResponseRedirect("/edit/")
    # Go.
    return render_to_response('edit.html', context)
Esempio n. 4
0
def edit(request):    
	# Require login.
	if not (request.user.is_authenticated()):
		return redirect_to_login(request.get_full_path())
			
	recs = Recommendation.objects.filter(user=request.user).order_by('-added')
	category_types = CategoryType.objects.all()
	all_categories = Category.objects.all()
	context = {'recs': recs,
               'category_types': category_types,
               'user': request.user,
               'cat_check_htmls': []}
	books_in_c = {}
	for c in all_categories:
		books_in_c[c] = [r for r in recs.filter(book__category=c) \
                                        .distinct()]
	print >>sys.stderr, repr(books_in_c)
	for rec in recs:
		b = ''
		for ct in category_types:
			b += '<h4>%s</h4>' % ct.description
			for c in ct.get_categories():
				b += '<span class="checkbox-container"><input class="form-update-checkbox-' + rec.book.gid +'" type="checkbox" name="{0}" id="{1}{0}"'.format(c.slug, rec.id)
				if rec in books_in_c[c]:
					b += 'checked="checked" '
				b += '/><label for="%d%s">%s</label></span>' % (rec.id, c.slug, c.name)
		context['cat_check_htmls'].insert(0,b)
             
	if 'keywords' in request.GET:
		context['results'] = gbooks.search(request.GET['keywords'])
	elif 'gid' in request.POST:
		if 'action' in request.POST:
			if request.POST['action'] == 'update':
				b = Book.objects.get(gid=request.POST['gid'])
				r = Recommendation.objects.get(user=request.user,
											   book=b)
				for c in Category.objects.all():
					if c.slug in request.POST:
						c.books.add(b)
					else:
						c.books.remove(b)
				r.comment = request.POST['blurb']
				r.save()
				print >>sys.stderr, repr(request.POST)
			elif request.POST['action'] == 'delete':
				b = Book.objects.get(gid=request.POST['gid'])
				r = Recommendation.objects.get(user=request.user,
											   book=b)
				if len(Recommendation.objects.filter(book=r.book)) == 1:
					os.unlink(os.path.join(BOOK_COVERS, r.book.cover_image))
					r.book.delete()
				r.delete()
			# Redirect to avoid refresh issues
			return HttpResponseRedirect("/edit/")
	elif 'profileaction' in request.POST:
		if request.POST['profileaction'] == 'update':
			profile_form = ProfileForm(request.POST, request.FILES, instance=request.user.profile)
			
			request.user.first_name=request.POST['first_name']
			request.user.last_name=request.POST['last_name']
			request.user.email=request.POST['email']
			request.user.save()

			if profile_form.is_valid():
				profile_form.save()
				return HttpResponseRedirect('/edit/')

			else:
				profile_form = ProfileForm(instance=request.user.profile)
				return HttpResponseRedirect('/edit/')

			#return render_to_response('edit.html', { 'form' : profile_form })
	profile_form = ProfileForm(instance=request.user.profile)
	# Go.
	context['form'] = profile_form
	if request.user.profile.picture:
		context['pictureurl'] = request.user.profile.picture.url
	context['siteurl'] = request.user.profile.site
	context['firstname'] = request.user.first_name
	context['lastname'] = request.user.last_name
	context['email'] = request.user.email
	context['sitename'] = settings.SITE_NAME
	return render_to_response('edit.html', context, context_instance=RequestContext(request))