def test_article_form_invalid_data(self): form = ArticleCreationForm(data={ 'title': 'Title One', 'content': 'Content One' }) self.assertTrue(form.is_valid())
def create(self, request): form = ArticleCreationForm(request.POST, user=request.user) errors = [] if form.is_valid(): form.save() return HttpResponse("发布成功") else: for k, v in form.errors.items(): errors.append(v) mydict = {"errors": errors} return HttpResponse(json.dumps(mydict), content_type="application/json")
def update(self, request, **kwargs): id = kwargs.get("id") article = get_object_or_404(Article, pk=id) form = ArticleCreationForm(request.POST, instance=article, user=article.author) if form.is_valid(): form.save() return HttpResponse("修改成功") else: for k, v in form.errors.items(): errors.append(v) mydict = {"errors": errors} return HttpResponse(json.dumps(mydict), content_type="application/json")
def add_article(request): user = request.user if user.is_authenticated and request.method == 'POST': form = ArticleCreationForm(request.POST) if form.is_valid(): article = form.save(commit=False) custom_user = CustomUser.objects.get(user=user) blog = Blog.objects.get_or_create(author=custom_user)[0] article.blog = blog article.save() subscribers = blog.subscribers.all() articles2read = [] for sub in subscribers: if not ArticleList.objects.filter(user=sub, article=article).exists(): articles2read.append({'article': article, 'user': sub}) ArticleList.objects.bulk_create( [ArticleList(**kw) for kw in articles2read]) return get_article(request, slug=article.slug) else: form = ArticleCreationForm() context = { 'form': form, 'action': 'article-add', 'title': 'Add a new article to your awesome blog' } return render(request, 'article_creation.html', context)
def test_article_form_invalid_data(self): form = ArticleCreationForm(data={}) self.assertFalse(form.is_valid())