Django使用带有Button动作的request.user

时间:2017-05-04 12:52:17

标签: django listview datatables request

说明

我有一个表格,显示用户提交的信息,需要由经理操作,所以我在每行末尾都有一个按钮,说“授权”和一个名为authorised_by的空白评论,一旦按下按钮,管理器被重定向到一个表单以忽略信息,并给出了授权所述信息的选项。

问题:

如何传回管理员名称以显示在authorised_by

ListView /表格代码:

model = Change
template_name = 'users/change_requests/exemption_authorise.html'
context_object_name = 'change'

def get_context_data(self, **kwargs):
    context = super().get_context_data(**kwargs)
    self.queryset = self.get_filters(self.model.objects.all())
    context['requested_by'] = self.request.user
    if self.model.authorised_by == True:
        context['authorised_by'] = self.request.user
    else:
        context['authorised_by'] = ""
    context['auth'] = int(bool(int(self.request.GET.get("auth")))) if "auth" in self.request.GET.keys() else None
    context['count_of_records'] = self.queryset.count()
    return context

FormView代码:

model = Change
    template_name = 'users/change_requests/auth_request.html'
    form_class = AuthForm
    pk_url_kwarg = 'authorise_id'

    def check_authorised(self):
        if not getattr(self, 'authorise', None):
            self.authorise = Change.objects.get(pk=self.kwargs.get('authorise_id'))

        if self.authorise.authorised_by:
            messages.error("Sorry, this has already been authorised by {}".format(self.authorise.authorised_by.get_full_name()))

            return True
        return False

    def get(self, request, *args, **kwargs):
        if self.check_authorised():
            return redirect('users:change_request')

        return super().get(request, *args, **kwargs)

    def post(self, request, *args, **kwargs):
        if self.check_authorised():
            return redirect('users:change_request')

        return super().post(request, *args, **kwargs)

    def get_initial(self):
        initial = super().get_initial()
        self.authorise = Change.objects.get(pk=self.kwargs.get('authorise_id'))
        initial.update({'request': self.authorise.request})
        self.initial = initial
        return initial

    def form_valid(self, form):
        self.object = form.save(commit=False)
        self.object.authorised_by = self.request.user
        self.object.save()
        return super(AuthRequest, self).form_valid(form)

    def get_success_url(self):
        redirect_name = 'users:change_request'
        success_url = reverse_lazy(
            redirect_name,

        )

        return success_url

模板代码段:

<thead>
  <tr>
    <th>#</th>
    <th>Name</th>
    <th>Request</th>
    <th>Notes</th>
    <th>Authorised By</th>
    <th>Authorisation</th>
  </tr>
</thead>
<tbody>
{% for req in change %}
  <tr>
    <td>{{ req.id }}</td>
    <td>{{ req.user.get_name }}</td>
    <td>{{ req.request }}</td>
    <td>{{ req.Notes }}</td>
    <td>{{ request.user }}</td>
{% endfor %}
  </tr>
</tbody>

我的按钮未在模板html中显示的原因是我在我的JSON数据视图中创建了它,我认为这与显示无关。

0 个答案:

没有答案