Beispiel #1
0
def create_item():
    """Add an item.

    Accepts GET and POST methods.
    Redirect if user is not signed in.

    """
    if not signed_in():
        flash('You must be logged in to add an item.')
        return redirect(url_for('catalog.full_catalog'))

    if request.method == 'POST':
        name = request.form.get('name')
        description = request.form.get('description')
        category = request.form.get('category')
        csrftoken = request.form.get('csrftoken')
        if csrftoken != session['csrf']:
            flash('Invalid CSRF token.')
        elif not name or not description or not category:
            flash('All fields must be filled.')
        else:
            # Everything valid. Create item.
            del session['csrf']
            item = Item.create_item(name, description, category,
                                    session['user_id'])
            if item:
                flash('Item successfully updated.')
                return redirect(
                    url_for('catalog.show_item',
                            category_name=item.category,
                            item_name=item.name))
    categories = Item.get_categories()
    session['csrf'] = token()
    return render_template('catalog-add.html', categories=categories)
Beispiel #2
0
def wiki(request, page):
    # Check if user is signed in
    name = signed_in(request)
    
    # Have to do special stuff with handling the app home URN index
    if request.path.endswith("/"):
        page = "index"
    
    # Are we looking at an older version, from url '?v=(version_number)'
    v = request.GET.get('v')
    
    # So our url is a valid existing wiki entry...
    if page and WikiPage.objects.filter(page_url=page).exists():
        # i = grab page, j = grab history (if it exists)
        i = WikiPage.objects.get(page_url=page)
        j = return_wikipagehistory(i, v)
        # page not there? just go (to the) home (url for this app)        
        if not j:
            if page == "index": page = ''
            return redirect('final_wiki', page=page)

        # Regular pass along to template
        d=dict(content=j.content, page=page, name=name, version=v)
        return render_to_response('7_final/index.html', d, context_instance=(RequestContext(request)))
    else:
        # Page exists, but there is no other versions, so time to create new versions!        
        return redirect('final__edit', page=page)
Beispiel #3
0
def _edit(request, page):
    # Have to do special stuff with handling the app home URN index
    if page == None:
        page = 'index'

    # Check if user is signed in, if not, go back to the app index       
    name = signed_in(request)
    if not name: return redirect('final_wiki', page='')

    # Is this post?
    if request.method == "POST":
        # Grab post info
        form = SubmitForm(request.POST)
        content = form.data['content']
        
        if form.is_valid():
            # If this wikipage doesn't exist, create new and save
            if not WikiPage.objects.filter(page_url=page).exists():
                m = WikiPage(page_url=page)
                m.save()
            
            # If it does, grab it so we can update this page's history
            else:
                m = WikiPage.objects.get(page_url=page)
            
            # Update this pages wikihistory!
            n = WikiPageHistory(page=m, content=content)
            n.save()
            
            # Redirect back to the new page (handle index URN)
            if page == 'index':
                page = ''
            return redirect('final_wiki', page=page)

    # No post, so present the form to edit a wikipage
    else:
        # Create wikipage form
        form = SubmitForm(request.POST)

        # Show the values for the current page in the wikipage form        
        if WikiPage.objects.filter(page_url=page).exists():
            i = WikiPage.objects.get(page_url=page)
            j = return_wikipagehistory(i, request.GET.get('v'))
            
            # If there is no page history, make sure the index (/) is referred to as (index)         
            if not j:
                if page == "index":
                    page = ''             
                return redirect('final__edit', page=page)
            
            # Where we pass the form content to the _edit view          
            content = j.content
        else:
            # Just pass blank content to the form, this is a new page
            content = ""
    
    # Pass along stuff and render 
    d=dict(content=content, page=page, name=name)
    return render_to_response("7_final/edit.html", d, context_instance=RequestContext(request))
Beispiel #4
0
def edit_item(category_name, item_name):
    """Edit an item.

    Accepts GET and POST methods.
    Redirect to show_item page if user is not authenticated/authorized.

    Parameters:
        category_name: category name of item to edit
        item_name: name of the item to edit
    """
    item = Item.by_name(category_name, item_name)
    if not item:
        flash('Could not find item: {}.'.format(item_name))
        return redirect('/')

    if not signed_in():
        flash('You must be logged in to edit an item.')
        return redirect(
            url_for('catalog.show_item',
                    category_name=item.category,
                    tem_name=item.name))

    if not item.is_owned_by(session['user_id']):
        flash('You do not have permission to edit this item.')
        return redirect(
            url_for('catalog.show_item',
                    category_name=item.category,
                    item_name=item.name))

    if request.method == 'POST':
        name = request.form.get('name')
        description = request.form.get('description')
        category = request.form.get('category')
        csrftoken = request.form.get('csrftoken')
        if csrftoken != session['csrf']:
            flash('Invalid CSRF token.')
        elif not name or not description or not category:
            flash('All fields must be filled.')
        else:
            del session['csrf']
            item.name = name
            item.description = description
            item.category = category
            flash('Item successfully updated.')
            return redirect(
                url_for('catalog.show_item',
                        category_name=item.category,
                        item_name=item.name))

    categories = Item.get_categories()
    category_items = Item.by_category(category_name)
    session['csrf'] = token()
    return render_template('catalog-item-edit.html',
                           item=item,
                           categories=categories,
                           category_items=category_items)
Beispiel #5
0
def delete_item(category_name, item_name):
    """Delete an item.

    Accepts GET and POST methods.
    Redirect to show_item page if user is not authenticated/authorized.

    Parameters:
        category_name: category name of item to delete
        item_name: name of the item to delete
    """
    item = Item.by_name(category_name, item_name)
    if not item:
        flash('Could not find item: {}.'.format(item_name))
        return redirect('/')

    if not signed_in():
        flash('You must be logged in to delete an item.')
        return redirect(
            url_for('catalog.show_item',
                    category_name=item.category,
                    item_name=item.name))

    if not item.is_owned_by(session['user_id']):
        flash('You do not have permission to delete this item.')
        return redirect(
            url_for('catalog.show_item',
                    category_name=item.category,
                    item_name=item.name))

    if request.method == 'POST':
        csrftoken = request.form.get('csrftoken')
        if csrftoken != session['csrf']:
            flash('Invalid CSRF token.')
        else:
            del session['csrf']
            item.delete()
            flash('Item successfully deleted.')
            return redirect('/')

    categories = Item.get_categories()
    category_items = Item.by_category(category_name)
    session['csrf'] = token()
    return render_template('catalog-item-delete.html',
                           item=item,
                           categories=categories,
                           category_items=category_items)
Beispiel #6
0
def index(request, json_api):
    name = signed_in(request)

    age = 0
    if cache.get('POSTS') == None:
        posts = Post.objects.all().order_by("-date_created")[:10]
        update_cache('POSTS', posts)
    else:
        posts, age = cache.get('POSTS')
        age = (datetime.utcnow() - age).total_seconds()

    # Was .json at the end of the URI?
    if json_api:
        # Return a response with correct content-type and generated json
        return HttpResponse(generate_json(posts), content_type="application/json")

    # Render home with list of entries
    d=dict(posts=posts, age=age, name=name)
    return render_to_response("5_jsonapiblog/index.html", d, context_instance=RequestContext(request))
Beispiel #7
0
def signup(request):
    # Check if user is signed in (check cookie)
    name = signed_in(request)

    users = User.objects.all()
    # Check if request is a POST, then process
    if request.method == 'POST':
        # Request is POST, validate input
        # Django automatically espaces form data
        form = RegisterForm(request.POST)
        # Get username and email field so form is repopulated
        username = form.data['username']
        email = form.data['email']
        password = form.data['password']
        
        if form.is_valid():
            try: 
                # Create a new User object
                m = User.objects.create_user(username=username,
                                             email=email,
                                             password=password)
                # Save the object
                m.save()
                # Create the response
                response = redirect("cookiesusers_welcome")
                # Set the cookie
                response.set_cookie("user_id", make_secure_val(str(m.pk)), path="/")
                # Return redirect/set-cookie
                return response
            except User.DoesNotExist:
                # Fail safe; user check occurs in clean_user
                raise Http404()
    else:
        # Request is not POST, leave the form blank
        form = RegisterForm()
        username = ""
        email = ""
    
    # Render template with form data
    # Never repopulate password or verify field, but pass errors
    d=dict(username=username, email=email, error=form.errors, name=name)
    return render_to_response("4_cookiesusers/signup.html", d, context_instance=RequestContext(request))
Beispiel #8
0
def post(request, pk, json_api):
    name = signed_in(request)

    age = 0
    if cache.get('POST_ID_' + str(pk)) == None:
        post = get_object_or_404(Post, pk=int(pk))
        update_cache('POST_ID_'+ str(pk), post)
    else:
        post, age = cache.get('POST_ID_' + str(pk))
        age = (datetime.utcnow() - age).total_seconds()
    
    # Was .json at the end of the URI?
    if json_api:
        # Return a response with correct content-type and generated json
        return HttpResponse(generate_json(post), content_type="application/json")
    
    # Get post from Post model with pk passed from the URLconf, or throw 404
    post = get_object_or_404(Post, pk=int(pk))
    d=dict(post=post, age=age, name=name)
    return render_to_response("5_jsonapiblog/post.html", d, context_instance=RequestContext(request))
Beispiel #9
0
def signup(request):
    name = signed_in(request)

    users = User.objects.all()

    if request.method == 'POST':
        form = RegisterForm(request.POST)
        username = form.data['username']
        email = form.data['email']
        password = form.data['password']
        
        if form.is_valid():
            try: 
                # Create a new User object
                m = User.objects.create_user(username=username,
                                             email=email,
                                             password=password)
                # Save the object
                m.save()
                # Create the response
                response = redirect("jsonapiblog_welcome")
                # Set the cookie
                response.set_cookie("user_id", make_secure_val(str(m.pk)), path="/")
                # Return redirect/set-cookie

                return response
            except User.DoesNotExist:
                # Fail safe; user check occurs in clean_user
                raise Http404()
    else:
        # Request is not POST, leave the form blank
        form = RegisterForm()
        username = ""
        email = ""
    
    # Render template with username, email, form.errors
    # Never repopulate password or verify field, but pass errors
    d=dict(username=username, email=email, error=form.errors, name=name)
    return render_to_response("5_jsonapiblog/signup.html", d, context_instance=RequestContext(request))
Beispiel #10
0
def _history(request, page):
    # Handle index (/) page naming
    if page == None: page = 'index'
    
    # Check if user is signed in
    name = signed_in(request)
    if not name: return redirect('final_wiki', page='')
    
    # blank version #
    v = ''

    # More than one version of this page exist?
    if WikiPage.objects.filter(page_url=page).exists():
        i = WikiPage.objects.get(page_url=page)
        try:
            v = WikiPageHistory.objects.filter(page=i).order_by('-version')
        # Only one version exists        
        except IndexError:
            v = WikiPageHistory.objects.get(page=i)
    
    # Pass along stuff and render 
    d=dict(versions=v, page=page, name=name)
    return render_to_response('7_final/history.html', d, context_instance=RequestContext(request))
Beispiel #11
0
def login(request):
    # Check if user is signed in (check cookie)
    name = signed_in(request)

    users = User.objects.all()
    
    if request.method == 'POST':
        form = LoginForm(request.POST)
        username = form.data['username']
        
        if form.is_valid():
            m = User.objects.get(username=username)
            request = redirect('cookiesusers_welcome')

            request.set_cookie('user_id', make_secure_val(str(m.pk)), path='/')
            return request
        
    else:
        form = LoginForm()
        username = ""
        
    d=dict(username=username, error=form.errors, name=name)
    return render_to_response('4_cookiesusers/login.html', d, context_instance=RequestContext(request))
Beispiel #12
0
def newpost(request):
    name = signed_in(request)

    # Check if request is a POST, then process
    if request.method == 'POST':

        form = SubmitForm(request.POST)
        subject = form.data['subject']
        content = form.data['content']
        if form.is_valid():#
            # If form is valid, save new Post
            p = Post(subject=subject, content=content)
            p.save()
            # Redirect the browser to permae link ( p.pk = new post primary key)
            update_cache('POST_ID_' + str(p.pk), p)
            return HttpResponseRedirect("" + str(p.pk))
    else:
        # Request is not POST, leave the form blank
        form = SubmitForm()
        subject = ""
    
    # Render template with form data
    d=dict(subject=subject, error=form.errors, name=name)
    return render_to_response("5_jsonapiblog/newpost.html", d, context_instance=RequestContext(request))