67 lines
2.4 KiB
Python
67 lines
2.4 KiB
Python
from django.shortcuts import render, redirect
|
|
from django.contrib import messages
|
|
from django.contrib.auth.mixins import LoginRequiredMixin
|
|
from django.urls import reverse_lazy
|
|
from django.views.generic import ListView, CreateView, DeleteView
|
|
|
|
from .models import FriendCode
|
|
from .forms import FriendCodeForm
|
|
|
|
|
|
class ListFriendCodesView(LoginRequiredMixin, ListView):
|
|
"""
|
|
Display the current user's friend codes.
|
|
"""
|
|
model = FriendCode
|
|
template_name = "friend_codes/list_friend_codes.html"
|
|
context_object_name = "friend_codes"
|
|
|
|
def get_queryset(self):
|
|
# Only display friend codes that belong to the current user.
|
|
return self.request.user.friend_codes.all()
|
|
|
|
|
|
class AddFriendCodeView(LoginRequiredMixin, CreateView):
|
|
"""
|
|
Add a new friend code for the current user.
|
|
"""
|
|
model = FriendCode
|
|
form_class = FriendCodeForm
|
|
template_name = "friend_codes/add_friend_code.html"
|
|
success_url = reverse_lazy('list_friend_codes')
|
|
|
|
def form_valid(self, form):
|
|
# Set the friend code's user to the current user before saving.
|
|
form.instance.user = self.request.user
|
|
messages.success(self.request, "Friend code added successfully.")
|
|
return super().form_valid(form)
|
|
|
|
|
|
class DeleteFriendCodeView(LoginRequiredMixin, DeleteView):
|
|
"""
|
|
Remove an existing friend code.
|
|
The friend code will not be removed if it is referenced by trade offers via
|
|
either the initiated_by or accepted_by relationships.
|
|
"""
|
|
model = FriendCode
|
|
template_name = "friend_codes/confirm_delete_friend_code.html"
|
|
context_object_name = "friend_code"
|
|
success_url = reverse_lazy('list_friend_codes')
|
|
|
|
def get_queryset(self):
|
|
# Ensure the friend code belongs to the current user.
|
|
return FriendCode.objects.filter(user=self.request.user)
|
|
|
|
def post(self, request, *args, **kwargs):
|
|
self.object = self.get_object()
|
|
# Check if there are any trade offers associated with this friend code.
|
|
if self.object.initiated_by.exists() or self.object.accepted_by.exists():
|
|
messages.error(
|
|
request,
|
|
"Cannot remove this friend code because there are existing trade offers associated with it."
|
|
)
|
|
return redirect(self.success_url)
|
|
else:
|
|
self.object.delete()
|
|
messages.success(request, "Friend code removed successfully.")
|
|
return redirect(self.success_url)
|