def deleteAuthor(request, pk):
    author = Author.get_by_id(pk)
    if request.method == 'POST':
        Author.delete_by_id(pk)
        return redirect('/authors')
    context = {'item': author}
    return render(request, 'author/delete.html', context)
Beispiel #2
0
def register(request):
	args={}
	args.update(csrf(request))
	if request.POST:
		username = request.POST.get('username', '')
		email 	 = request.POST.get('email', '')
		nickname = request.POST.get('nickname', '')
		password = request.POST.get('password', '')
		password1= request.POST.get('password1', '')
		if password != password1:
			args['login_error'] = "Пароли не совпадают"
			return render_to_response('forms/register.html', args)
		if password is None:
			args['login_error'] = "Пароль обязателен"
			return render_to_response('forms/register.html', args)
		if User.objects.get(username=username):
			args['login_error'] = "Логин уже занят"
			return render_to_response('forms/register.html', args)
		user = User.objects.create_user(username, email, password)
		user.save()
		author = Author(user=user, nickname=nickname, avatar='static/empty.png')
		author.save()
		return redirect('/auth/login/')			
	else:
		return render_to_response('forms/register.html', args)
Beispiel #3
0
    def identifyAuthor(self):
        print("Creating author")
        channel = self.tree.find("channel")
        author_tree = channel.find("{http://wordpress.org/export/1.2/}author")
        self.author_name = author_tree.find("{http://wordpress.org/export/1.2/}author_login").text
        author_email = author_tree.find("{http://wordpress.org/export/1.2/}author_email").text

        users = User.objects.filter(username = self.author_name)
        if len(users) == 0:
            print("Creating user {0} with password 'password', don't forget to change it...".format(self.author_name))
            admin = User.objects.create_user(self.author_name, author_email, "password")
            admin.is_superuser = True
            admin.is_staff = True
            admin.save()
        else:
            print("User {0} found, skipping".format(users[0].username))
            admin = users[0]
        
        authors = Author.objects.filter(user = admin)
        if len(authors) == 0:
            print("Creating author for user {0}".format(admin.username))
            author = Author()
            author.user = admin
            author.save()
            self.author = author
        else:
            print("Author {0} present, skipping".format(authors[0].user.username))
            self.author = authors[0]
Beispiel #4
0
def createAuthor(request):

    if request.method == 'POST':
        form = CreateAuthorForm(request.POST)

        if form.is_valid():
            name = form.cleaned_data['name']
            birthDate = form.cleaned_data['birthDate']
            deathDate = form.cleaned_data['deathDate']
            nationality = form.cleaned_data['nationality']

            auteur = Author(name=name,
                            birthDate=birthDate,
                            deathDate=deathDate,
                            nationality=nationality)

            auteur.save()

            messages.add_message(request, messages.INFO,
                                 'L\'auteur à été créé')
            return redirect('author-list', )

        else:
            pass

    else:
        form = CreateAuthorForm()

    return render(request, "author/create.html", {
        'form': form,
    })
Beispiel #5
0
def create_author_object_based_on_book_dict_and_save_in_db(book_dict):
    authors_list = book_dict["authors"]
    for author in authors_list:
        try:
            object_allready_in_db = Author.objects.get(authorName=author)
            return object_allready_in_db
        except Author.DoesNotExist:
            new_author_object = Author(authorName=author)
            new_author_object.save()
            return new_author_object
def createAuthor(request):
    form = AuthorForm()
    context = {'form': form}
    if request.method == 'POST':
        form = AuthorForm(request.POST)
        if form.is_valid():
            Author.create(request.POST['name'], request.POST['surname'],
                          request.POST['patronymic'])
            return redirect("/authors")

    return render(request, 'author/author_form.html', context)
Beispiel #7
0
def setup():
    error = ''
    form = SetupForm()
    if form.validate_on_submit():

        salt = bcrypt.gensalt()
        hashed_pwd = bcrypt.hashpw(form.password.data.encode('utf-8'), salt)

        author = Author(form.fullname.data, form.email.data,
                        form.username.data, hashed_pwd, True)
        db.session.add(author)
        db.session.flush()
        if author.id:
            blog = Blog(form.name.data, author.id)
            db.session.add(blog)
            db.session.flush()
        else:
            db.session.rollback()
            error = 'err. creatin user'

        if author.id and blog.id:
            db.session.commit()
        else:
            db.session.rollback()
            error = 'err.creatin blog'

        flash('blog created')
        redirect(url_for('admin'))

    return render_template('blog/setup.html', form=form, error=error)
Beispiel #8
0
def setup():
    error = None
    form = SetupForm()
    if form.validate_on_submit():
        author = Author(form.fullname.data, form.email.data,
                        form.username.data, form.password.data, True)
        db.session.add(author)
        db.session.flush()
        if author.id:
            blog = Blog(form.name.data, author.id)
            db.session.add(blog)
            db.session.flush()
        else:
            db.session.rollback()
            error = "Error creating user"

        if author.id and blog.id:
            db.session.commit()
            flash("Blog created")
            return redirect(url_for('admin'))
        else:
            db.session.rollback()
            error = "Error creating blog"

    return render_template('blog/setup.html', form=form)
Beispiel #9
0
def setup():
    form = SetupForm()
    error = ""
    # taking data from form and adding that data it to the table
    if form.validate_on_submit():
        salt = bcrypt.gensalt()  # generating salt
        hashed_password = bcrypt.hashpw(form.password.data.encode('utf8'),
                                        salt)
        author = Author(form.fullname.data, form.email.data,
                        form.username.data, hashed_password, True)
        db.session.add(author)
        db.session()
        db.session.flush()
        if author.id:
            blog = Blog(form.name.data, author.id)
            db.session.add(blog)
            db.session.flush()
        else:
            db.session.rollback()
            error = "Error Creating user"
        if author.id and blog.id:
            db.session.commit()
            flash("Blog Created")
            return redirect(url_for('admin'))
        else:
            db.session.rollback()
            error = "Error Creating Blog"
    return render_template('blog/setup.html', form=form)
def setup():
    form = SetupForm()
    error = None
    if form.validate_on_submit():

        # Encrypt password data
        salt = bcrypt.gensalt()
        hashed_password = bcrypt.hashpw(form.password.data, salt)

        # Create Author entitiy
        author = Author(form.fullname.data, form.email.data,
                        form.username.data, hashed_password, True)
        db.session.add(author)
        db.session.flush()

        # Check author entity for errors, create Blog entity if none
        if author.id:
            blog = Blog(form.name.data, author.id)
            db.session.add(blog)
            db.session.flush()
        else:
            db.session.rollback()
            error = "Error creating user"

        # Check Blog entity for errors
        if author.id and blog.id:
            db.session.commit()
            flash("Blog Created")
            return redirect(url_for('admin'))
        else:
            db.session.rollback()
            error = "Error creating blog"

    return render_template('blog/setup.html', form=form)
Beispiel #11
0
def setup():
    form = SetupForm()
    error = ""
    if form.validate_on_submit():
        salt = bcrypt.gensalt()
        hashed_password = bcrypt.hashpw(form.password.data, salt)
        author = Author(form.fullname.data, form.email.data,
                        form.username.data, hashed_password, True)
        db.session.add(author)
        db.session.flush()
        if author.id:
            blog = Blog(form.name.data, author.id)
            db.session.add(blog)
            db.session.flush()
        else:
            db.session.rollback()
            error = "Error creating user"
        if author.id and blog.id:
            db.session.commit()
            flash("Blog created")
            return redirect(url_for('index'))
        else:
            db.session.rollback()
            error = "Error creating blog"
    return render_template('blog/setup.html', form=form, error=error)
Beispiel #12
0
 def test_get_by_id_positive(self):
     """Positive test of the CustomUser.get_by_id() method"""
     author = Author.get_by_id(101)
     self.assertEqual(author.id, 101)
     self.assertEqual(author.name, 'author1')
     self.assertEqual(author.surname, "s1")
     self.assertEqual(author.patronymic, "p1")
Beispiel #13
0
 def test_create(self):
     author = Author.create(name="testName", surname="s1", patronymic="p1")
     author = Author.objects.get(id=author.id)
     self.assertIsInstance(author, Author)
     self.assertEqual(author.name, "testName")
     self.assertEqual(author.surname, "s1")
     self.assertEqual(author.patronymic, "p1")
Beispiel #14
0
def add_user():

    form = RegisterForm()

    blog = Blog.query.all()

    if request.method == 'POST':
        if form.validate_on_submit():

            salt = bcrypt.gensalt()
            hashed_password = bcrypt.hashpw(form.password.data.encode('utf8'),
                                            salt)

            fullname = form.fullname.data
            email = form.email.data
            username = form.username.data
            password = hashed_password
            is_author = True
            is_admin = form.is_admin.data
            is_active = True

            author = Author(fullname, email, username, password, is_author,
                            is_admin, is_active)

            db.session.add(author)
            db.session.commit()

            flash('User added successfully')

            return redirect(url_for('admin_app.admin'))

    return render_template('/author/register.html', form=form, blog=blog)
Beispiel #15
0
def setup():
    blogs = Blog.query.count()
    if blogs():
        return redirect(url_for('admin'))
    form = SetupForm()
    if form.validate_on_submit():
        salt = bcrypt.gensalt()
        hashed_password = bcrypt.hashpw(form.password.data, salt)
        author = Author(
            form.fullname.data,
            form.email.data,
            form.username.data,
            hashed_password,
            True
        )
        db.session.add(author)
        db.session.flush()
        if author.id:
            blog = Blog(form.name.data, author.id)
            db.session.add(blog)
            db.session.flush()
        else:
            db.session.rollback()
            error = "Error Creating User"
        if author.id and blog.id:
            db.session.commit()
        else:
            db.session.rollback()
            error = "Error Creating Blog"
        flash('Blog Created')
        return redirect('/admin')
    return render_template('blog/setup.html', form=form)
Beispiel #16
0
def setup():
    form = SetupForm()
    error = ''
    if form.validate_on_submit():
        salt = bcrypt.gensalt()
        hashed_password = bcrypt.hashpw(form.password.data, salt)
        author = Author(
            form.fullname.data,
            form.email.data,
            form.username.data,
            hashed_password, #bcrypt hashed
            True
            )
        # send to db
        db.session.add(author)
        # needs to match "admin = ...db.ForeignKey('author.id'))" in models.py
        db.session.flush() # sqlalchemy simulates record being written to db = check
        if author.id:
            blog = Blog(
                form.name.data,
                author.id
                )
            db.session.add(blog)
            db.session.flush()
        else:
            db.session.rollback()
            error = 'Error creating user'
        if author.id and blog.id:
            db.session.commit()
            flash('Blog created')
            return redirect(url_for('index'))
        else:
            db.session.rollback()
            error = 'Error creating blog'
    return render_template('blog/setup.html', form=form, error=error)
Beispiel #17
0
def setup():
    form = SetupForm()
    error = ""

    if form.validate_on_submit():
        salt = bcrypt.gensalt()
        hashed_password = bcrypt.hashpw(form.password.data, salt)
        author = Author(form.fullname.data, form.email.data,
                        form.username.data, hashed_password, True)
        db.session.add(author)
        # this will flush data, but not commit, and this gives us an author.id
        db.session.flush()
        if author.id:
            # have author id, so record does not already exit in author table
            # now build blog record
            blog = Blog(form.name.data, author.id)
            db.session.add(blog)
            db.session.flush()
        else:
            db.session.rollback()
            error = "Error creating user"

        if author.id and blog.id:
            db.session.commit()
            flash("Blog created")
            return redirect(url_for('index'))
        else:
            db.session.rollback()
            error = "Error creating blog"

    return render_template('blog/setup.html', form=form, error=error)
Beispiel #18
0
def twitter_auth():
    oauth_verifier = request.args.get('oauth_verifier')
    access_token = get_access_token(session['request_token'], oauth_verifier)
    print(access_token['screen_name'])
    user = Author.query.filter_by(
        username=access_token['screen_name'], ).first()
    if user:
        session['username'] = user.username
        session['is_author'] = user.is_author
        session['user_id'] = user.id
        if 'next' in session:
            next = session.get('next')
            session.pop('next')
            return redirect(next)
        else:
            return redirect(url_for('index'))

    if not user:
        salt = bcrypt.gensalt()
        hashed_password = bcrypt.hashpw("password", salt)
        author = Author(access_token['screen_name'],
                        access_token['screen_name'] + "@defaultemail.com",
                        access_token['screen_name'], hashed_password, True)
        db.session.add(author)
        db.session.flush()
        db.session.commit()
        return redirect(url_for('success'))
    abort(403)
Beispiel #19
0
def setup():
    form = SetupForm()
    error = ""
    if form.validate_on_submit():
        author = Author(
                form.fullname.data,
                form.email.data,
                form.username.data,
                bcrypt.generate_password_hash(form.password.data),
                True
            )
        db.session.add(author)
        db.session.flush()
        if author.id:
            blog = Blog(
                    form.name.data,
                    author.id
                )
            db.session.add(blog)
            db.session.flush()
            if author.id and blog.id:
                db.session.commit()
                flash("Blog created")
                return redirect(url_for("index"))
            else:
                error = "Error creating blog"
                db.session.rollback()
        else:
            error = "Error creating author"
            db.session.rollback()
    return render_template("blog/setup.html", form=form, error=error)
Beispiel #20
0
def setup():
	form = SetupForm()

	if request.method == 'POST':

		if form.validate_on_submit():
			
			blog_name = form.blog_name.data
			author_name = form.author_name.data
			email = form.email.data
			username = form.username.data
			password = form.password.data
			is_author = True

			author = Author(author_name, email, username, password, is_author)
			db.session.add(author)
			db.session.flush()


			if author.id:
				blog = Blog(blog_name, author.id)
				db.session.add(blog)
				db.session.commit()

				return redirect(url_for('login'))

			else:
				db.session.rollback()
				return 'Form set up Failed'

			return 'Form Set Up Done!!'

	return render_template('author/setup.html', form = form)
Beispiel #21
0
def add(request):
    message = ""
    if request.method == "POST":
        author_form = AuthorForm(request.POST)
        if author_form.is_valid():
            author = Author(
                name=author_form.cleaned_data["name"],
                nickname=author_form.cleaned_data["nickname"],
                gender=author_form.cleaned_data["gender"],
            )
            author.save()
            return HttpResponseRedirect("/view/author/{}/".format(author.id))
    else:
        author_form = AuthorForm()
    return render_to_response(
        "author/add.html", {"form": author_form, "message": message}, context_instance=RequestContext(request)
    )
Beispiel #22
0
def create_author_secret_key_and_send_auth_email(sender, instance: Author,
                                                 **kwargs):
    """
    Happens before an Author instance is saved - generates a secret key
    from uuid.uuid5's SHA1 hash with the namespace as a uuid1 generated
    from instance.pk and name as the username.

    TODO set up celery to send authentication email
         in the background so that the server can
         respond with something for the time being.
    """

    # Generate secret key.
    namespace = uuid.uuid1(instance.pk)
    secret_key = uuid.uuid5(namespace, instance.username)

    if not (instance.secret_key
            or connection.settings_dict['NAME'].startswith('test_')):
        # Since Author does not have a previous
        # secret key, it means that this is a new
        # user and hence has to be sent an email
        # with the confirmation link to be verified.
        # The second half of this is for testing
        # purposes - you don't want to email all
        # the fake authors that are created during testing.
        # This is also why the secret_key is generated
        # outside of this if clause because we NEED the
        # secret_key field to be populated regardless.

        subject, from_email, to = 'Welcome To The Medialist', settings.EMAIL_HOST_USER, instance.email
        html_content = render_to_string(
            'email/email-confirmation.html', {
                'activation_url':
                'http://' + 'localhost:8000' + reverse(
                    'author:verify', kwargs={'secret_key': str(secret_key)})
            })
        text_content = strip_tags(html_content)

        instance.email_user(subject,
                            text_content,
                            from_email,
                            html_message=html_content)

    instance.secret_key = secret_key
Beispiel #23
0
def register():
    form = RegisterForm()
    if form.validate_on_submit():
        hashed_password = generate_password_hash(form.password.data)
        author = Author(form.full_name.data, form.email.data, hashed_password)
        db.session.add(author)
        db.session.commit()
        flash('You are now registered, please login')
        return redirect(url_for('.login'))
    return render_template('/author/register.html', form=form)
Beispiel #24
0
def register():
    form = RegisterForm()
    if form.validate_on_submit():
        hashed_password = generate_password_hash(form.password.data)
        author = Author(form.full_name.data, form.email.data, hashed_password)
        db.session.add(author)
        db.session.commit()
        flash("You have successfully registered", "success")
        return render_template("author/login.html", form=form)
    return render_template("author/register.html", form=form)
def updateAuthor(request, pk):
    author = Author.get_by_id(pk)
    form = AuthorForm(instance=author)
    if request.method == 'POST':
        form = AuthorForm(request.POST, instance=author)
        if form.is_valid():
            form.save()
            return redirect("/authors")
    context = {'form': form}
    return render(request, 'author/author_form.html', context)
Beispiel #26
0
    def setUp(self):
        """ Create a user object to be used by the tests """
        time_mock = datetime.datetime(2017, 4, 10, 12, 00, tzinfo=pytz.utc)
        with mock.patch('django.utils.timezone.now') as mock_time:
            mock_time.return_value = time_mock
            self.user = CustomUser(id=111, email='*****@*****.**', password='******', first_name='fname',
                                   middle_name='mname',
                                   last_name='lname')
            self.user.save()
            self.user_free = CustomUser(id=222, email='*****@*****.**', password='******', first_name='2fname',
                                        middle_name='2mname',
                                        last_name='2lname')
            self.user_free.save()

            self.author1 = Author(id=101, name="author1", surname="s1", patronymic="p1")
            self.author1.save()

            self.author2 = Author(id=102, name="author2", surname="s2", patronymic="p2")
            self.author2.save()

            self.book1 = Book(id=101, name="book1", description="description1", count=1)
            self.book1.save()
            self.book1.authors.add(self.author1)
            self.book1.save()

            self.book2 = Book(id=102, name="book2", description="description2")
            self.book2.save()
            self.book2.authors.add(self.author2)
            self.book2.save()

            self.book3 = Book(id=103, name="book3", description="description3")
            self.book3.save()
            self.book3.authors.add(self.author1)
            self.book3.authors.add(self.author2)
            self.book3.save()

            self.order1 = Order(id=101, user=self.user, book=self.book1, plated_end_at=TEST_DATE)
            self.order1.save()
            self.order2 = Order(id=102, user=self.user, book=self.book2, plated_end_at=TEST_DATE)
            self.order2.save()
            self.order3 = Order(id=103, user=self.user, book=self.book3, end_at=TEST_DATE_END, plated_end_at=TEST_DATE)
            self.order3.save()
Beispiel #27
0
def register():
    form = RegisterForm()
    if form.validate_on_submit():
        salt = bcrypt.gensalt()
        hashed_password = bcrypt.hashpw(form.password.data, salt)
        author = Author(form.fullname.data, form.email.data,
                        form.username.data, hashed_password, False)
        db.session.add(author)
        db.session.commit()
        return redirect('/success')
    return render_template('author/register.html', form=form)
Beispiel #28
0
def register():
    form = RegisterForm()
    if form.validate_on_submit():
        hashed_password = generate_password_hash(
            form.password.data)  # сохраним пароль в хешированном виде
        author = Author(form.full_name.data, form.email.data, hashed_password)
        db.session.add(author)
        db.session.commit()
        flash('Подзравляем, Вы зарегестрировались! Можете войти на форум.')
        return redirect(url_for('author_app.login'))
    return render_template('author/register.html', form=form)
Beispiel #29
0
def list(request):
    # Handle file upload
    if request.method == 'POST':
        form = DocumentForm(request.POST, request.FILES)
        if form.is_valid():
            newdoc = Author(docfile = request.FILES['docfile'])
            newdoc.save()

            # Redirect to the document list after POST
            return HttpResponseRedirect(reverse('myproject.myapp.views.list'))
    else:
        form = DocumentForm() # A empty, unbound form

    # Load documents for the list page
    documents = Author.objects.all()

    # Render list page with the documents and the form
    return render_to_response(
        'author/list.html',
        {'documents': documents, 'form': form},
        context_instance=RequestContext(request)
    )
def get_author_by_id(request, id=0):
    author_by_id = Author.get_by_id(id)
    bks = [
        book for book in list(Book.get_all())
        if author_by_id in book.authors.all()
    ]
    # books = list(Book.get_all())
    return render(request,
                  'author/get_author_by_id.html',
                  context={
                      'author_by_id': author_by_id,
                      'books': bks
                  })
Beispiel #31
0
def register():

    form = RegisterForm()

    if form.validate_on_submit():
        author = Author(form.full_name.data,
                        form.email.data,
                        password=Password.generate_password_hash(
                            form.password.data))
        db.session.add(author)
        db.session.commit()
        flash(constants.REGISTRATION_SUCCESSFUL)
        return url_secure_redirect("author_app.login")
    return render_template('author/register.html', form=form)
Beispiel #32
0
    def handle(self, *args, **options):
        try:
            authors_list = []
            with open(options["csvpath"]) as csvfile:
                reader = csv.DictReader(csvfile)
                for row in reader:
                    authors_list.append(Author(name=row["name"]))

            break_size = len(authors_list) / 2
            Author.objects.bulk_create(authors_list,
                                       ignore_conflicts=True,
                                       batch_size=break_size)
            print("All data have been imported to database")
        except Exception as e:
            logger.error(e)
Beispiel #33
0
    def register(cls, user_data):
        User = get_user_model()
        logger.info('Creating user model.')
        new_user = User.objects.create_user(
            email=user_data.get('email'),
            first_name=user_data.get('first_name'),
            last_name=user_data.get('last_name'),
            password=user_data.get('password'),
            is_staff=True)
        logger.info('Creating authentication token for user.')
        token, created = Token.objects.get_or_create(user=new_user)

        logger.info('Creating author profile for new user.')
        author = Author(skills=user_data.get('skills'))
        return token, new_user, author
def index(request):
    context = RequestContext(request)
    if request.method == 'DELETE':
        if request.user.is_authenticated():
            category = QueryDict(request.body).get('category_name')
            post_id = QueryDict(request.body).get('post_id')

            try:
                post = Post.objects.get(guid=post_id)
                PostCategory.removeCategory(post, category, Author.get_author_with_username(request.user.username))

                return HttpResponse(json.dumps({'msg': 'category deleted'}),
                                    content_type="application/json",
                                    status=200)
            except Exception as e:
                return HttpResponse(e.message,
                                    content_type="text/plain",
                                    status=400)

        else:
            loginError(context)

    elif request.method == 'POST':
        if request.user.is_authenticated():
            category = QueryDict(request.body).get('category_name')
            post_id = QueryDict(request.body).get('post_id')

            try:
                post = Post.objects.get(guid=post_id)
                PostCategory.addCategoryToPost(post, category)

                return HttpResponse(json.dumps({'msg': 'category added'}),
                                    content_type="application/json")
            except Exception as e:
                return HttpResponse(e.message,
                                    content_type="text/plain",
                                    status=400)
        else:
            loginError(context)
def index(request):
    context = RequestContext(request)
    if request.method == 'GET':
        if 'application/json' in request.META['HTTP_ACCEPT']:
            return HttpResponseRedirect('/api/author/posts', status=302)
        else:
            if request.user.is_authenticated():
                try:
                    # get only posts made by friends and followees
                    viewer = Author.objects.get(user=request.user)
                    return render_to_response('index.html', _getAllPosts(viewer=viewer, time_line=True), context)
                except Author.DoesNotExist:
                    return _render_error('login.html', 'Please log in.', context)
            else:
                return _render_error('login.html', 'Please log in.', context)

    elif request.method == 'DELETE':
        try:
            if request.user.is_authenticated():
                post_utils.deletePost(QueryDict(request.body).get('post_id'))

                return HttpResponse(json.dumps({'msg': 'post deleted'}),
                                    content_type="application/json")
            else:
                return _render_error('login.html', 'Please log in.', context)
        except Exception as e:
            print "Error in posts: %s" % e

    elif request.method == 'POST':
        try:
            if request.user.is_authenticated():
                title = request.POST.get("title", "")
                description = request.POST.get("description", "")
                content = request.POST.get("text_body", "")
                author = Author.objects.get(user=request.user)
                visibility = request.POST.get("visibility_type", "")
                content_type = Post.MARK_DOWN if request.POST.get(
                    "markdown_checkbox", False) else Post.PLAIN_TEXT
                categories = request.POST.get("categories")

                new_post = Post.objects.create(title=title,
                                               description=description,
                                               guid=uuid.uuid1(),
                                               content=content,
                                               content_type=content_type,
                                               visibility=visibility,
                                               author=author,
                                               publication_date=timezone.now())

                if visibility == Post.ANOTHER_AUTHOR:
                    try:
                        visible_author = request.POST.get("visible_author", "")
                        visible_author_obj = Author.get_author_with_username(
                            visible_author)

                        VisibleToAuthor.objects.create(
                            visibleAuthor=visible_author_obj, post=new_post)
                    except Author.DoesNotExist:
                        # TODO: not too sure if care about this enough to
                        # handle it
                        print("hmm")

                # TODO: handle multiple image upload
                if len(request.FILES) > 0 and 'thumb' in request.FILES:
                    profile = DocumentForm(request.POST, request.FILES)
                    image = DocumentForm.createImage(
                        profile, request.FILES['thumb'])
                    PostImage.objects.create(post=new_post, image=image)

                category_list = categories.split(',')
                for category in category_list:
                    if len(category.strip()) > 0:
                        PostCategory.addCategoryToPost(new_post, category)

                viewer = Author.objects.get(user=request.user)
                return render_to_response('index.html', _getAllPosts(viewer=viewer, time_line=True), context)
            else:
                return redirect('login.html', 'Please log in.', context)
        except Exception as e:
            print "Error in posts: %s" % e

    return HttpResponseRedirect(request.META.get('HTTP_REFERER'))
Beispiel #36
0
def load_json_site(fic):
    site = {}
    with open(fic, 'r') as json_file:
        site = json.load(json_file)
    for a_json in site['Author']:
        try :
            a = Author.objects.get(pk=a_json['pk'])
        except:
            a = Author()
        a.load_from_dict(a_json)
        a.save()
    for a_json in site['Category']:
        try :
            a = Category.objects.get(pk=a_json['pk'])
        except:
            a = Category()
        a.load_from_dict(a_json)
        a.save()
    for a_json in site['Event']:
        try :
            a = Event.objects.get(pk=a_json['pk'])
        except:
            a = Event()
        a.load_from_dict(a_json)
        a.save()
    for a_json in site['Article']:
        try :
            a = Article.objects.get(pk=a_json['pk'])
        except:
            a = Article()
        a.load_from_dict(a_json)
        a.save()
    for a_json in site['Part']:
        try :
            a = Part.objects.get(pk=a_json['pk'])
        except:
            a = Part()
        a.load_from_dict(a_json)
        a.save()