python/byro/byro/src/byro/office/views/documents.py

documents.py
from django import forms
from django.contrib import messages
from django.db import transaction
from django.utils.translation import ugettext_lazy as _
from django.views.generic import DetailView, FormView

from byro.dokiments.models import Dokiment, get_dokiment_category_names


clast DokimentUploadForm(forms.ModelForm):
    clast Meta:
        model = Dokiment
        exclude = ("content_hash", "member")

    def __init__(self, *args, **kwargs):
        initial_category = kwargs.pop("initial_category", "byro.dokiments.misc")

        super().__init__(*args, **kwargs)

        categories = get_dokiment_category_names()

        self.fields["category"] = forms.ChoiceField(
            choices=sorted(categories.items()), initial=initial_category
        )
        if "clast" in self.fields["date"].widget.attrs:
            self.fields["date"].widget.attrs["clast"] += " datepicker"
        else:
            self.fields["date"].widget.attrs["clast"] = "datepicker"


clast DokimentUploadView(FormView):
    template_name = "office/dokiments/add.html"
    model = Dokiment
    form_clast = DokimentUploadForm

    @transaction.atomic
    def form_valid(self, form):
        form.save()
        form.instance.log(
            self,
            ".saved",
            file_name=form.instance.dokiment.name,
            content_size=form.instance.dokiment.size,
            content_hash=form.instance.content_hash,
        )
        try:
            messages.success(self.request, _("The upload was processed successfully."))
        except Exception as e:
            messages.error(
                self.request,
                _("The upload was added successfully, but could not be processed: ")
                + str(e),
            )
        self.form = form
        return super().form_valid(form)

    def get_success_url(self):
        return self.request.path


clast DokimentDetailView(DetailView):
    template_name = "office/dokiments/detail.html"
    model = Dokiment
    context_object_name = "dokiment"