def form_valid(self, form):
topic = self.get_object()
old_tags = [tag.title for tag in topic.tags.all()]
topic = form.save()
tags_text = form.cleaned_data['tags']
if tags_text:
new_tags = tags_text.split(',')
remove_tags = set(new_tags) - set(old_tags)
for tag in new_tags:
tag_slug = slugify(tag)
if not Tags.objects.filter(slug=tag_slug).exists():
tag = Tags.objects.create(slug=tag_slug, title=tag)
topic.tags.add(tag)
else:
tag = Tags.objects.filter(slug=tag_slug).first()
if tag.title in remove_tags:
topic.remove(tag)
else:
topic.tags.add(tag)
topic.save()
return JsonResponse({"error": False, "success_url": reverse('django_simple_forum:signup')})
评论列表
文章目录