HarvardX / commerce / auctions / views.py
views.py
Raw
from django.contrib.auth import authenticate, login, logout
from django.db import IntegrityError
from django.http import HttpResponse, HttpResponseRedirect
from django.shortcuts import render
from django.urls import reverse
from django.forms import modelform_factory
from django.contrib.auth.decorators import login_required

from .models import User, Listing, Bid, Comment
from .forms import ListingForm, BidForm, CommentForm

def index(request):
    return render(request, "auctions/index.html", {
        "listings": Listing.objects.filter(active=True),
        "title": "Active"
    })


def login_view(request):
    if request.method == "POST":

        # Attempt to sign user in
        username = request.POST["username"]
        password = request.POST["password"]
        user = authenticate(request, username=username, password=password)

        # Check if authentication successful
        if user is not None:
            login(request, user)
            return HttpResponseRedirect(reverse("index"))
        else:
            return render(request, "auctions/login.html", {
                "message": "Invalid username and/or password."
            })
    else:
        return render(request, "auctions/login.html")


def logout_view(request):
    logout(request)
    return HttpResponseRedirect(reverse("index"))


def register(request):
    if request.method == "POST":
        username = request.POST["username"]
        email = request.POST["email"]

        # Ensure password matches confirmation
        password = request.POST["password"]
        confirmation = request.POST["confirmation"]
        if password != confirmation:
            return render(request, "auctions/register.html", {
                "message": "Passwords must match."
            })

        # Attempt to create new user
        try:
            user = User.objects.create_user(username, email, password)
            user.save()
        except IntegrityError:
            return render(request, "auctions/register.html", {
                "message": "Username already taken."
            })
        login(request, user)
        return HttpResponseRedirect(reverse("index"))
    else:
        return render(request, "auctions/register.html")

@login_required
def create(request):
    LForm = modelform_factory(Listing, form=ListingForm)

    if request.method == 'POST':
        form = LForm(request.POST, request.FILES)
        if form.is_valid():
            formlisting = form.save(commit=False)
            formlisting.user = User.objects.get(username=request.user.username)
            formlisting.save()
            return HttpResponseRedirect(reverse("index"))

    form = LForm()
    return render(request, 'auctions/create.html', {'listing_form': form})


def listing(request, listing_id):
    BForm = modelform_factory(Bid, form=BidForm)
    CForm = modelform_factory(Comment, form=CommentForm)
    message = None
    listing_item = Listing.objects.get(id=listing_id)
    user = request.user

    if user.is_authenticated: 
        watchlist = user.watchlist
        if listing_item in watchlist.all():
            in_watchlist = True
        else: 
            in_watchlist = False

        if request.user == listing_item.user:
            can_close = listing_item.active
        else:
            can_close = False
    else: 
        in_watchlist = None
        can_close = None

    if request.method == 'POST':
        if 'bid' in request.POST:
            form = BForm(request.POST, request.FILES)
            if form.is_valid():
                formbid = form.save(commit=False)
                formbid.user = User.objects.get(username=user.username)
                formbid.listing_item = Listing.objects.get(id=listing_id)
                try:
                    formbid.save()
                except: 
                    message = "Invalid Bid"
                    
        elif 'watch' in request.POST:
            if in_watchlist:
                watchlist.remove(listing_item)
                in_watchlist = False
            else:
                watchlist.add(listing_item)
                in_watchlist = True
        
        elif 'comment' in request.POST:
            form = CForm(request.POST, request.FILES)
            if form.is_valid():
                formcomment = form.save(commit=False)
                formcomment.user = User.objects.get(username=user.username)
                formcomment.listing_item = Listing.objects.get(id=listing_id)
                formcomment.save()
        
        elif 'close' in request.POST:
            listing_item.active = False
            listing_item.save()
            can_close = False
    
    if listing_item.max_bid is not None and listing_item.max_bid.user == user and not listing_item.active:
            message = "CONGRATULATIONS! YOU WON THE AUCTION!"

    bidding_form = BForm()
    comment_form = CForm()
    return render(request, 'auctions/listing.html', {
        "in_watchlist": in_watchlist,
        "can_close": can_close,
        "message": message,
        "listing": Listing.objects.get(id=listing_id),
        "bid_form": bidding_form['bid'],
        "comment_form": comment_form['comment'],
        "all_comments": Comment.objects.filter(listing_item=listing_item)})

@login_required
def watchlist(request):
    return render(request, "auctions/index.html", {
        "listings": request.user.watchlist.all(),
        "title": "Watchlist"
    })


def category_list(request):
    return render(request, "auctions/category_list.html", {
        "categories": Listing.Categories.choices
    })


def category_filter(request, cname):
    return render(request, "auctions/index.html", {
        "listings": Listing.objects.filter(category=cname, active=True),
        "title": cname
    })