dpaste/dpaste/forms.py

116 lines
3.7 KiB
Python
Raw Permalink Normal View History

import datetime
2011-05-30 09:03:04 +10:00
from django import forms
2018-06-22 20:37:04 +10:00
from django.apps import apps
from django.utils.translation import gettext_lazy as _
2018-06-22 20:37:04 +10:00
from .highlight import LEXER_CHOICES, LEXER_DEFAULT, LEXER_KEYS
2014-12-15 04:03:35 +11:00
from .models import Snippet
2011-05-30 09:03:04 +10:00
config = apps.get_app_config("dpaste")
2013-09-28 01:50:58 +10:00
def get_expire_values(expires):
if expires == "never":
expire_type = Snippet.EXPIRE_KEEP
expires = None
elif expires == "onetime":
expire_type = Snippet.EXPIRE_ONETIME
expires = None
else:
expire_type = Snippet.EXPIRE_TIME
# Correct one of the identical sub-expressions on both sides of operator "and".
expires = expires or config.EXPIRE_DEFAULT
2020-01-08 23:19:52 +11:00
expires = datetime.datetime.now() + datetime.timedelta(seconds=int(expires))
return expires, expire_type
2011-05-30 09:03:04 +10:00
class SnippetForm(forms.ModelForm):
content = forms.CharField(
label=_("Content"),
2020-01-08 23:19:52 +11:00
widget=forms.Textarea(attrs={"placeholder": _("Awesome code goes here...")}),
2018-06-22 20:37:04 +10:00
max_length=config.MAX_CONTENT_LENGTH,
strip=False,
)
2013-03-20 05:17:07 +11:00
lexer = forms.ChoiceField(
label=_("Lexer"), initial=LEXER_DEFAULT, choices=LEXER_CHOICES
2013-03-20 05:17:07 +11:00
)
2014-01-21 22:10:44 +11:00
expires = forms.ChoiceField(
label=_("Expires"),
2018-12-20 01:03:15 +11:00
choices=config.EXPIRE_CHOICES,
initial=config.EXPIRE_DEFAULT,
)
rtl = forms.BooleanField(label=_("Right to Left"), required=False)
2013-03-20 05:17:07 +11:00
# Honeypot field
2013-03-20 05:17:07 +11:00
title = forms.CharField(
label=_("Title"),
2013-03-20 05:17:07 +11:00
required=False,
widget=forms.TextInput(attrs={"autocomplete": "off"}),
2013-03-20 05:17:07 +11:00
)
2011-05-30 09:03:04 +10:00
class Meta:
model = Snippet
fields = ("content", "lexer", "rtl")
2011-05-30 09:03:04 +10:00
def __init__(self, request, *args, **kwargs):
super().__init__(*args, **kwargs)
2011-05-30 09:03:04 +10:00
self.request = request
2013-03-20 05:43:38 +11:00
# Set the recently used lexer if we have any
session_lexer = self.request.session.get("lexer")
if session_lexer and session_lexer in LEXER_KEYS:
self.fields["lexer"].initial = session_lexer
# if the lexer is given via GET, set it
if "l" in request.GET and request.GET["l"] in LEXER_KEYS:
self.fields["lexer"].initial = request.GET["l"]
def clean_content(self):
content = self.cleaned_data.get("content", "")
2018-12-12 04:56:30 +11:00
if not content.strip():
raise forms.ValidationError(_("This field is required."))
return content
def clean_expires(self):
"""
Extract the 'expire_type' from the choice of expire choices.
"""
expires = self.cleaned_data["expires"]
expires, expire_type = get_expire_values(expires)
self.cleaned_data["expire_type"] = expire_type
return expires
def clean(self):
"""
The `title` field is a hidden honeypot field. If its filled,
this is likely spam.
"""
if self.cleaned_data.get("title"):
raise forms.ValidationError("This snippet was identified as Spam.")
return self.cleaned_data
2011-06-08 20:23:08 +10:00
2011-05-30 09:03:04 +10:00
def save(self, parent=None, *args, **kwargs):
# Set parent snippet
self.instance.parent = parent
2011-06-08 20:23:08 +10:00
# Add expire timestamp. None indicates 'keep forever', use the default
2014-01-12 02:00:11 +11:00
# null state of the db column for that.
self.instance.expires = self.cleaned_data["expires"]
self.instance.expire_type = self.cleaned_data["expire_type"]
2014-01-21 22:10:44 +11:00
2011-05-30 09:03:04 +10:00
# Save snippet in the db
super().save(*args, **kwargs)
2011-05-30 09:03:04 +10:00
# Add the snippet to the user session list
self.request.session.setdefault("snippet_list", [])
self.request.session["snippet_list"] += [self.instance.pk]
2011-05-30 09:03:04 +10:00
# Save the lexer in the session so we can use it later again
self.request.session["lexer"] = self.cleaned_data["lexer"]
return self.instance