views.py 9.03 KB
Newer Older
1
from django.urls import reverse_lazy
2
from django.http import HttpResponseRedirect
3
from django.contrib.auth.mixins import LoginRequiredMixin
4
from django.views.generic import (View, TemplateView, ListView, CreateView, DetailView)
5
from django.views.generic.detail import SingleObjectMixin
6
from django.contrib import messages
7
from django.shortcuts import get_object_or_404, redirect
8
from rules.contrib.views import PermissionRequiredMixin
9
from django.contrib.auth import get_user_model
10

11 12
from .models import Job, Application, Question, JobMessage
from .forms import JobForm, QuestionFormSet, ApplicationForm, AnswerForm, MessageForm
13

14

15 16
User = get_user_model()

17 18 19
class Index(TemplateView):
    template_name = 'jobs/index.html'

Aatish Neupane's avatar
Aatish Neupane committed
20 21
    def get_context_data(self, *args, **kwargs):
        context = super().get_context_data(*args, **kwargs)
22
        context['jobs'] = Job.objects.filter(active=True).order_by('-updated')[:6]
Aatish Neupane's avatar
Aatish Neupane committed
23 24
        return context

25

26 27 28 29 30
class JobDetail(DetailView):
    context_object_name = 'job'
    model = Job


31 32
class JobRenew(LoginRequiredMixin, PermissionRequiredMixin, SingleObjectMixin,
               View):
33 34 35 36 37 38 39 40
    model = Job
    permission_required = 'jobs.change_job'
    http_method_names = ['post']

    def post(self, request, *args, **kwargs):
        job = self.get_object()
        job.renew()
        messages.add_message(
41
            request, messages.SUCCESS, 'Job has been renewed until {}.'.format(
42 43 44 45
                job.expires.isoformat(' ', 'seconds')))
        return HttpResponseRedirect(job.get_absolute_url())


46
class JobCreate(LoginRequiredMixin, CreateView):
47 48
    model = Job
    form_class = JobForm
49
    success_url = reverse_lazy("jobs:job_list")
50

51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71
    def get(self, request, *args, **kwargs):
        self.object = None
        form = self.get_form(self.get_form_class())
        question_form = QuestionFormSet()
        return self.render_to_response(
            self.get_context_data(form=form, question_form=question_form))

    def post(self, request, *args, **kwargs):
        self.object = None
        form_class = self.get_form_class()
        form = self.get_form(form_class)
        question_form = QuestionFormSet(self.request.POST)
        if (form.is_valid() and question_form.is_valid()):
            return self.form_valid(form, question_form)
        else:
            return self.form_invalid(form, question_form)

    def form_valid(self, form, question_form):
        self.object = form.save(commit=False)
        self.object.posted_by = self.request.user
        self.object.save()
72
        form.save_m2m()
73 74 75 76 77 78 79 80

        question_form.instance = self.object
        question_form.save()

        return HttpResponseRedirect(self.get_success_url())

    def form_invalid(self, form, question_form):
        return self.render_to_response(
81
            self.get_context_data(form=form, question_form=question_form))
82 83


84
class ApplicationCreate(LoginRequiredMixin, CreateView):
85 86 87
    # TODO: restrict users from re-application
    model = Application
    form_class = ApplicationForm
88
    success_url = reverse_lazy("jobs:index")
89 90

    def get_question_queryset(self):
91 92 93 94
        # filter questions for particular job and order it so same queryset
        # can be used stably as initial params for GET and POST requests
        return Question.objects.filter(
            job_id=self.kwargs['job_pk']).order_by('id')
95 96 97

    def get_answer_formset(self, *args):
        questions = self.get_question_queryset()
98 99
        return AnswerForm.inlineformset_factory(extra=questions.count())(
            initial=[{
100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122
                'question': q.id
            } for q in questions], *args)

    def get(self, request, *args, **kwargs):
        self.object = None
        form = self.get_form(self.get_form_class())
        answer_form = self.get_answer_formset()
        return self.render_to_response(
            self.get_context_data(form=form, answer_form=answer_form))

    def post(self, request, *args, **kwargs):
        self.object = None
        form_class = self.get_form_class()
        form = self.get_form(form_class)
        answer_form = self.get_answer_formset(self.request.POST)
        if (form.is_valid() and answer_form.is_valid()):
            return self.form_valid(form, answer_form)
        else:
            return self.form_invalid(form, answer_form)

    def form_valid(self, form, answer_form):
        self.object = form.save(commit=False)
        self.object.applicant = self.request.user
123
        self.object.job = get_object_or_404(Job, id=self.kwargs['job_pk'])
124
        self.object.save()
125
        form.save_m2m()
126 127 128 129

        answer_form.instance = self.object
        answer_form.save()

130 131 132 133
        messages.add_message(
            self.request, messages.SUCCESS,
            'Your application has been succesfully received.')

134 135 136 137 138
        return HttpResponseRedirect(self.get_success_url())

    def form_invalid(self, form, answer_form):
        return self.render_to_response(
            self.get_context_data(form=form, answer_form=answer_form))
139 140


141
class ApplicationList(LoginRequiredMixin, PermissionRequiredMixin, ListView):
142 143
    model = Application
    context_object_name = 'applications'
144 145 146 147
    permission_required = 'jobs.change_job'

    def get_permission_object(self):
        return get_object_or_404(Job, id=self.kwargs['job_pk'])
148 149 150 151

    def get_queryset(self):
        return super().get_queryset().filter(job_id=self.kwargs['job_pk'])

Aatish Neupane's avatar
Aatish Neupane committed
152

153 154 155 156 157 158 159 160 161 162 163
class ListOwnApplications(ListView):
    model = Application
    context_object_name = 'applications'
    template_name = 'jobs/list_own_applications.html'

    def get_queryset(self):
        return Application.objects.filter(applicant=self.request.user)

    def get_context_data(self, **kwargs):
        context = super(ListOwnApplications, self).get_context_data(**kwargs)
        context['title'] = 'Your Applications'
164
        context['application_page'] = 'active'
165 166 167 168 169 170 171 172 173 174 175 176 177 178 179
        return context


class ListJobApplications(ListView):
    model = Application
    context_object_name = 'applications'
    template_name = 'jobs/list_applications_others.html'

    def get_queryset(self):
        return Application.objects.filter(job__posted_by=self.request.user)

    def get_context_data(self, **kwargs):
        context = super(ListJobApplications, self).get_context_data(**kwargs)
        context['title'] = 'Applications to your jobs'
        context['form'] = MessageForm
180
        context['application_page'] = 'active'
181 182 183
        return context


184
class ApplicationDetail(LoginRequiredMixin, DetailView):
185
    model = Application
186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205


class MesssageInbox(LoginRequiredMixin, ListView):
    model = JobMessage
    context_object_name = 'jobmessage'

    def get_queryset(self):
        qs_list = []
        qs = JobMessage.objects.filter(receiver=self.request.user).order_by('-date')
        lookup = set(qs.values_list('sender', flat=True))
        for sender_id in lookup:
            for elem in qs:
                if elem.sender_id == sender_id:
                    qs_list.append(elem.id)
                    break
        return JobMessage.objects.filter(pk__in=qs_list).order_by('-date')

    def get_context_data(self, **kwargs):
        context = super(MesssageInbox, self).get_context_data(**kwargs)
        context['title'] = 'Messages Inbox'
206
        context['messages_page'] = 'active'
207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225
        return context


class Conversation(LoginRequiredMixin, ListView):
    model = JobMessage
    context_object_name = 'jobmessage'
    template_name = 'jobs/conversation.html'

    def get_queryset(self):
        queryset1 = JobMessage.objects.filter(
            receiver=self.request.user, sender=self.kwargs['pk'])
        queryset2 = JobMessage.objects.filter(
            receiver=self.kwargs['pk'], sender=self.request.user)
        return queryset1.union(queryset2).order_by('date')

    def get_context_data(self, **kwargs):
        context = super(Conversation, self).get_context_data(**kwargs)
        context['form'] = MessageForm
        context['person'] = User.objects.get(id=self.kwargs['pk'])
226
        context['messages_page'] = 'active'
227 228 229 230 231 232 233 234 235 236 237 238 239 240 241
        return context


class MyJobs(LoginRequiredMixin, ListView):
    model = Job
    context_object_name = 'jobs'
    template_name = 'jobs/job.html'

    def get_queryset(self):
        return Job.objects.filter(posted_by=self.request.user).order_by('expires')


    def get_context_data(self, **kwargs):
        context = super(MyJobs, self).get_context_data(**kwargs)
        context['title'] = 'Your jobs'
242
        context['my_jobs_page'] = 'active'
243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267
        return context


def send_message(request):
    form = MessageForm(request.POST)
    if form.is_valid():
        user = User.objects.get(id=request.POST.get('receiver_id'))
        JobMessage.objects.create(sender=request.user, receiver=user, text=request.POST.get('text'))
    else:
        print("Error")
    return redirect('jobs:conversation', pk=request.POST.get('receiver_id'))

def change_status(request):
    print(request.POST)
    job_id = request.POST.get('job_id')
    if job_id is not None:
        job = Job.objects.get(id=job_id)
        if job.active:
            job.active = False
        else:
            job.active = True
        job.save()
    else:
        print("Error")
    return redirect('jobs:my_jobs')