class Course(models.Model):
name = models.CharField()
programs = models.ManyToManyField('Program', through='ProgramCourse', related_name='courses')
class Program(models.Model):
name = models.CharField()
class ProgramCourse(models.Model):
program = models.ForeignKey(Program, on_delete=models.CASCADE)
course = models.ForeignKey(Course, on_delete=models.CASCADE)
order = models.IntegerField() # Дополнительное поле для сортировки
post = models.ForeignKey(
Article,
related_name='post',
on_delete=models.CASCADE,
editable=False # !!!
)
def article(request, slug):
article = get_object_or_404(Article, slug__iexact=slug)
# Комментарии
if request.method == 'POST':
comment_form = CommentForm(request.POST)
if comment_form.is_valid():
comment_form.instance.author = request.user
comment_form.instance.post = article
comment_form.save()
return redirect('/')
else:
comment_form = CommentForm()
comments = Comment.objects.order_by('-pk')
context = {
'article': article,
'comments': comments,
'comment_form': comment_form,
}
return render(request, 'home/one_news.html', context)
STOP_LIST = [
'мат',
'мат',
'мат',
]
class ContactForm(forms.Form):
...
def clean_text(self):
text = self.cleaned_data['text']
for word in STOP_LIST:
if word in text:
raise forms.ValidationError("Вы позволили себе немного лишнего! Одумайтесь и исправьте текст!")
return text
from django.db.models.signals import post_save
from django.dispatch import receiver
@receiver(post_save, sender=User, created)
def save_profile(sender, instance, **kwargs):
# instance — это сохранённый экземпляр модели User
# created — это флаг, указывающий был ли пользователь создан, или сохранён уже существующий
class ServiceCreateView(CreateView):
model = Service
template_name = 'elitemservice/main.html'
def form_valid(self, form):
resp = super(ServiceCreateView, self).form_valid(form)
# после вызова суперметода в self.object находится созданный по форме объект
user = self.request.user
if user.is_authenticated:
user.loads_services.create(
pk=self.object.pk,
name_service=self.object.name_service,
about_service=self.object.about_service,
file_service=self.object.file_service,
)
user.save()
return resp
db_name = get_db_name_by_host(request.get_host())
news = News.objects.using(db_name).all()
news = News.objects.filter(site__domain=request.get_host())
db_name = get_db_name_by_host(request.get_host())
news = News.objects.using(db_name).all()
from django.db.models import F
class Quiz(models.Model):
...
def increase_views(self):
self.__class__.objects.filter(pk=self.pk).update(views=F('views') + 1)
class News(models.Model):
title = models.CharField(u'заголовок', max_length=200)
image = models.ImageField(u'изображение', upload_to='images/%Y/%m/%d/', max_length=250)
text = models.TextField(u'текст')
@receiver(post_save, sender=FingerPrint)
def update_calculated_fields(sender, instance, **kwargs):
tlsh = instance.calculate_tlsh()
sender.objects.filter(pk=instance.pk).update(tlsh=tlsh)