def _post_bookmarks(request): try: url = request.POST['url'] title = request.POST['title'] form = BookmarkForm({'url': url, 'title': title}) if form.is_valid(): bookmark = Bookmark() bookmark.url = url bookmark.title = title bookmark.save() return JsonResponse({}, status=201) else: data = { 'errors': [{ 'title': '入力エラー', 'data': json.loads(form.errors.as_json()) }] } return JsonResponse(data, status=400) except: data = { 'errors': [{ 'title': 'ブックマークを登録できませんでした' }] } return JsonResponse(data, status=500)
def add_bookmark(request): incorrect_url = False added = False in_db = False if request.POST: url = request.POST["url"] if not url.startswith("http://www."): if not url.startswith("www."): url = "http://www." + url else: url = "http://" + url if correct_url(url): username = request.user.username if Bookmark.objects.filter(username=username, url=url).count(): in_db = True else: metadata = parse_meta(url) bookmark = Bookmark(username=username, url=url, title=metadata["title"], favicon=metadata["favicon"], description=metadata["description"]) bookmark.save() added = True else: incorrect_url = not correct_url(url) context = {"incorrect_url": incorrect_url, "added": added, "in_db": in_db} return render(request, "bookmarks/add_bookmark.html", context)
def create(self, validated_data): bookmark = Bookmark() bookmark.url = validated_data['url'] bookmark.title = validated_data['title'] bookmark.description = validated_data['description'] tag_string = build_tag_string(validated_data['tag_names'], ' ') return create_bookmark(bookmark, tag_string, self.context['user'])
def update_bookmark(bookmark: Bookmark, tag_string, current_user: User): # Update website info _update_website_metadata(bookmark) # Update tag list _update_bookmark_tags(bookmark, tag_string, current_user) # Update dates bookmark.date_modified = timezone.now() bookmark.save() return bookmark
def save(request): form = BookmarksSaveForm(request.POST) if not form.is_valid(): return HttpResponseBadRequest(json.dumps({'error': form.errors})) content = form.cleaned_data['content'] id = md5(content.encode('utf-8')).hexdigest() book = Bookmark(id=id, content=content) book.save() response = HttpResponse(json.dumps({'id': id})) response['Content-Type'] = "application/json" return response
def setUp(self): self.client = Client() self.user = User.objects.create_user(username='******', email='*****@*****.**', password='******') self.bookmark = Bookmark( user=self.user, name='Bookmark 1', url='https://www.google.com', notes='This is the first note.', ) self.bookmark.save()
def test_archive_bookmark(self): bookmark = Bookmark(url='https://example.com', date_added=timezone.now(), date_modified=timezone.now(), owner=self.user) bookmark.save() self.assertFalse(bookmark.is_archived) archive_bookmark(bookmark) updated_bookmark = Bookmark.objects.get(id=bookmark.id) self.assertTrue(updated_bookmark.is_archived)
def handle(self, *args, **options): ''' The layout of the export puts links into <dt> tags and any related comments into a <dd> tag immediately following. If a link has no comments then the <dd> tag is not present. Ignore all other tags ''' user = get_user_model().objects.get(pk=1) # Load the export html into a beautiful soup object soup = BeautifulSoup(open('delicious.html')) print 'Parsing export with %s rows' % len(soup.dl.contents) for i in range(len(soup.dl.contents)): if soup.dl.contents[i].name == 'dt': print('{row}: Creating new bookmark for {url}'.format( row=i, url=soup.dl.contents[i].a['href'])) bookmark = Bookmark( user=user, url=soup.dl.contents[i].a['href'], title=soup.dl.contents[i].a.string, saved=timezone.make_aware( timezone.datetime.fromtimestamp( float(soup.dl.contents[i].a['add_date'])), timezone.get_current_timezone())) print(' {row}: Bookmark title: {title}'.format( row=i, title=soup.dl.contents[i].a.text.encode('utf-8'))) try: # Check for any comments for this bookmark if soup.dl.contents[(i + 1)].name == 'dd': print(' {row}: Got comments: {comments}'.format( row=i, comments=soup.dl.contents[(i + 1)].string)) bookmark.comment = soup.dl.contents[(i + 1)].string except IndexError: # We've reached the end of the export file pass bookmark.save() # Add the tags for tag in soup.dl.contents[i].a['tags'].split(','): print(' {row}: Found tag {tag}'.format(row=i, tag=tag)) if tag != '': try: the_tag = Tag.objects.get(name=tag.strip(' ')) except Tag.DoesNotExist as e: the_tag = Tag(name=tag.strip(' ')) the_tag.save() bookmark.tags.add(the_tag)
def bookmarklet_save(request): # where the bookmarklet first lands them if request.method == 'GET': if request.GET['link']: link = request.GET['link'] # check user and save url user_profile = get_object_or_404(UserProfile, user = request.user) check = Bookmark.objects.filter(url = link, owner = user_profile) if not check: # if they have the old bookmarklet, load the title the old way if 'title' in request.GET: title = request.GET['title'] else: messages.add_message(request, messages.INFO, "There's been an error. You're using an old version of our Bookmarklet. " + "Just drag the new version on this site to your bookmarks bar and you will be good to go!") return redirect(home) else: messages.add_message(request, messages.INFO, 'You have already added this mark') return redirect(home) # post vars, AKA time to save the bookmark elif request.method == 'POST': link = request.POST['link'] title = request.POST['title'] privacy = request.POST['privacy'] if privacy == 'private': public = False elif privacy == 'public': public = True user_profile = get_object_or_404(UserProfile, user = request.user) m = Bookmark(url = link, owner = user_profile, title = title, public = public) m.save() messages.add_message(request, messages.INFO, 'Consider that marked') return redirect(home) # they got here somehow without post or get vars else: return redirect(home) return render_to_response('bookmarks/save.html', { 'title': title, 'link': link }, context_instance=RequestContext(request) )
def test_bookmark_resolved_title(self): bookmark = Bookmark(title='Custom title', website_title='Website title', url='https://example.com') self.assertEqual(bookmark.resolved_title, 'Custom title') bookmark = Bookmark(title='', website_title='Website title', url='https://example.com') self.assertEqual(bookmark.resolved_title, 'Website title') bookmark = Bookmark(title='', website_title='', url='https://example.com') self.assertEqual(bookmark.resolved_title, 'https://example.com')
def _run_bookmark_model_url_validity_checks(self, cases): for case in cases: url, expectation = case bookmark = Bookmark(url=url, date_added=datetime.datetime.now(), date_modified=datetime.datetime.now(), owner=self.user) try: bookmark.full_clean() self.assertTrue(expectation, 'Did not expect validation error') except ValidationError as e: self.assertFalse(expectation, 'Expected validation error') self.assertTrue('url' in e.message_dict, 'Expected URL validation to fail')
def add(ctx, url, tags, verbose, validate): click.echo() # TODO better user-agent header # TODO app name # TODO version headers = {'user-agent': '{}/{}'.format("my-bookmark-cli-app", "0.0.0")} r = get(url, headers=headers) # TODO make something better for other status codes if (not validate) or (validate and r.status_code == 200): if verbose: display_url(url) tags = list(set(tags)) display_tags(tags) click.echo() backend.begin() ts = [] for tag in tags: ts += [Tag.find_or_create_new(backend, tag)] page_title = BeautifulSoup(r.text, "html.parser").title.text b = Bookmark({ 'url': url, 'tags': ts, 'title': page_title }) b.save(backend) if verbose >= 2: click.echo() click.echo( click.style("URL: ") + click.style(b.url, fg='green') ) click.echo("Tags: {}".format(b.tags)) click.echo("Title: {}".format(b.title)) for tag in b.tags: click.echo("name: {} value: {}".format( tag.name, tag.value )) if (True): backend.commit() else: click.echo(r.status_code)
def get_form_for_sound(request, sound_id): sound = Sound.objects.get(id=sound_id) form = BookmarkForm(instance=Bookmark(name=sound.original_filename), prefix=sound.id) form.fields['category'].queryset = BookmarkCategory.objects.filter( user=request.user) categories_already_containing_sound = BookmarkCategory.objects.filter( user=request.user, bookmarks__sound=sound).distinct() add_bookmark_url = '/'.join( request.build_absolute_uri(reverse( 'add-bookmark', args=[sound_id])).split('/')[:-2]) + '/' tvars = { 'bookmarks': Bookmark.objects.filter(user=request.user, sound=sound).count() != 0, 'sound_id': sound.id, 'form': form, 'categories_aready_containing_sound': categories_already_containing_sound, 'add_bookmark_url': add_bookmark_url } template = 'bookmarks/bookmark_form.html' return render(request, template, tvars)
def export(request): """ This uses export.html to export the bookmarks into a format that can be imported by other systems """ ctx = {} ctx["bookmarks"] = Bookmark.by_user(request.user) return TemplateResponse(request, "bookmarks/export.html", ctx)
def create_initial_content(self): LegFile.objects.create(key=1, id='a', title="first", intro_date=date(2011, 12, 13), type="Bill") LegFile.objects.create(key=2, id='b', title="second", intro_date=date(2011, 12, 13), type="Bill") LegFile.objects.create(key=3, id='c', title="third", intro_date=date(2011, 12, 13), type="Bill") legfile = LegFile.objects.get(key=1) self.subscriber.bookmarks.add(Bookmark(content=legfile))
def add_bookmark(): form = BookmarkForm(link='http://') if form.validate_on_submit() and request.method == 'POST': # Get form data link = form.link.data follow_redirects = form.follow_redirects.data # T/F for following link redirects # Test that link works, or return error to user try: r = requests.get(link, headers={'user-agent': USER_AGENT}, allow_redirects=follow_redirects, timeout=TIMEOUT) r.raise_for_status() # Exceptions for 400 or 500 errors except requests.exceptions.HTTPError as e: flash('Please check your link. It leads to this error: {}.'.format( e), category='danger') # Missing schema except requests.exceptions.MissingSchema as e: flash('No schema. Did you mean http://{}?'.format(link), category='danger') # Timeout errors except requests.exceptions.Timeout: flash('There was a timeout error. Please check URL.', category='danger') # Connection errors except requests.exceptions.ConnectionError: flash('Could not connect to your link. Please check URL.', category='danger') # Too many redirects except requests.exceptions.TooManyRedirects: flash('Exceeded max number of redirects. Please check URL.', category='danger') # All other requests-related exceptions except requests.exceptions.RequestException as e: flash('Please check your link. It leads to this error: {}.'.format( e), category='danger') # No errors when requesting link, so add to database else: # Generate a possible id b_id = hex_gen() # If it exists, keep regenerating while (Bookmark.query.filter(Bookmark.id == b_id).one_or_none() is not None): b_id = hex_gen() url = r.url # Get final url (from redirects) url_root = request.url_root b = Bookmark(b_id, link=url, user_id=flask_login.current_user.id) db_session.add(b) db_session.commit() msg_uf = ('Successfully added {0}. Your short link is ' + '<a target="_blank" href="{1}">{1}</a>.') msg = msg_uf.format(url, url_root + b_id) flash(Markup(msg), category='success') return redirect(url_for('add_bookmark'), 303) return render_template('add_bookmark.html', form=form)
def save(self): try: bookmark = Bookmark(user=self.instance.user, sound=self.instance.sound) if not self.cleaned_data['category']: if self.cleaned_data['new_category_name'] != "": category = BookmarkCategory( user=self.instance.user, name=self.cleaned_data['new_category_name']) category.save() bookmark.category = category self.cleaned_data['category'] = category else: bookmark.category = self.cleaned_data['category'] if self.cleaned_data['name'] != "": bookmark.name = self.cleaned_data['name'] bookmark.save() return True except: return False
def bookmarks_ajax(request): response_data = {} response_data['success'] = False response_data['errors'] = '' if not request.method == 'POST'or not request.is_ajax(): return http.HttpResponseForbidden('Forbidden.') data = request.POST files = request.FILES form = BookmarkForm(data, files, user=request.user) if form.is_valid(): try: b = Bookmark.objects.get(article_id=form.cleaned_data.get('article_id'), user=request.user) b.delete() except Bookmark.DoesNotExist: b = Bookmark(article_id=form.cleaned_data.get('article_id'), user=request.user) b.save() # Delete bookmarks session key so they get rebuilt on next request # via middleware if request.session.get('bookmarks'): del request.session['bookmarks'] # Delete article instance cache a = Article.objects.get(pk=form.cleaned_data.get('article_id')) a.clear_cache() # Delete user dashboard cache if possible try: urlpath = URLPath.objects.get(slug=request.user.username) urlpath.article.clear_cache() except: pass response_data['success'] = True else: response_data['errors'] = dict((k, map(unicode, v)) for (k, v) in form.errors.iteritems()) return http.HttpResponse(simplejson.dumps(response_data), mimetype='application/json; charset=UTF-8')
def home(request): """ Uses index.html to display a list of all the user's tags """ ctx = {} ctx["area"] = "tags" ctx["tags"] = make_page(Tag.by_user(request.user), request.GET.get("p")) ctx["untag_count"] = Bookmark.by_user(request.user).filter(tags=None).count() return TemplateResponse(request, "tags/index.html", ctx)
def home(request): """ Home page is a list of all bookmarks and uses template index.html """ ctx = {} # Set up the context ctx["area"] = "bookmarks" ctx["bookmarks"] = make_page(Bookmark.by_user(request.user), request.GET.get("p")) return TemplateResponse(request, "bookmarks/index.html", ctx)
def create_bookmarks(request): if request.method == "POST": form = BookmarkForm(request.POST) if form.is_valid(): url = form.cleaned_data['url'] urlname = form.cleaned_data['urlname'] course = form.cleaned_data['course'] Bookmark.add_bookmark(course, url, urlname) messages.success(request, "Bookmark saved successfully!") return redirect('bookmarks:create') else: form = BookmarkForm() form.fields["course"].queryset = Course.objects.filter(user=request.user) bookmarks = Bookmark.objects.select_related('course').filter( course__user=request.user) return render(request, 'bookmarks/bookmarks.html', { 'bookmarks': bookmarks, 'form': form, })
def handle(self, **options): with open(options['path'], 'r') as file: data = json.load(file) self.log_message( u"Found {} bookmarks".format(len(data)) ) for bookmark in data: self.log_message(u"{}".format(bookmark['title'])) b = Bookmark( title=bookmark['title'], description=bookmark['description'], date_added=bookmark['date_added'], private=bookmark['private'], url=bookmark['url'] ) b.save() for tag in bookmark['tags']: b.tags.add(tag)
def _search_context(query, user): if not query: return {"bookmarks": [], "tags": [], "query": "", "area": "search"} ctx = {"query": query, "area": "search"} ctx["bookmarks"] = Bookmark.by_user(user).filter( Q(title__icontains=query) | Q(url__icontains=query)) ctx["tags"] = Tag.by_user(user).filter(name__icontains=query) return ctx
def untagged(request): """ Given a slug, uses filter.html to display all the things tagged with that specific tag """ ctx = {} bookmarks = Bookmark.by_user(request.user).filter(tags=None) ctx["untag_count"] = bookmarks.count() ctx["area"] = "tags" ctx["tag"] = None ctx["bookmarks"] = make_page(bookmarks, request.GET.get("p")) return TemplateResponse(request, "tags/filter.html", ctx)
def preview(request): """ The preview page for themes Set the theme with the "t" GET attribute """ ctx = {} ctx["area"] = "bookmarks" ctx["preview_theme"] = request.GET.get("t", "light") ctx["bookmarks"] = Bookmark.by_user(request.user)[:5] return TemplateResponse(request, "users/preview.html", ctx)
def setup_bookmark( self, is_archived: bool = False, tags=None, user: User = None, url: str = '', title: str = '', description: str = '', website_title: str = '', website_description: str = '', ): if tags is None: tags = [] if user is None: user = self.get_or_create_test_user() if not url: unique_id = get_random_string(length=32) url = 'https://example.com/' + unique_id bookmark = Bookmark(url=url, title=title, description=description, website_title=website_title, website_description=website_description, date_added=timezone.now(), date_modified=timezone.now(), owner=user, is_archived=is_archived) bookmark.save() for tag in tags: bookmark.tags.add(tag) bookmark.save() return bookmark
def test_can_update_bookmark(self): bookmark = Bookmark( user=self.user, name='Bookmark 1', url='https://www.google.com', notes='This is the first note.', ) bookmark.save() form_data = { 'name': 'Bookmark 8', 'url': 'https://www.google123.com', 'notes': 'This is the first note.', } self.client.force_login(self.user) update_url = "/bookmarks/edit/%s" % bookmark.id response = self.client.post(update_url, data=form_data) self.assertEquals(response.status_code, 302) self.assertRedirects(response, '/bookmarks/') bookmark.refresh_from_db() self.assertEquals(form_data['name'], bookmark.name) self.assertEquals(form_data['url'], bookmark.url) self.assertEquals(form_data['notes'], bookmark.notes)
def handle_data(self, data): if self.in_a: bookmark = Bookmark() bookmark.url = self.attrs.get('href') bookmark.title = data bookmark.bookmarked_at = unixtime2datetime( self.attrs.get('add_date')) try: bookmark.save() except IntegrityError: pass
def filter(request, tag): """ Given a slug, uses filter.html to display all the things tagged with that specific tag """ tag = get_object_or_404(Tag, owner=request.user, slug=makeslug(tag)) ctx = {} if not tag.pinned: # Don't display "tags" thing as active when the tag is pinned ctx["area"] = "tags" ctx["tag"] = tag ctx["pin_form"] = PinTagForm(instance=tag) ctx["bookmarks"] = make_page(Bookmark.get_by_tag(tag), request.GET.get("p")) return TemplateResponse(request, "tags/filter.html", ctx)
class BookmarksDeleteTest(TestCase): def setUp(self): self.client = Client() self.user = User.objects.create_user(username='******', email='*****@*****.**', password='******') self.bookmark = Bookmark( user=self.user, name='Bookmark 1', url='https://www.google.com', notes='This is the first note.', ) self.bookmark.save() def test_can_see_delete_bookmark_form(self): self.client.force_login(self.user) delete_url = "/bookmarks/delete/%s" % self.bookmark.id response = self.client.get(delete_url) self.assertEquals(response.status_code, 200) self.assertTemplateUsed(response, 'confirm_delete.html')
def handle_data(self, data): if self.in_a: bookmark = Bookmark() bookmark.url = self.attrs.get('href') bookmark.title = data bookmark.bookmarked_at = unixtime2datetime(self.attrs.get('add_date')) try: bookmark.save() except IntegrityError: pass
def add(): form = BookmarkForm() if form.validate_on_submit(): url = form.url.data description = form.description.data tags = form.tags.data bm = Bookmark(user=current_user, url=url, description=description, tags=tags) db.session.add(bm) db.session.commit() flash("Stored '{}'".format(description)) return redirect(url_for('index')) return render_template('bookmark_form.html', form=form, title="Add a bookmark")
def bookmark_new(): form = BookmarkForm(request.form) if form.validate_on_submit(): try: bookmark = Bookmark(form.url.data, form.title.data, description=form.description.data, tags=form.tags.data, public=form.public.data) db.session.add(bookmark) db.session.commit() except IntegrityError: flash(u'Boomark for "%s" exists already.' % form.url.data, 'error') return render_template('bookmark-form.html', form=form) flash(u'Done!') return redirect('%d' % bookmark.id) flash_errors(form) return render_template('bookmark-form.html', form=form)
def add_bookmark(request, sound_id): sound = get_object_or_404(Sound, id=sound_id) if request.POST: form = BookmarkForm(request.POST, instance=Bookmark(user=request.user, sound=sound)) form.fields['category'].queryset = BookmarkCategory.objects.filter(user=request.user) if form.is_valid(): form.save() if request.is_ajax(): return HttpResponse() else: msg = "Added new bookmark for sound \"" + sound.original_filename + "\"." messages.add_message(request, messages.WARNING, msg) next = request.GET.get("next", "") if next: return HttpResponseRedirect(next) else: return HttpResponseRedirect(reverse("sound", args=[sound.user.username, sound.id]))
def create(request): """ Given the json representation of a bookmark, creates it The bookmark must have been from "to_json", and must be the "obj" POST value. If it succeeds it returns a JSON object with "obj" being the JSON representation of the bookmark, "type" which is always "bookmark" and "id" which is the id of the newly created bookmark. """ if "obj" not in request.POST: raise SuspiciousOperation try: bm = Bookmark.from_json(request.POST.get("obj"), request.user) except Exception: raise SuspiciousOperation out = {} out["type"] = "bookmark" out["obj"] = bm.to_json() out["id"] = bm.pk return HttpResponse(json.dumps(out), content_type="application/json")
def new_bookmark(request): if request.method == 'POST': bookmark = Bookmark() form = NewBookmarkForm(request.POST, instance=bookmark) if form.is_valid(): bookmark.owner = request.user bookmark.save() for tag in form.cleaned_data['tags']: bookmark.tags.add(tag) bookmark.save() url = reverse("user-list", args=[request.user.username]) return HttpResponseRedirect(url) else: form = NewBookmarkForm() template_name = "bookmarks/new_bookmark.html" context = {'form': form} return(template_name, context)
def save(self): try: bookmark = Bookmark(user=self.instance.user,sound=self.instance.sound) if not self.cleaned_data['category']: if self.cleaned_data['new_category_name'] != "": category = BookmarkCategory(user=self.instance.user, name=self.cleaned_data['new_category_name']) category.save() bookmark.category = category self.cleaned_data['category'] = category else: bookmark.category = self.cleaned_data['category'] if self.cleaned_data['name'] != "": bookmark.name = self.cleaned_data['name'] bookmark.save() return True except: return False
def test_getting_relative_bookmark_creation_time(session): bookmark = Bookmark() session.add(bookmark) session.commit() assert bookmark.get_human_time() == 'just now'
def save_data(request): data = request.GET.getlist('data[]') if data is None: return HttpResponseBadRequest() taskss = data[0] del data[0] if not is_valid_url(taskss): return HttpResponse('<h1>Invalid URL!</h1>') if "http" not in taskss and "www" not in taskss: if "//" in taskss: return HttpResponse('<h2>// is present without http(or https) and www!</h2>') tasks = "http://www." + taskss elif "http" in taskss and "//" not in taskss and "www" in taskss: return HttpResponse('<h2>http(or https) and www are there but no "//"!</h2>') elif "http" not in taskss and "www" in taskss: if taskss[:3] == "www": tasks = "http://" + taskss else: return HttpResponse('<h2>Second elif ("www" not the First Characters)!</h2>') elif "http" in taskss and "www" not in taskss: try: taskss.index("/") except: return HttpResponse('<h2>http(or https) is there but www and // are not there!</h2>') k = taskss.index("/") tasks = taskss[:(k+2)] + "www." + taskss[(k+2):] else: tasks = taskss #loop for removing spaces from list data data = [x.strip(' ') for x in data] u_data = unique(data) conn = sqlite3.connect('db.sqlite3') c = conn.cursor() c.execute("SELECT * FROM bookmarks_bookmark WHERE task LIKE '%" + tasks + "%'") result = c.fetchall() if not result: searchInstance = Bookmark(task = tasks, tag_name = ",".join(u_data)) searchInstance.save() return HttpResponse('<h1>Data Saved!</h1>') ''' c.execute("SELECT * FROM bookmarks_bookmark") url_result = c.fetchall() urls = [idx for idx,r in enumerate(url_result)] url = [r[2] for r in url_result] for i in urls: if not is_valid_url(url[i]): Bookmark.objects.filter(task = url[i]).delete() ''' tup = [r[1] for r in result] tags1 = ",".join(tup) #Converting list into string i.e. from ['abc, xyz'] to 'abc, xyz' tags2 = tags1.split(',') # 'abc, xyz' to ['abc', 'xyz'] #u_d = tup + u_data u_d = union(tags2, u_data) Bookmark.objects.filter(task__contains = tasks).update(tag_name = ",".join(u_d)) return HttpResponse('<h1>Data Saved!</h1>')
def handle(self, *args, **options): ''' The layout of the export puts links into <dt> tags and any related comments into a <dd> tag immediately following. If a link has no comments then the <dd> tag is not present. Ignore all other tags ''' user = get_user_model().objects.get(pk=1) # Load the export html into a beautiful soup object soup = BeautifulSoup(open('delicious.html')) print 'Parsing export with %s rows' % len(soup.dl.contents) for i in range(len(soup.dl.contents)): if soup.dl.contents[i].name == 'dt': print( '{row}: Creating new bookmark for {url}'.format( row=i, url=soup.dl.contents[i].a['href'] ) ) bookmark = Bookmark( user=user, url=soup.dl.contents[i].a['href'], title=soup.dl.contents[i].a.string, saved=timezone.make_aware( timezone.datetime.fromtimestamp( float(soup.dl.contents[i].a['add_date']) ), timezone.get_current_timezone() ) ) print( ' {row}: Bookmark title: {title}'.format( row=i, title=soup.dl.contents[i].a.text.encode('utf-8') ) ) try: # Check for any comments for this bookmark if soup.dl.contents[(i + 1)].name == 'dd': print( ' {row}: Got comments: {comments}'.format( row=i, comments=soup.dl.contents[(i + 1)].string ) ) bookmark.comment = soup.dl.contents[(i + 1)].string except IndexError: # We've reached the end of the export file pass bookmark.save() # Add the tags for tag in soup.dl.contents[i].a['tags'].split(','): print( ' {row}: Found tag {tag}'.format( row=i, tag=tag ) ) if tag != '': try: the_tag = Tag.objects.get(name=tag.strip(' ')) except Tag.DoesNotExist as e: the_tag = Tag(name=tag.strip(' ')) the_tag.save() bookmark.tags.add(the_tag)
def delicious_import(request): if request.method == 'POST': form = DeliciousImportForm(request.POST, request.FILES) if form.is_valid(): try: soup = BeautifulStoneSoup(request.FILES['delicious_html'], convertEntities="html", smartQuotesTo="html") except TypeError: raise forms.ValidationError("Not a delicious HTML file") rows = soup.findAll(['dt','dd']) for row in rows: if row.name == 'dd': continue else: bookmark = Bookmark() link = row.first() bookmark.title = link.text bookmark.url = link['href'] bookmark.owner = request.user pub_date = datetime.utcfromtimestamp(int(link['add_date'])) bookmark.pub_date = pub_date bookmark.private = link['private'] == u"1" if row.find('dd'): bookmark.description = row.find('dd').text bookmark.save() if link.has_key('tags'): tags = link['tags'].split(',') for tag in tags: if len(tag) > 0: bookmark.tags.add(tag) bookmark.save() url = reverse("user-list", args=[request.user.username]) return HttpResponseRedirect(url) else: form = DeliciousImportForm() template_name = "bookmarks/delicious_import.html" context = {'form': form} return(template_name, context)