/
Zero1l
/
321
Обзор
Документация
Войти
/
Zero1l
/
321
Код
Запросы
0
Задачи
Вики
Пакеты
0
Релизы
0
CI/CD
Аналитика
Безопасность
master
README.py
94 строки
3 KB
Zero1l
update README.py
08 окт 2025, 14:05
08 окт 2025, 14:05
5178bb8
Код
Авторство
О чём код?
# 321 class Tag(models.Model): name = models.CharField(max_length=50) def __str__(self): return self.name python class Article(models.Model): title = models.CharField(max_length=200) text = models.TextField() published_at = models.DateTimeField() class Meta: verbose_name = 'Статья' verbose_name_plural = 'Статьи' ordering = ['-published_at'] python class Scope(models.Model): article = models.ForeignKey(Article, related_name='scopes', on_delete=models.CASCADE) tag = models.ForeignKey(Tag, related_name='scopes', on_delete=models.CASCADE) is_main = models.BooleanField(default=False) class Meta: unique_together = ('article', 'tag') python from django.forms import BaseInlineFormSet from django.core.exceptions import ValidationError class ScopeInlineFormset(BaseInlineFormSet): def clean(self): super().clean() main_count = 0 for form in self.forms: if not form.cleaned_data or form.cleaned_data.get('DELETE', False): continue is_main = form.cleaned_data.get('is_main', False) if is_main: main_count += 1 if main_count == 0: raise ValidationError('Должен быть выбран один основной раздел.') elif main_count > 1: raise ValidationError('Можно выбрать только один основной раздел.') python from django.contrib import admin from .models import Article, Tag, Scope class ScopeInline(admin.TabularInline): model = Scope formset = ScopeInlineFormset extra = 1 # Кол-во дополнительно создаваемых форм при редактировании @admin.register(Article) class ArticleAdmin(admin.ModelAdmin): inlines = [ScopeInline] : django {% for scope in article.scopes.all %} <span class="badge {% if scope.is_main %}badge-primary{% else %}badge-secondary{% endif %}"> {{ scope.tag.name }} </span> {% endfor %} python class Article(models.Model): # поля... def get_sorted_tags(self): scopes = self.scopes.select_related('tag') primary_scope = [s for s in scopes if s.is_main] others = sorted([s for s in scopes if not s.is_main], key=lambda s: s.tag.name) sorted_scopes = primary_scope + others return [s.tag for s in sorted_scopes] django {% for tag in article.get_sorted_tags %} <span class="badge {% if tag.scope.is_main %}badge-primary{% else %}badge-secondary{% endif %}"> {{ tag.name }} </span> {% endfor %}