Files
interchan/board/forms.py
Alek Ratzloff 470a10d2a7 Add ability to create bans from reports
This is done in the admin view and opens a new iframed window. The ban
form is pretty barebones and doesn't have full functionality yet, but
that is coming.

Signed-off-by: Alek Ratzloff <alekratz@gmail.com>
2022-06-23 16:03:09 -07:00

108 lines
3.0 KiB
Python

from django.conf import settings
from django.db import transaction
from django.db.models import Q
from django import forms
from django.forms import ModelForm, ModelChoiceField
from django.utils import timezone
from board.models import Ban, Post, Report, ReportReason, ReportRecord
from hcaptcha.fields import hCaptchaField
class PostForm(ModelForm):
"""
A form used for new threads for posts.
This requires the board and the IP address to be specified.
"""
hcaptcha = hCaptchaField() if settings.USE_HCAPTCHA else None
class Meta:
model = Post
fields = ["subject", "name", "text", "image"]
def __init__(self, *args, board, ip, **kwargs):
super(PostForm, self).__init__(*args, **kwargs)
self.instance.board = board
self.instance.ip = ip
class ReplyForm(PostForm):
"""
A form used for replies to posts.
This requires the OP post, the reply post, the board, and the IP address be
specified.
"""
hcaptcha = hCaptchaField() if settings.USE_HCAPTCHA else None
class Meta:
model = Post
fields = ["name", "text", "bump", "image"]
def __init__(self, *args, op, reply, **kwargs):
super(ReplyForm, self).__init__(*args, **kwargs)
self.instance.op = op
self.instance.reply = reply
class ReportForm(ModelForm):
"""
A form used to create reports on posts.
This requires the board and the IP address to be specified.
"""
# uses report_form.html
class Meta:
model = Report
fields = ["reason"]
def __init__(self, *args, op, board, ip, **kwargs):
super(ReportForm, self).__init__(*args, **kwargs)
self.instance.ip = ip
self.op = op
queryset = ReportReason.objects.filter(Q(board=None) | Q(board=board))
self.fields["reason"] = ModelChoiceField(queryset=queryset)
def clean(self):
# Get or create the record before creating the model
with transaction.atomic():
try:
record = ReportRecord.objects.get(post=self.op)
except ReportRecord.DoesNotExist:
record = ReportRecord.objects.create(post=self.op)
self.instance.record = record
return super(ReportForm, self).clean()
class BanForm(ModelForm):
"""
A form used to create bans based on specific posts.
"""
# uses ban_form.html
duration = forms.IntegerField(label="Duration (days)", min_value=1, required=False)
class Meta:
model = Ban
fields = ["ban_reason"]
def __init__(self, *args, op, **kwargs):
super(BanForm, self).__init__(*args, **kwargs)
self.op = op
self.instance.board = op.board
self.instance.ip = op.ip
def clean(self):
super(BanForm, self).clean()
now = timezone.now()
duration = self.cleaned_data["duration"]
if duration:
expires = now + timezone.timedelta(days=duration)
else:
expires = None
self.instance.expires = expires