bornhack-website/src/villages/models.py

61 lines
1.9 KiB
Python
Raw Normal View History

2016-07-05 21:43:18 +00:00
from django.db import models
from django.urls import reverse_lazy
2016-07-05 21:43:18 +00:00
from django.utils.text import slugify
from utils.models import CampRelatedModel, UUIDModel
2016-07-05 21:43:18 +00:00
2017-03-07 23:24:14 +00:00
class Village(UUIDModel, CampRelatedModel):
2016-07-05 21:43:18 +00:00
class Meta:
2019-06-16 12:32:24 +00:00
ordering = ["name"]
unique_together = ("slug", "camp")
2016-07-05 21:43:18 +00:00
2019-06-16 12:32:24 +00:00
contact = models.ForeignKey("auth.User", on_delete=models.PROTECT)
camp = models.ForeignKey("camps.Camp", on_delete=models.PROTECT)
2016-07-05 21:43:18 +00:00
name = models.CharField(max_length=255)
slug = models.SlugField(max_length=255, blank=True)
description = models.TextField(
help_text="A descriptive text about your village. Markdown is supported."
)
2016-07-05 21:43:18 +00:00
2016-07-05 21:55:05 +00:00
private = models.BooleanField(
2016-07-05 21:58:46 +00:00
default=False,
2019-06-16 12:32:24 +00:00
help_text="Check if your village is invite only. Leave unchecked to welcome strangers.",
2016-07-05 21:43:18 +00:00
)
2019-06-16 12:32:24 +00:00
deleted = models.BooleanField(default=False)
2016-07-05 21:43:18 +00:00
def __str__(self):
2017-03-30 07:36:47 +00:00
return "%s (%s)" % (self.name, self.camp.title)
2016-07-05 21:43:18 +00:00
def get_absolute_url(self):
2019-06-16 12:32:24 +00:00
return reverse_lazy(
"village_detail", kwargs={"camp_slug": self.camp.slug, "slug": self.slug}
)
2016-07-05 21:43:18 +00:00
def save(self, **kwargs):
if (
2019-06-16 12:32:24 +00:00
not self.pk
or not self.slug
or Village.objects.filter(slug=self.slug).count() > 1
2016-07-05 21:43:18 +00:00
):
slug = slugify(self.name)
if not slug:
slug = "noname"
2016-07-05 21:43:18 +00:00
incrementer = 1
# We have to make sure that the slug won't clash with current slugs
while Village.objects.filter(slug=slug).exists():
if incrementer == 1:
2019-06-16 12:32:24 +00:00
slug = "{}-1".format(slug)
2016-07-05 21:43:18 +00:00
else:
2019-06-16 12:32:24 +00:00
slug = "{}-{}".format("-".join(slug.split("-")[:-1]), incrementer)
2016-07-05 21:43:18 +00:00
incrementer += 1
self.slug = slug
super(Village, self).save(**kwargs)
def delete(self, using=None, keep_parents=False):
self.deleted = True
self.save()