views.py 2.1 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061
  1. from django.shortcuts import render, redirect, get_object_or_404
  2. from django.contrib.auth.models import User
  3. from django.contrib.auth.decorators import login_required
  4. from django.core.exceptions import PermissionDenied
  5. from .models import Bookmark
  6. from .forms import BookmarkForm
  7. # Create your views here.
  8. def bookmark_list(request):
  9. bookmarks = Bookmark.public.all()
  10. if request.GET.get('tag'):
  11. bookmarks = bookmarks.filter(tags__name=request.GET['tag'])
  12. context = {'bookmarks': bookmarks}
  13. return render(request, 'marcador/bookmark_list.html', context)
  14. def bookmark_user(request, username):
  15. user = get_object_or_404(User, username=username)
  16. if request.user == user:
  17. bookmarks = user.bookmarks.all()
  18. else :
  19. bookmarks = Bookmark.public.filter(owner__username=username)
  20. if request.GET.get('tag'):
  21. bookmarks = bookmarks.filter(tags__name=request.GET['tag'])
  22. context = {'bookmarks': bookmarks, 'owner':user}
  23. return render(request, 'marcador/bookmark_user.html', context)
  24. @login_required
  25. def bookmark_create(request):
  26. if request.method == 'POST':
  27. form = BookmarkForm(data=request.POST)
  28. if form.is_valid():
  29. bookmark = form.save(commit=False)
  30. bookmark.owner = request.user
  31. bookmark.save()
  32. form.save_m2m()
  33. return redirect('marcador_bookmark_user', username=request.user.username)
  34. else:
  35. form = BookmarkForm()
  36. context = {'form': form, 'create': True}
  37. return render(request, 'marcador/form.html', context)
  38. @login_required
  39. def bookmark_edit(request, pk):
  40. bookmark = get_object_or_404(Bookmark, pk=pk)
  41. if bookmark.owner != request.user and not request.user.is_superuser:
  42. raise PermissionDenied
  43. if request.method == "POST":
  44. form = BookmarkForm(instance=bookmark, data=request.POST)
  45. if form.is_valid():
  46. form.save()
  47. return redirect('marcador_bookmark_user', username=request.user.username)
  48. else:
  49. form = BookmarkForm(instance=bookmark)
  50. context = {'form':form, 'create':False}
  51. return render(request, 'marcador/form.html', context)