def add_book(request): booksurl = request.build_absolute_uri(reverse('books:index')) if request.method == 'POST': book_form = BookForm(request.POST) print(book_form.errors) if book_form.is_valid(): book_ISBN = book_form.cleaned_data['ISBN'] book_name = book_form.cleaned_data['name'] book_description = book_form.cleaned_data['description'] book_author = book_form.cleaned_data['author'] book_publication_year = book_form.cleaned_data['publication_year'] book_publisher = book_form.cleaned_data['publisher'] book_page_count = book_form.cleaned_data['page_count'] book_cover_URL = book_form.cleaned_data['cover_URL'] new_book = Book(ISBN=book_ISBN, name=book_name, description=book_description, author=book_author, publication_year=book_publication_year, publisher=book_publisher, page_count=book_page_count, cover_URL=book_cover_URL) new_book.save() return HttpResponseRedirect('/') else: book_form = BookForm() return render(request, 'books/add_book.html', { 'booksurl': booksurl, 'book_form': book_form })
def book_create(request): if request.method == 'POST': form = BookForm(request.POST) else: form = BookForm() return save_book_form(request, form, 'books/includes/partial_book_create.html')
def book_update(request, pk, template_name='book_form.html'): book = get_object_or_404(Book, pk=pk) form = BookForm(request.POST or None, instance=book) if form.is_valid(): form.save() return redirect('book_list') return render(request, template_name, {'form':form})
def test_custom_validation_rejects_book_that_already_exists(self): form = BookForm(data={ 'title': "MyNewBook", 'authors': [self.author.pk,] }) self.assertFalse(form.is_valid()) self.assertTrue(form.has_error(NON_FIELD_ERRORS, code="bookexists"))
def edit_book(request, slug): book = get_object_or_404(Book, slug=slug) if request.user.is_superuser or book.admin == request.user: if request.method == "POST": book_form = BookForm(request.POST, instance=book) if book_form.is_valid(): book = book_form.save() book.status = request.POST.get('status') book.authors.add(request.user) book.updated_on = datetime.datetime.now() book.save() data = { "error": False, "response": "Book has been edited Successfully." } else: data = {"error": True, "response": book_form.errors} return HttpResponse(json.dumps(data), content_type='application/json; charset=utf-8') users = User.objects.all() return render(request, "docs/books/edit_book.html", { "book": book, "users": users, "privacy_choices": PRIVACY_CHOICES }) return render_to_response("admin/accessdenied.html")
def test_custom_validation_accepts_new_book(self): new_author = AuthorFactory() form = BookForm(data={ 'title': "MyUniqueBook", 'authors': [new_author.pk,], }) self.assertTrue(form.is_valid())
def test_custom_validation_rejects_book_that_already_exists(self): form = BookForm(data={ 'title':'MyNewBook', 'authors':[self.author.pk,], }) self.assertFalse(form.is_valid()) self.assertTrue(form.has_error(NON_FIELD_ERRORS, code='bookexists'))
def create_book(request): if request.user.is_superuser: if request.method == "POST": book_form = BookForm(request.POST) if book_form.is_valid(): book = book_form.save() book.status = request.POST.get('status') if request.POST.get( 'status') else 'Waiting' book.display_order = Book.objects.all().count() book.authors.add(request.user) book.save() data = {"error": False, "response": "Book created"} else: data = {"error": True, "response": book_form.errors} return HttpResponse(json.dumps(data), content_type='application/json; charset=utf-8') users = User.objects.all() return render(request, "docs/books/create_book.html", { "users": users, "privacy_choices": PRIVACY_CHOICES }) return render_to_response("admin/accessdenied.html")
def book_update(request, pk): book = get_object_or_404(Book, pk=pk) if request.method == 'POST': form = BookForm(request.POST, instance=book) else: form = BookForm(instance=book) return save_book_form(request, form, 'partial_book_update.html')
def add_review(request): profile = UserProfile.objects.get(user=request.user) my_books = Book.objects.exclude(UserProfile=profile) if request.method == 'POST': form_1 = BookForm(request.POST) form_instance = ReviewForm(request.POST) if(form_instance.is_valid() and form_1.is_valid()): title = form_1.cleaned_data["title"] genre = form_1.cleaned_data["genre"] author = form_1.cleaned_data["author"] length = form_1.cleaned_data["length"] completed = form_1.cleaned_data["completed"] bk = Book.objects.create(title=title, genre=genre, author=author, length=length, completed=completed) bk.UserProfile.add(profile) description = form_instance.cleaned_data["description"] stars = form_instance.cleaned_data["stars"] recommendation = form_instance.cleaned_data["recommendation"] readability = form_instance.cleaned_data["readability"] rev = Review.objects.create(UserProfile=profile, description=description, stars=stars, recommendation=recommendation, readability=readability, book=bk) return HttpResponseRedirect('../reviews') else: form_1 = BookForm() form_instance = ReviewForm() context = { 'books': my_books, "form": form_instance, "profile": profile, "user": request.user, "form1": form_1, "is_user": checkAuth(request), } return render(request, 'add_review.html', context=context)
def add_book(request): if request.method == 'POST': form = BookForm(request.POST or None) if form.is_valid(): save_it = form.save(commit=False) save_it.save() return render_to_response("books/add_book.html",locals(),context_instance=RequestContext(request))
def test_custom_validation_accepts_new_book(self): new_author = AuthorFactory() form = BookForm(data={ 'title':'MyUniqueBook', 'authors':[new_author.pk], }) self.assertTrue(form.is_valid())
def post(self, request): form = BookForm(request.POST) if form.is_valid(): form.save() res = {'code': 0, 'result': '添加书成功'} else: res = {'code': 1, 'errmsg': form.errors} return JsonResponse(res, safe=True)
def post(self, request,*args, **kwargs): super(BookAddView, self).post(request, *args, **kwargs) form = BookForm(request.POST) if form.is_valid(): form.save() return self.form_valid(form) else: return self.form_invalid(form)
def post(self, request): form = BookForm(request.POST) if form.is_valid(): form.save() res = {'code': 0, 'result': '添加图书成功'} else: # form.errors会把验证不通过的信息以对象的形式传到前端,前端直接渲染即可 res = {'code': 1, 'errmsg': form.errors} return JsonResponse(res, safe=True)
def add_book(request): if request.method == 'POST': form = BookForm(request.POST or None) if form.is_valid(): save_it = form.save(commit=False) save_it.save() return render_to_response("books/add_book.html", locals(), context_instance=RequestContext(request))
def store(request): # return HttpResponse(request.POST.items()) if request.method == "POST": form = BookForm(request.POST) if form.is_valid(): try: form.save() except Exception as e: pass return redirect('/books')
def post(self, request): form = BookForm(request.POST) if form.is_valid(): form.save() res = {'code':0,'result': '添加书成功'} logger.info("%s 新填加书成功" % request.user) else: res = {'code': 1,'errmsg': form.errors} logger.error("errmsg %s " % form.errors) return JsonResponse(res, safe=True)
def post(self, request, *args, **kwargs): pk = kwargs.get('pk') p = self.model.objects.get(pk=pk) form = BookForm(request.POST, instance=p) if form.is_valid(): form.save() res = {"code": 0, "result": "更新图书成功", 'next_url': self.next_url} else: res = {"code": 1, "errmsg": form.errors, 'next_url': self.next_url} return render(request, settings.JUMP_PAGE, res)
def book_create(request): form = BookForm(request.POST or None) if request.POST: if form.is_valid(): form.save() return redirect('books:book_list') return render(request, 'books/book_form.html', { 'form': form, 'new_or_edit': 'New' })
def test_init(self): # Test successful init without data. form = BookForm(instance=self.book_1) self.assertTrue(isinstance(form.instance, Book)) self.assertEqual(form.instance.pk, self.book_1.pk) # Test successful init with data. form=BookForm(self.dict, instance=self.book_1) self.assertTrue(isinstance(form.instance, Book)) self.assertEqual(form.instance.pk, self.book_1.pk)
def book_update(request, book_id): book = get_book(book_id) form = BookForm(request.POST or None, instance=book) if request.POST: if form.is_valid(): form.save() return redirect('books:book_list') return render(request, 'books/book_form.html', { 'form': form, 'new_or_edit': 'Edit' })
def accept_edit_book(request, user_pk, book_id): book = get_object_or_404(BookType, id=book_id) if request.method == 'POST': form = BookForm(request.POST, instance=book) if form.is_valid(): form.save() return HttpResponseRedirect(reverse(accept_books, args=(user_pk,))) else: form = BookForm(instance=book) return render(request, 'books/edit.html', {'form': form})
def test_custom_validation_rejects_book_that_already_exists(self): # next we test if an error is raised when we try to create a book that already exists form = BookForm(data={ 'title': 'MyNewBook', 'authors': [ self.author.pk, ], }) self.assertFalse(form.is_valid()) self.assertTrue(form.has_error(NON_FIELD_ERRORS, code='bookexists'))
def addBook(request): if request.method == "POST": form = BookForm(data=request.POST) if form.is_valid(): book = form.save() # messages.add_message(request, messages.SUCCESS, 'Das Buch "' + book.title +\ # '" wurde erfolgreich angelegt.') return HttpResponseRedirect(book.get_absolute_url()) else: form = BookForm() return render(request, "books/add_book.html", {"form": form, "add": True, "quote": getRandomQuote()})
def test_custom_validation_accepts_book_that_doesnot_exist(self): new_Author = AuthorFactory() form = BookForm(data={ 'title': "My new Book", 'authors': [ new_Author.pk, ], }) self.assertTrue(form.is_valid())
def test_custom_validation_rejects_book_that_already_exist(self): form = BookForm(data={ 'title': "My new Book", 'authors': [ self.author.pk, ], }) self.assertTrue( form.is_valid()) # this is not proper will have to change it self.assertTrue(form.has_error(NON_FIELD_ERRORS, code="bookexists"))
def test_custom_validation_accepts_new_book(self): """ Function doc """ new_author = AuthorFactory form = BookForm(data={ 'title': "MyUniqueBook", 'authors': [ new_author.pk, ], }) self.assertTrue(form.is_valid())
def bookedit(request, pk): book = get_object_or_404(Books, pk=pk) # best practice form = BookForm(request.POST or None, instance=book) if form.is_valid(): form.save() return redirect('book:detail', pk=book.id) return render_to_response('books/bookedit.html', { 'form': form, 'book': book }, context_instance=RequestContext(request))
def edit(request, b_id): book = get_object_or_404(Book, pk=b_id) if request.method == 'POST': form = BookForm(request.POST, instance=book) if form.is_valid(): b=form.save() return redirect('show_books') else: return render_to_response('edit_book.html',{'form':form, 'book':book}, context_instance = RequestContext(request)) return render_to_response('edit_book.html',{'form':BookForm(instance=book), 'book':book}, context_instance = RequestContext(request))
def edit_book(request): if request.method == 'POST': form = BookForm(request.POST) if form.is_valid(): cd = form.cleaned_data book = Book(title=cd['title']) book.put() return HttpResponseRedirect('/search/?q=all') else: form = BookForm() logger.error ("here i am") return render_to_response('book_edit.html', {'form': form})
def list_all(request): if request.method == 'POST': form = BookForm(request.POST) if form.is_valid(): book = form.save() return redirect(book) else: return render_to_response('create_book.html', {'form':form}, context_instance = RequestContext(request)) books = Book.objects.all() #sorted(submissions, key = lambda x: x.calculate_popularity(), reverse=True) return render_to_response('all_books.html', {'books':sorted(books, key=lambda x: x.get_average(), reverse=True)}, context_instance = RequestContext(request))
def booknew(request): # generic 'old' way if 'POST' == request.method: form = BookForm(request.POST) if form.is_valid(): form.save() return redirect('book:list') else: form = BookForm() return render_to_response('books/booknew.html', { 'form': form }, context_instance=RequestContext(request))
def post(self, request): form = BookForm(request.POST) books = Book.objects.filter( date_reviewed__isnull=True).prefetch_related('authors') if form.is_valid(): form.save() return redirect('review-books') context = { 'form': form, 'books': books, } return render(request, "list-to-review.html", context)
def create(req): if req.method == 'GET': context = {'form': BookForm()} return render(req, 'create.html', context) else: form = BookForm(req.POST, instance=Book()) if form.is_valid(): book = form.save() book.save() return redirect('books index') context = {'form': form} return render(req, 'create.html', context)
def uploadbooks(request): form = BookForm() if request.method == "POST": form = BookForm(request.POST, request.FILES) if form.is_valid(): form.save() return home(request) else: form = BookForm() context = {'book': form} return render(request, 'upload.html', context=context)
def books_add_view(request): """Render form for adding books to database. Show list of added books.""" first_author_form = AuthorForm(data=request.POST or None) authors_fs = AuthorFormSet(data=request.POST or None) book_form = BookForm(data=request.POST or None) language_form = LanguageForm(data=request.POST or None) if (first_author_form.is_valid() and language_form.is_valid() and book_form.is_valid() and authors_fs.is_valid()): first_author_name = first_author_form.cleaned_data['name'] first_author, _ = Author.objects.get_or_create(name=first_author_name) more_authors = [] for form in authors_fs: if form.is_valid(): try: author_name = form.cleaned_data['name'] author, _ = Author.objects.get_or_create(name=author_name) more_authors.append(author) except KeyError: pass language_code = language_form.cleaned_data['code'] language, _ = Language.objects.get_or_create(code=language_code) book = book_form.save(commit=False) book.language = language book = book_form.save() book.authors.add(first_author) if more_authors: book.authors.add(*list(more_authors)) date = book_form.cleaned_data['pub_date'] book.pub_date = date book.save() messages.info(request, f'New book has been added!') return redirect('add') context = { 'first_author_form': first_author_form, 'authors_fs': authors_fs, 'book_form': book_form, 'language_form': language_form, } return render(request, 'books_add.html', context)
def edit(req, book_id): book = Book.objects.get(pk=book_id) if req.method == 'GET': context = {'form': BookForm(instance=book)} return render(req, 'create.html', context) else: form = BookForm(req.POST, instance=book) if form.is_valid(): book = form.save() book.save() return redirect('books index') context = {'form': form} return render(req, 'edit.html', context)
def addBook(request): if not request.user.is_authenticated(): return HttpResponseRedirect(getHost(request) + '/login/?next=%s' % request.path) if request.method == 'POST' : form = BookForm(request.POST) if form.is_valid(): cd = form.cleaned_data g = Book(name=cd['name'], description=cd['description'], book_type=cd['book_type']) g.create_by = request.user g.save() for contactId in request.POST['contacts'].split(","): Contact_Book(contact=Contact(id=contactId), book=g).save() return HttpResponseRedirect(getHost(request) + "/books/") else: form = BookForm() contacts = Contact.objects.filter(create_by=request.user) return render_to_response('books/book_form.html', {'form':form, 'contacts':contacts},context_instance=RequestContext(request))
def update_book(request, book_id): book = Book.objects.get(pk=book_id) form = BookForm(instance=book) object_name = {'form': form} template_name = 'books/edit_book.html' if book.seller != request.user: return render(request, 'books/forbidden.html') if request.method == 'POST': form = BookForm(request.POST, request.FILES, instance=book) if form.is_valid(): book.save() return redirect('books:mine') object_name = {'form': form} return render(request, template_name, object_name)
def create_book(request): if request.user.is_superuser: if request.method == "POST": book_form = BookForm(request.POST) if book_form.is_valid(): book = book_form.save() book.status = request.POST.get('status') book.authors.add(request.user) book.save() data = {"error": False, "response": "Book created"} else: data = {"error": True, "response": book_form.errors} return HttpResponse(json.dumps(data)) users = User.objects.all() return render_to_response("docs/books/create_book.html", {"users": users, "privacy_choices": PRIVACY_CHOICES}) return render_to_response("admin/accessdenied.html")
def create_book(request): if request.user.is_superuser: if request.method == "POST": book_form = BookForm(request.POST) if book_form.is_valid(): book = book_form.save() book.status = request.POST.get('status') if request.POST.get('status') else 'Waiting' book.display_order = Book.objects.all().count() book.authors.add(request.user) book.save() data = {"error": False, "response": "Book created"} else: data = {"error": True, "response": book_form.errors} return HttpResponse(json.dumps(data), content_type='application/json; charset=utf-8') users = User.objects.all() return render(request, "docs/books/create_book.html", {"users": users, "privacy_choices": PRIVACY_CHOICES}) return render_to_response("admin/accessdenied.html")
def addBook(request): if request.method == 'POST': form = BookForm(request.POST) if form.is_valid(): title = form.cleaned_data['title'] authors = form.cleaned_data['authors'] publisher = form.cleaned_data['publisher'] publication_date = form.cleaned_data['publication_date'] description = form.cleaned_data['description'] new_book = Book(title=title, publisher=publisher, publication_date=publication_date, description=description) new_book.save() for i in range(0,len(authors)): new_book.authors.add(authors[i]) new_book.save() #return HttpResponse("You have added a New Book.") #return render(request, 'auth_users.html') return redirect('/books/home/') else: form = BookForm() return render(request,'book.html',{'form':form})
def edit_book(request, slug): book = get_object_or_404(Book, slug=slug) if request.user.is_superuser or book.admin == request.user: if request.method == "POST": book_form = BookForm(request.POST, instance=book) if book_form.is_valid(): book = book_form.save() book.status = request.POST.get('status') book.authors.add(request.user) book.updated_on = datetime.datetime.now() book.save() data = {"error": False, "response": "Book has been edited Successfully."} else: data = {"error": True, "response": book_form.errors} return HttpResponse(json.dumps(data), content_type='application/json; charset=utf-8') users = User.objects.all() return render(request, "docs/books/edit_book.html", {"book": book, "users": users, "privacy_choices": PRIVACY_CHOICES}) return render_to_response("admin/accessdenied.html")
def edit_book(request, slug): book = Book.objects.get(slug=slug) if request.user.is_superuser or book.admin == request.user: if request.method == "POST": book_form = BookForm(request.POST, instance=book) if book_form.is_valid(): book = book_form.save() book.status = request.POST.get('status') book.authors.add(request.user) book.save() data = {"error": False, "response": "Book has been edited Successfully."} else: data = {"error": True, "response": book_form.errors} return HttpResponse(json.dumps(data)) users = User.objects.all() return render_to_response("docs/books/edit_book.html", {"book": book, "users": users, "privacy_choices": PRIVACY_CHOICES}) return render_to_response("admin/accessdenied.html")
def add_book(request): if request.method == 'POST': form = BookForm(request.POST) if form.is_valid(): book = form.save(commit=False) book.visible = True book.save() form.save_m2m() messages.success(request, _("The book was added successfully.")) return HttpResponseRedirect(reverse(index)) else: form = BookForm() return render(request, 'books/add.html', {'form': form})
def test_save(self): self.assertEqual(self.book_1.title, "The Great Gatsby") # Test changing title in existing book record form_1 =BookForm(self.dict, instance=self.book_1) form_1.save() self.assertEqual(self.book_1.title, "new_title") # pk is still the same self.assertEqual(self.book_1.pk, 1) # Testing without instance argument, it means testing of new record form_2 =BookForm(self.dict) form_2.save() self.assertEqual(form_2.instance.pk, 4)
def edit_book(request, book_id): book = get_object_or_404(BookType, id=book_id) if request.method == 'POST': form = BookForm(request.POST, instance=book) if form.is_valid(): book = form.save(commit=False) book.visible = True book.save() form.save_m2m() messages.success(request, _("The book was edited successfully.")) return HttpResponseRedirect(reverse(index)) else: form = BookForm(instance=book) return render(request, 'books/edit.html', {'form': form})
def change(request): isbn = request.GET['q'] thebook = get_object_or_404(Book, ISBN = isbn) if request.POST: newbook = BookForm(request.POST, instance = thebook) if newbook.is_valid(): newbook.save() return render_to_response('change.html', { 'newbook': newbook, 'msg': u'图书修改成功!', }) else: newbook = BookForm(instance = thebook) return render_to_response('change.html', {'newbook': newbook,}) else: newbook = BookForm(instance = thebook) return render_to_response('change.html', {'newbook': newbook,})
def newbook(request): abook = None if request.POST: book = Book() abook = BookForm(request.POST, instance = book) if abook.is_valid(): abook.save() return render_to_response('newbook.html', { 'abook': abook, 'msg': u'图书添加成功!', }) else: abook = BookForm() return render_to_response('newbook.html', {'abook': abook, 'msg': u'图书添加失败,请检查信息是否正确'}) else: abook = BookForm() return render_to_response('newbook.html', {'abook': abook,})
def test_forms(self): form = BookForm(data=self.dict) self.assertEqual(form.is_valid(), True)