website/www/usethesource/views.py

81 lines
2.9 KiB
Python

from django import forms
from django.contrib.admin.views.decorators import staff_member_required
from django.shortcuts import get_object_or_404, redirect, render
from .models import Candidate, Comment
def landing_page(request):
candidates = Candidate.objects.all()
return render(request, 'usethesource/landing_page.html', {'candidates': candidates})
def candidate_page(request, slug):
candidate = get_object_or_404(Candidate, slug=slug)
return render(request, 'usethesource/candidate.html', {'candidate': candidate, 'add': True})
def download_page(request, slug, download_type):
candidate = get_object_or_404(Candidate, slug=slug)
url = candidate.source_url if download_type == 'source' else candidate.binary_url
return render(
request,
'usethesource/download.html',
{'candidate': candidate, 'download_url': url},
)
class CommentForm(forms.ModelForm):
class Meta:
model = Comment
fields = ['message']
@staff_member_required
def create_comment(request, slug):
candidate = get_object_or_404(Candidate, slug=slug)
if request.method == 'GET':
form = CommentForm()
else:
form = CommentForm(request.POST)
if form.is_valid():
instance = form.save(commit=False)
instance.candidate = candidate
instance.user = request.user
instance.save()
return redirect('usethesource:view_comment', comment_id=instance.id, show_add='true')
return render(request, 'usethesource/comment_form.html', {'form': form, 'candidate': candidate})
@staff_member_required
def edit_comment(request, comment_id):
comment = get_object_or_404(Comment, id=comment_id)
if request.method == 'GET':
form = CommentForm(instance=comment)
else:
form = CommentForm(request.POST, instance=comment)
if form.is_valid():
instance = form.save(commit=False)
instance.save()
return redirect('usethesource:view_comment', comment_id=instance.id, show_add='false')
return render(request, 'usethesource/edit_comment_form.html', {'form': form, 'comment': comment})
@staff_member_required
def view_comment(request, comment_id, show_add):
show_add = show_add == 'true'
comment = get_object_or_404(Comment, id=comment_id)
return render(request, 'usethesource/returned_comment.html', {'comment': comment, 'candidate': comment.candidate, 'add': show_add})
@staff_member_required
def delete_comment(request, comment_id, show_add):
show_add = show_add == 'true'
Comment.objects.filter(id=comment_id).delete()
return render(request, 'usethesource/comment_deleted.html', {'comment': None, 'add': show_add})
@staff_member_required
def add_button(request, slug):
candidate = get_object_or_404(Candidate, slug=slug)
return render(request, 'usethesource/add_comment_button_partial.html', {'candidate': candidate})