from django.shortcuts import render, get_object_or_404 from django.http import HttpResponseRedirect from django.urls import reverse from django.views.generic import FormView from django.contrib.auth.mixins import LoginRequiredMixin from django.contrib.auth.decorators import login_required from django.utils import timezone from .models import Request, RequestMessage from .forms import RequestForm, ResponseForm, ProviderResponseForm @login_required def listRequests(request): mnts = request.user.maintainer_set.all() requestedFromMe = Request.objects.filter(applicant=mnts) requestedToMe = Request.objects.filter(provider__in=mnts) requests = (requestedFromMe | requestedToMe).order_by("-lastAction") return render(request, "rrequests/list.html", {"requests": requests, "requestedFromMe": requestedFromMe, "requestedToMe": requestedToMe}) class RrequestCreate(LoginRequiredMixin, FormView): template_name = "rrequests/request_create.html" form_class = RequestForm def get_form_kwargs(self, *args, **kwargs): kwargs = super(RrequestCreate, self).get_form_kwargs(*args, **kwargs) kwargs['user'] = self.request.user return kwargs def form_valid(self, form): formData = form.cleaned_data print(formData) request = Request( subject=formData['subject'], status=Request.STATE_OPEN, applicant=formData['applicant'], provider=formData['provider'], ) request.save() requestMsg = RequestMessage( request=request, creator=formData['applicant'], message=formData['message'], ) requestMsg.save() return HttpResponseRedirect(request.get_absolute_url()) @login_required def rrequestDetail(request, pk): reqObj = get_object_or_404(Request, pk=pk) mnts = request.user.maintainer_set.all() formClass = None provider = None if reqObj.provider in mnts: provider = True formClass = ProviderResponseForm else: provider = False formClass = ResponseForm if request.method == "POST": form = formClass(request=reqObj, user=request.user, data=request.POST) if form.is_valid(): # create message object msg = RequestMessage( request=reqObj, creator=reqObj.provider if provider else reqObj.applicant, message=form.cleaned_data['message'] ) if form.cleaned_data['new_status'] != "KEEP": msg.statusChanged = form.cleaned_data['new_status'] reqObj.status = msg.statusChanged msg.save() if "createdResources" in form.cleaned_data and \ form.cleaned_data['createdResources'].strip() != "": reqObj.grantedResources = form.cleaned_data["createdResources"].strip() reqObj.lastAction = timezone.now() reqObj.save() return HttpResponseRedirect(reverse("rrequests:show", args=(pk,))) else: form = formClass(request=reqObj, user=request.user) return render(request, "rrequests/request_detail.html", {"request": reqObj, "form": form})