views.py 2.5 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495
  1. # Copyright © 2023 Ingram Micro Inc. All rights reserved.
  2. from django.http import HttpResponseNotAllowed
  3. from django.shortcuts import get_object_or_404, redirect, render
  4. from django.views.decorators.http import require_http_methods
  5. from app.models import (
  6. Product,
  7. ProductType,
  8. Purchase,
  9. User,
  10. )
  11. def _render_page(request, **kwargs):
  12. return render(
  13. request,
  14. 'main.html',
  15. {
  16. 'users': User.objects.order_by('pk'),
  17. 'product_types': ProductType.objects.order_by('pk'),
  18. 'products': Product.objects.order_by('pk'),
  19. 'purchases': Purchase.objects.order_by('pk'),
  20. **kwargs,
  21. },
  22. )
  23. def render_main_page_if_get(f):
  24. def wrap(request, *args, **kwargs):
  25. if request.method == 'GET':
  26. return _render_page(request)
  27. if request.method != 'POST':
  28. return HttpResponseNotAllowed(['GET', 'POST'])
  29. return f(request, *args, **kwargs)
  30. return wrap
  31. @require_http_methods(['GET'])
  32. def main_view(request):
  33. return _render_page(request)
  34. @render_main_page_if_get
  35. def user_create_view(request):
  36. username = request.POST.get('username')
  37. if User.objects.filter(username=username).exists():
  38. return _render_page(request, user_error='Username must be unique')
  39. User.objects.create(username=request.POST.get('username'))
  40. return redirect('/')
  41. @render_main_page_if_get
  42. def user_update_view(request, pk):
  43. user = get_object_or_404(User, pk=pk)
  44. user.username += '1'
  45. user.save()
  46. return redirect('/')
  47. @render_main_page_if_get
  48. def user_delete_view(request, pk):
  49. user = get_object_or_404(User, pk=pk)
  50. user.delete()
  51. return redirect('/')
  52. @render_main_page_if_get
  53. def product_create_view(request):
  54. product_type_id = request.POST.get('product_type')
  55. name = request.POST.get('name')
  56. Product.objects.create(product_type_id=product_type_id, name=name)
  57. return redirect('/')
  58. @render_main_page_if_get
  59. def product_delete_view(request, pk):
  60. product = get_object_or_404(Product, pk=pk)
  61. product.delete()
  62. return redirect('/')
  63. @render_main_page_if_get
  64. def purchase_create_view(request):
  65. user_id = request.POST.get('user')
  66. product_id = request.POST.get('product')
  67. Purchase.objects.create(user_id=user_id, product_id=product_id)
  68. return redirect('/')
  69. @render_main_page_if_get
  70. def purchase_delete_view(request, pk):
  71. purchase = get_object_or_404(Purchase, pk=pk)
  72. purchase.delete()
  73. return redirect('/')