def test_get_diff_with_callable_related_manager(self): resource = AuthorResource() author = Author(name="Some author") author.save() author2 = Author(name="Some author") self.book.author = author self.book.save() diff = resource.get_diff(author2, author) headers = resource.get_export_headers() self.assertEqual(diff[headers.index('books')], '<span>core.Book.None</span>')
def handle(self, *args, **options): """Handle the command""" source_file = options['file'] self.stdout.write(f'Checking if {source_file} exists...') try: # Open csv and loads info to db with open(source_file, 'r') as file: rows = list(csv.reader(file)) count = 0 for idx in range(1, len(rows)): author = Author.objects.filter(name=rows[idx][0]).first() if not author: author = Author(name=rows[idx][0]) author.save() count += 1 self.stdout.write(self.style.SUCCESS( f'Authors table populated with {count} authors!' )) except FileNotFoundError: self.stdout.write(self.style.ERROR('File not found!'))
def author_edit(request, author_id=None): msg = False if author_id: author = get_object_or_404(Author, pk=author_id) submit_url = reverse("dashboard:author_edit", kwargs={'author_id':author.id}) else: author = Author() submit_url = reverse("dashboard:author_add") if request.method == 'POST': form = forms.AuthorForm(request.POST, instance=author) if form.is_valid(): print(form.cleaned_data) author_new = form.save(commit=False) author_new.owner = get_login_user(request.user.id) author_new.save() return redirect('dashboard:author_detail', author.id) else: print("validation fail") else: form = forms.AuthorForm(instance=author) return render(request, 'dashboard/author/edit.html', {'msg': msg, 'form':form, 'author': author, 'submit_url': submit_url})
def new_login(): form = BlogForm(request.form) if request.method == 'POST' and form.validate(): blog = Routes.response_sql() title = form.title.data author = form.author.data email = form.email.data password = md5(form.password.data).hexdigest() blog.title = title blog.author = author blog.email = email blog.password = password blog.update_date = datetime.datetime.now() blog.genre = 'first blog' a = Author(author, email, password) db.session.add(a) db.session.commit() return redirect(url_for('admin.default')) response = Routes.session_blog() return render_template("admin/login.html", blog=response)
def author_edit(request, author_id=None): msg = False if author_id: author = get_object_or_404(Author, pk=author_id) submit_url = reverse("core:author_edit", kwargs={"author_id": author.id}) else: author = Author() submit_url = reverse("core:author_add") if request.method == "POST": form = forms.AuthorForm(request.POST, instance=author) if form.is_valid(): print(form.cleaned_data) author_new = form.save(commit=False) author_new.owner = get_login_user(request.user.id) author_new.save() return redirect("core:author_detail", author.id) else: print("validation fail") else: form = forms.AuthorForm(instance=author) return render( request, "dashboard/author/edit.html", { "msg": msg, "form": form, "author": author, "submit_url": submit_url }, )
def test_get_stats_type(self): """ Tests if TypeError is raised """ a_list = ["test", "type", "error"] self.assertRaises(TypeError, word_counter.get_stats, a_list) self.assertRaises(TypeError, word_counter.get_stats, None) correct_type = [ Article(text="test", author_id=Author(id="Test Test", name="testtest")) ] self.assertEqual(word_counter.get_stats(correct_type), {"test": 1})
def add_authors_to(self, book): authors = [] for form in self.forms: author_data = form.cleaned_data full_name = author_data.get('full_name', '') info = author_data.get('info', '') try: author = Author.objects.get(full_name=full_name) if info: author.info = info author.save() except ObjectDoesNotExist: author = Author(**author_data) author.save() authors.append(author) book.set_authors(authors)
def copy_author_to_submission(user, book): author = Author( first_name=user.first_name, middle_name=user.profile.middle_name, last_name=user.last_name, salutation=user.profile.salutation, institution=user.profile.institution, department=user.profile.department, country=user.profile.country, author_email=user.email, biography=user.profile.biography, orcid=user.profile.orcid, twitter=user.profile.twitter, linkedin=user.profile.linkedin, facebook=user.profile.facebook, ) author.save() book.author.add(author) return author
def author_edit(request, author_id=None): msg = False if author_id: author = get_object_or_404(Author, pk=book_id) submit_url = reverse("dashboard:author_edit", kwargs={'author_id': author.id}) else: author = Author() submit_url = reverse("dashboard:author_add") if request.method == 'POST': form = forms.AuthorForm(request.POST, instance=author) if form.is_valid(): author_new = form.save(commit=False) author_new.save() return redirect('dashboard:author_index') form = forms.AuthorForm(instance=author) return render(request, 'dashboard/author/edit.html', { 'msg': msg, 'form': form, 'author': author, 'submit_url': submit_url })
b.save() # запись значения в базу данных b.name = 'another first name' # изменение атрибута b.save() # запись нового значения в базу b.delete() # удаление объекта из базы # ** для присваивания связи между объектами: # получение объекта класса entry через метод get, присаивание id объекта (pk-1) entry = Entry.object.get() # получение объекта класса blog cheese_blog = Blog.object.get(name="Cheder Talk") entry.blog = cheese_blog # присваивание связи между entry и blog 1 к многим entry.save() genry = Author(name="Genry") # создание автора jonny = Author(name="Jonny") # создание автора entry.authors.add(genry, jonny) # присваивание связи авторов к заметке & = & # endregion ------------------------------------------------------------------- # region #* ОРМ базы данных --------------------------------------------------- """#** Для извлечения данных из базы (фильтр) нужно создать QuerySet - набор объектов из базы. QuerySet соответствует SQL-выражению, а фильтры, которые к нему применены, это условия в WHERE. QuerySet можно получить с помощью менеджеров модели. Каждая модель имеет, по крайней мере, один менеджер, и по умолчанию он называется objects.""" all_entries = Entry.objects.all() # создание QuerySet всех объектов Entry print(all_entries.query) # .query - посмотреть соответствие SQL запроса # создание QuerySet с фильтром по значению headline entries = Entry.objects.filter(headline='name')