Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Nikki/delete vehicle #24

Merged
merged 13 commits into from
Dec 6, 2023
1 change: 0 additions & 1 deletion .gitignore
Original file line number Diff line number Diff line change
Expand Up @@ -14,7 +14,6 @@
**/client_secret.json
*creds*
*.dat
*password*
*.httr-oauth*

# Private Node Modules
Expand Down
11 changes: 11 additions & 0 deletions Pipfile
Original file line number Diff line number Diff line change
@@ -0,0 +1,11 @@
[[source]]
url = "https://pypi.org/simple"
verify_ssl = true
name = "pypi"

[packages]

[dev-packages]

[requires]
python_version = "3.12"
6 changes: 0 additions & 6 deletions backend/auction/admin.py
Original file line number Diff line number Diff line change
Expand Up @@ -15,12 +15,6 @@ class AuctionItemAdmin(admin.ModelAdmin):
search_fields = ("auction_id__name", "content_type__model")
list_filter = ("auction_id", "content_type")

def formfield_for_foreignkey(self, db_field, request, **kwargs):
# This method can be used to filter foreign key choices in the admin
if db_field.name == "auction_id":
kwargs["queryset"] = Auction.objects.filter(is_published=True)
return super().formfield_for_foreignkey(db_field, request, **kwargs)


# Register your models here
admin.site.register(Auction, AuctionAdmin)
Expand Down
2 changes: 1 addition & 1 deletion backend/auction/models.py
Original file line number Diff line number Diff line change
Expand Up @@ -21,7 +21,7 @@ def __str__(self):
return (
self.name
if self.name is not None
else "Auction at {start_date} to {end_date}"
else f"Auction from {self.start_date} to {self.end_date}"
)


Expand Down
11 changes: 5 additions & 6 deletions backend/bid/admin.py
Original file line number Diff line number Diff line change
@@ -1,7 +1,5 @@
from django.contrib import admin
from django.contrib.contenttypes.admin import GenericTabularInline

from auction.models import Auction
from django.contrib.contenttypes.models import ContentType

from .models import Bid

Expand All @@ -20,9 +18,10 @@ class BidAdmin(admin.ModelAdmin):
list_filter = ("auction", "bidder", "content_type")

def formfield_for_foreignkey(self, db_field, request, **kwargs):
# This method can be used to filter foreign key choices in the admin
if db_field.name == "auction":
kwargs["queryset"] = Auction.objects.filter(is_published=True)
if db_field.name == "content_type":
valid_models = ["vehicle", "equipment", "trailer"]
kwargs["queryset"] = ContentType.objects.filter(
model__in=valid_models)
return super().formfield_for_foreignkey(db_field, request, **kwargs)


Expand Down
17 changes: 17 additions & 0 deletions backend/bid/serializers.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,17 @@
from django.contrib.contenttypes.models import ContentType
from rest_framework import serializers

from .models import Bid


class BidSerializer(serializers.ModelSerializer):
unit_type = serializers.SerializerMethodField()

class Meta:
model = Bid
fields = ["id", "amount", "bidder", "auction", "unit_type", "object_id"]

def get_unit_type(self, obj):
if obj.content_type:
return obj.content_type.model
return None
8 changes: 7 additions & 1 deletion backend/bid/urls.py
Original file line number Diff line number Diff line change
@@ -1,4 +1,10 @@
from django.contrib import admin
from django.urls import include, path

urlpatterns = []
from .views import BidDetailApiView, BidListApiView

urlpatterns = [
path("", BidListApiView.as_view(), name="bid_list"),
path("<uuid:bid_id>/", BidDetailApiView.as_view(), name="bid_detail"),
]

107 changes: 105 additions & 2 deletions backend/bid/views.py
Original file line number Diff line number Diff line change
@@ -1,3 +1,106 @@
from django.shortcuts import render
from django.contrib.contenttypes.models import ContentType
from rest_framework import status
from rest_framework.generics import get_object_or_404
from rest_framework.response import Response
from rest_framework.views import APIView

# Create your views here.
from .models import Bid
from .serializers import BidSerializer
from auction.models import Auction
from user.models import Bidder


class BidListApiView(APIView):
def get(self, request, *args, **kwargs):
"""
Get all bids
"""
bids = Bid.objects.all()
serializer = BidSerializer(bids, many=True)
return Response(serializer.data, status=status.HTTP_200_OK)

"""
API endpoint to make a bid on an object
"""
def post(self, request, *args, **kwargs):
data = request.data
amount = data.get('amount')
bidder_id = data.get('bidder')
auction_id = data.get('auction')
content_type_name = data.get('content_type')
object_id = data.get('object_id')

# Check for missing fields
if not all([amount, bidder_id, auction_id, content_type_name, object_id]):
return Response({'error': 'Bid amount, bidder, auction, content type, and object ID are required.'},
status=status.HTTP_400_BAD_REQUEST)

# Validate ContentType
try:
content_type = ContentType.objects.get(model=content_type_name)
if content_type_name not in ['vehicle', 'equipment', 'trailer']:
raise ValueError('Invalid content type')
except (ContentType.DoesNotExist, ValueError):
return Response({'error': 'Invalid content type.'},
status=status.HTTP_400_BAD_REQUEST)

# Validate bidder and auction
try:
bidder = Bidder.objects.get(id=bidder_id)
auction = Auction.objects.get(id=auction_id)
except (Bidder.DoesNotExist, Auction.DoesNotExist):
return Response({'error': 'Invalid bidder or auction.'},
status=status.HTTP_400_BAD_REQUEST)

# Validate object_id
model_class = content_type.model_class()
try:
model_class.objects.get(id=object_id)
except model_class.DoesNotExist:
return Response({'error': 'Invalid object ID for the given content type.'},
status=status.HTTP_400_BAD_REQUEST)

content_type = ContentType.objects.get(model=data.get('content_type'))
highest_bid = Bid.objects.filter(content_type=content_type, object_id=data.get('object_id')).order_by('-amount').first()
if highest_bid and amount <= highest_bid.amount:
return Response({'error': 'Your bid must be higher than the current highest bid.'},
status=status.HTTP_400_BAD_REQUEST)

# Create the new bid
new_bid_data = {
'amount': amount,
'bidder': bidder_id,
'auction': auction_id,
'content_type': content_type.id,
'object_id': object_id
}
serializer = BidSerializer(data=new_bid_data)
if serializer.is_valid():
serializer.save()
return Response(serializer.data, status=status.HTTP_201_CREATED)

return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST)

class BidDetailApiView(APIView):
"""
Retrieve, update or delete an bid instance.
"""

def get(self, request, bid_id, format=None):
bid = get_object_or_404(Bid, id=bid_id)
serializer = BidSerializer(bid)
return Response(serializer.data)

def put(self, request, bid_id, format=None):
bid = get_object_or_404(Bid, id=bid_id)
serializer = BidSerializer(bid, data=request.data)
if serializer.is_valid():
serializer.save()
return Response(serializer.data)
return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST)

def delete(self, request, bid_id, format=None):
bid = get_object_or_404(Bid, id=bid_id)
bid.delete()
return Response(status=status.HTTP_204_NO_CONTENT)

1 change: 1 addition & 0 deletions backend/core/urls.py
Original file line number Diff line number Diff line change
Expand Up @@ -21,5 +21,6 @@
path("admin/", admin.site.urls),
path("api/v1/auctions/", include("auction.urls")),
path("api/v1/vehicles/", include("vehicle.urls")),
path("api/v1/bids/", include("bid.urls")),
path("api/v1/", include("user.urls")),
]
17 changes: 17 additions & 0 deletions backend/user/migrations/0003_remove_admin_password.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,17 @@
# Generated by Django 4.2.7 on 2023-11-28 01:40

from django.db import migrations


class Migration(migrations.Migration):

dependencies = [
('user', '0002_alter_bidder_bidder_number_alter_bidder_company_name'),
]

operations = [
migrations.RemoveField(
model_name='admin',
name='password',
),
]
21 changes: 19 additions & 2 deletions backend/vehicle/admin.py
Original file line number Diff line number Diff line change
@@ -1,4 +1,5 @@
from django.contrib import admin
from django.contrib.contenttypes.models import ContentType

from .models import (
Brand, Equipment, SavedUnits, Supplier, Trailer, Type, UnitImage, Vehicle)
Expand Down Expand Up @@ -75,10 +76,18 @@ class TrailerAdmin(admin.ModelAdmin):


class UnitImageAdmin(admin.ModelAdmin):
list_display = ("id", "image_url", "content_type", "object_id", "created_at")
list_display = ("id", "image_url", "content_type",
"object_id", "created_at")
search_fields = ("content_type__model",)
list_filter = ("content_type",)

def formfield_for_foreignkey(self, db_field, request, **kwargs):
if db_field.name == "content_type":
valid_models = ["vehicle", "equipment", "trailer"]
kwargs["queryset"] = ContentType.objects.filter(
model__in=valid_models)
return super().formfield_for_foreignkey(db_field, request, **kwargs)


class SavedUnitsAdmin(admin.ModelAdmin):
list_display = (
Expand All @@ -89,9 +98,17 @@ class SavedUnitsAdmin(admin.ModelAdmin):
"object_id",
"created_at",
)
search_fields = ("bidder_id__first_name", "auction_id__name", "content_type__model")
search_fields = ("bidder_id__first_name",
"auction_id__name", "content_type__model")
list_filter = ("auction_id", "bidder_id", "content_type")

def formfield_for_foreignkey(self, db_field, request, **kwargs):
if db_field.name == "content_type":
valid_models = ["vehicle", "equipment", "trailer"]
kwargs["queryset"] = ContentType.objects.filter(
model__in=valid_models)
return super().formfield_for_foreignkey(db_field, request, **kwargs)


# Register your models here
admin.site.register(Brand, BrandAdmin)
Expand Down
58 changes: 15 additions & 43 deletions backend/vehicle/migrations/0003_savedunits.py
Original file line number Diff line number Diff line change
@@ -1,61 +1,33 @@
# Generated by Django 4.2.6 on 2023-11-25 01:48
# Generated by Django 4.2.7 on 2023-11-28 01:40

from django.db import migrations, models
import django.db.models.deletion
import uuid


class Migration(migrations.Migration):

dependencies = [
("user", "0003_remove_admin_password"),
("contenttypes", "0002_remove_content_type_name"),
("auction", "0002_auction_cover_image_auction_is_published_and_more"),
(
"vehicle",
"0002_rename_hydraulic_cylindar_condition_equipment_hydraulic_cylinder_condition",
),
('user', '0003_remove_admin_password'),
('auction', '0002_auction_cover_image_auction_is_published_and_more'),
('contenttypes', '0002_remove_content_type_name'),
('vehicle', '0002_rename_hydraulic_cylindar_condition_equipment_hydraulic_cylinder_condition'),
]

operations = [
migrations.CreateModel(
name="SavedUnits",
name='SavedUnits',
fields=[
(
"id",
models.UUIDField(
default=uuid.uuid4,
editable=False,
primary_key=True,
serialize=False,
unique=True,
),
),
("created_at", models.DateTimeField(auto_now_add=True)),
("updated_at", models.DateTimeField(auto_now=True)),
("object_id", models.UUIDField()),
(
"auction_id",
models.ForeignKey(
on_delete=django.db.models.deletion.PROTECT,
to="auction.auction",
),
),
(
"bidder_id",
models.ForeignKey(
on_delete=django.db.models.deletion.PROTECT, to="user.bidder"
),
),
(
"content_type",
models.ForeignKey(
on_delete=django.db.models.deletion.PROTECT,
to="contenttypes.contenttype",
),
),
('id', models.UUIDField(default=uuid.uuid4, editable=False, primary_key=True, serialize=False, unique=True)),
('created_at', models.DateTimeField(auto_now_add=True)),
('updated_at', models.DateTimeField(auto_now=True)),
('object_id', models.UUIDField()),
('auction_id', models.ForeignKey(on_delete=django.db.models.deletion.PROTECT, to='auction.auction')),
('bidder_id', models.ForeignKey(on_delete=django.db.models.deletion.PROTECT, to='user.bidder')),
('content_type', models.ForeignKey(on_delete=django.db.models.deletion.PROTECT, to='contenttypes.contenttype')),
],
options={
"unique_together": {("auction_id", "bidder_id", "object_id")},
'unique_together': {('auction_id', 'bidder_id', 'object_id')},
},
),
]
9 changes: 8 additions & 1 deletion backend/vehicle/serializers.py
Original file line number Diff line number Diff line change
Expand Up @@ -88,6 +88,13 @@ class Meta:


class UnitImageSerializer(serializers.ModelSerializer):
unit_type = serializers.SerializerMethodField()

class Meta:
model = UnitImage
fields = ["id", "image_url", "content_type", "object_id", "content_object"]
fields = ["id", "image_url", "unit_type", "object_id"]

def get_unit_type(self, obj):
if obj.content_type:
return obj.content_type.model
return None
9 changes: 9 additions & 0 deletions backend/vehicle/views.py
Original file line number Diff line number Diff line change
Expand Up @@ -69,3 +69,12 @@ def get(self, request, vehicle_id, *args, **kwargs):
return Response(serializer.data, status=status.HTTP_200_OK)
except vehicle.DoesNotExist:
return Response(status=status.HTTP_404_NOT_FOUND)

def delete(self, request, vehicle_id, format=None):
"""
Delete specific vehicle
"""

vehicle = get_object_or_404(Vehicle, id=vehicle_id)
vehicle.delete()
return Response(status=status.HTTP_204_NO_CONTENT)