Esempio n. 1
0
def entry(request):
    if request.session.has_key('logged_in'):
        now = datetime.datetime.now()
        if request.method == 'POST':
            form = EntryForm(request.POST)
            if form.is_valid():
                cd = form.cleaned_data
                now = datetime.datetime.now()
                strnow = now.strftime('%d/%m/%Y')
                author = cd['author']
                content = cd['content']
                e = Entry(date=now,
                          strdate=strnow,
                          author=author,
                          content=content)
                e.save()
                return HttpResponseRedirect('/diary/submitted/')
        else:
            form = EntryForm()
            return render(request, 'new_entry.html', {
                'form': form,
                'now': now
            })
    else:
        return render(request, 'login.html',
                      {'user_login': '******'})
Esempio n. 2
0
def edit(slug):
    entry = Entry.get(Entry.slug == slug)
    if entry.user == g.user or g.user.is_admin:
        form = EntryForm()
        if form.validate_on_submit():
            try:
                entry.title = form.title.data
                entry.date = form.date.data
                entry.time = form.time.data
                entry.learned = form.learned.data
                entry.resources = form.resources.data
                entry.slug = safe_slugify(form.title.data, entry)
                entry.save()
                if form.tags.data:
                    # clear and refresh tags in case any were removed
                    clear_tags(entry)
                    process_tags(form.tags.data, entry)
                flash("Entry updated successfully.")
                return redirect(url_for('detail', slug=entry.slug))
            except IntegrityError:
                flash("An entry with that title already exists.")
        else:
            flash_errors(form)
    else:
        # this should only be reached if user directly enters in url, as edit
        # link should not display if logged in user did not create entry
        return ("You know, it's really not nice to try to edit things that do "
                "not belong to you.")
    return render_template('edit.html', entry=entry, form=form)
Esempio n. 3
0
def edit(id):
    """The edit view"""
    journal_post = models.Entry.select().where(models.Entry.id == id).get()
    if request.method == 'GET':
        form = EntryForm(formdata=MultiDict(
            {
                'title': journal_post.title,
                'date': str(journal_post.date),
                'time_spent': journal_post.time_spent,
                'what_you_learned': journal_post.what_you_learned,
                'resources_to_remember': journal_post.resources_to_remember
            }))
    else:
        form = EntryForm()

    if form.validate_on_submit():
        journal_post.title = form.title.data.strip()
        journal_post.date = form.date.data
        journal_post.time_spent = form.time_spent.data
        journal_post.what_you_learned = form.what_you_learned.data.strip()
        journal_post.resources_to_remember = (
            form.resources_to_remember.data.strip())
        journal_post.save()
        return redirect(url_for('index'))
    return render_template('edit.html', form=form, journal_post=journal_post)
Esempio n. 4
0
def edit(id):
    title = "Edit Entry"
    user = User.query.get_or_404(g.user.id)
    entry = EntryClone.query.get_or_404(id)
    if not entry:
        abort(404)

    if (user.userInitial != entry.userInitial) and user.role != ROLE_ADMIN:
        flash('You are not allowed to edit this entry!', category='danger')
        return redirect(url_for('timetable', sem=entry.SemesterId))

    form = EntryForm()
    if form.validate_on_submit():
        entry.RoomId = form.RoomId.data
        entry.CourseCode = form.CourseCode.data
        entry.CourseType = form.CourseType.data
        entry.UserInitial = form.UserInitial.data
        db.session.add(entry)
        db.session.commit()
        flash('Slot Edited', category='success')
        myurl = app.config[
            "SERVER_BASE"] + "/timetable/" + entry.SemesterId + "?tutorial=&btn=edit"
        #return redirect(url_for('timetable',sem=entry.SemesterId))
        return redirect(myurl)
    else:
        form.RoomId.data = entry.RoomId
        form.CourseCode.data = entry.CourseCode
        form.CourseType.data = entry.CourseType
        form.UserInitial.data = entry.userInitial
    return render_template('edit.html', id=id, title=title, form=form)
Esempio n. 5
0
def edit(id):
    title="Edit Entry"
    user  = User.query.get_or_404(g.user.id)
    entry = EntryClone.query.get_or_404(id)
    if not entry:
        abort(404)

    if (user.userInitial != entry.userInitial) and user.role != ROLE_ADMIN :
        flash('You are not allowed to edit this entry!', category='danger')
        return redirect(url_for('timetable',sem=entry.SemesterId))

    form=EntryForm()
    if form.validate_on_submit():
        entry.RoomId=form.RoomId.data
        entry.CourseCode=form.CourseCode.data
        entry.CourseType=form.CourseType.data
        entry.UserInitial=form.UserInitial.data
        db.session.add(entry)
        db.session.commit()
        flash('Slot Edited', category='success')
        myurl =app.config["SERVER_BASE"]+"/timetable/"+entry.SemesterId+"?tutorial=&btn=edit"
        #return redirect(url_for('timetable',sem=entry.SemesterId))
        return redirect(myurl)
    else:
        form.RoomId.data = entry.RoomId
        form.CourseCode.data = entry.CourseCode
        form.CourseType.data = entry.CourseType
        form.UserInitial.data = entry.userInitial
    return render_template('edit.html',id=id,title=title,form=form)
Esempio n. 6
0
def save_entry(request):
	if not request.is_ajax() or not request.method == 'POST':
		raise Http404
	
	form= EntryForm(request.POST)
	
	if not form.is_valid():
		return HttpResponse('{}', mimetype='application/javascript')
	
	if 'pk' in request.POST:
		entry= get_object_or_404(Entry, pk= request.POST['pk'])
		form= EntryForm(request.POST, instance= entry)
		entry= form.save(commit= False)
		
		entry.body = strip_tags(entry.body)
		entry.title = strip_tags(entry.title)
		entry.save()
	else:
		entry= form.save(commit= False)
		entry.body = strip_tags(entry.body)
		entry.title = strip_tags(entry.title)
		entry.save()
	
	entry_content_type= ContentType.objects.get_for_model(entry.__class__)
	
	response_data= json.dumps({
		'pk': entry.pk,
		'model': '%s.%s' % (entry_content_type.app_label, entry_content_type.model),
	})
	
	return HttpResponse(response_data, mimetype='application/javascript')
Esempio n. 7
0
def edit(id):
    title = 'Edit Entry'
    user = User.query.get_or_404(g.user.id)
    entry = EntryClone.query.get_or_404(id)
    slotinfo = entry.EntryDay + '@' + entry.EntryTime
    print 'printing...'
    print slotinfo
    if not entry:
        abort(404)
    if user.userInitial != entry.userInitial and user.role != ROLE_ADMIN:
        flash('You are not allowed to edit this entry!', category='danger')
        return redirect(url_for('timetable', sem=entry.SemesterId))
    form = EntryForm()
    if form.validate_on_submit():
        entry.RoomId = form.RoomId.data
        entry.CourseCode = form.CourseCode.data
        entry.CourseType = form.CourseType.data
        entry.userInitial = form.UserInitial.data
        db.session.add(entry)
        db.session.commit()
        flash('Slot Edited for ' + slotinfo, category='success')
        myurl = app.config['SERVER_BASE'] + '/timetable/' + entry.SemesterId + '?tutorial=&btn=edit'
        return redirect(myurl)
    form.RoomId.data = entry.RoomId
    form.CourseCode.data = entry.CourseCode
    form.CourseType.data = entry.CourseType
    form.UserInitial.data = entry.userInitial
    return render_template('edit.html', id=id, title=title, form=form, slotinfo=slotinfo)
Esempio n. 8
0
def add(time, day, sem):
    title = 'Add Entry'
    user = User.query.get_or_404(g.user.id)
    entry = EntryClone.query.filter_by(EntryDay=day, EntryTime=time, SemesterId=sem)
    slotinfo = day + '@' + time
    if user.role != ROLE_ADMIN:
        flash('Sorry. You need special permissions to carry out this task!', category='danger')
        abort(404)
    form = EntryForm()
    if form.validate_on_submit():
        for e in entry:
            if e.userInitial == form.UserInitial.data and e.userInitial != 'TUTOR' and form.CourseCode.data != 'COMP1126' and form.CourseCode.data != 'COMP1127':
                flash('Sorry. You already have an entry in this slot!', category='danger')
                myurl = app.config['SERVER_BASE'] + '/timetable/' + sem + '?tutorial=&btn=edit'
                return redirect(myurl)
            if e.RoomId == form.RoomId.data and form.CourseCode.data.strip() != 'COMP1126' and form.CourseCode.data.strip() != 'COMP1127':
                flash('Sorry. This room is already occupied!', category='danger')
                myurl = app.config['SERVER_BASE'] + '/timetable/' + sem + '?tutorial=&btn=edit'
                return redirect(myurl)

        entry = EntryClone(EntryDay=day, EntryTime=time, RoomId=form.RoomId.data, SemesterId=sem, CourseCode=form.CourseCode.data, CourseType=form.CourseType.data, userInitial=form.UserInitial.data)
        db.session.add(entry)
        db.session.commit()
        flash('Slot Added for ' + slotinfo, category='success')
        myurl = app.config['SERVER_BASE'] + '/timetable/' + entry.SemesterId + '?tutorial=&btn=edit'
        return redirect(myurl)
    return render_template('add.html', title=title, form=form, time=time, day=day, sem=sem, slotinfo=slotinfo)
Esempio n. 9
0
def detail_page():
    form = EntryForm()
    if request.method == 'POST':
        if form.validate_on_submit():
            flash(f"{form.name.data}'s data was stored", 'success')
            student_name = request.form['name']
            student_roll_no = request.form['roll_no']
            student_phone = request.form['phone']
            new_student = StudentDetails(name=student_name,
                                         roll_no=student_roll_no,
                                         phone=student_phone)
            db.session.add(new_student)
            db.session.commit()
            all_details = StudentDetails.query.order_by(
                StudentDetails.roll_no).all()
            return redirect('/details')
        else:
            all_details = StudentDetails.query.order_by(
                StudentDetails.roll_no).all()
            return render_template('detail.html',
                                   details=all_details,
                                   form=form)
    else:
        all_details = StudentDetails.query.order_by(
            StudentDetails.roll_no).all()
        return render_template('detail.html', details=all_details, form=form)
Esempio n. 10
0
def create(request):
	if request.user.is_authenticated() is False:
		args = {}
		args['entry_list'] = Entry.objects.all()
		args['error'] = 'You must be signed in before creating a new post.'	
		return render_to_response('coltrane/entry_index.html', args)
	if request.POST:
		#post_values = request.POST.copy()
		#post_values['author'] = 4
		post_values = request.POST.copy()
		form = EntryForm(request.POST, request.FILES)
		if form.is_valid():
			#form.save()
			obj = form.save(commit=False)
			obj.author = request.user
			#get entry and category id:
			e1 = obj.id
			c1 = post_values['categories']
			c2 = Category.objects.get(id=c1)
			#save entry to category	
			obj.save()	
			#add the hashtags from the post into the database:
			getHashtags = obj.body + " " + obj.title
			s = {tag.strip("#") for tag in getHashtags.split() if tag.startswith("#")}
			for item in s:
				h = Hashtag.objects.filter(title=item)
				if not h:
					item = item.lower()
					newhash = Hashtag(title=item, num_used=1)
					newhash.save()
					obj.tags.add(newhash)
					#obj.save()
				else:
					#oldh = Hashtag.objects.get(title=item)	
					for item2 in h:
						item2.num_used += 1
						item2.save()
						obj.tags.add(item2)			
					#obj.save()	
			#this code increments each time a specific user creates a post
			inc_post = request.user.id
			count_post = User_Profile.objects.get(uid_id=inc_post)
			count_post.num_posts += 1
			count_post.save()
			
			obj.categories.add(c1)
			return HttpResponseRedirect('/weblog')
	else:
		form = EntryForm()
		form.author = request.user
	args = {}
	args.update(csrf(request))
	args['form'] = form 
	args['username'] = request.user.username
	args['uid'] = request.user.id
	return render_to_response('coltrane/newpost.html', args)
Esempio n. 11
0
def login():
    form = EntryForm()
    if form.validate_on_submit():
        return redirect(url_for('recording', form=form))
        # if form.text.data == '1234':
        #     flash('Thats the ticket!', 'success')
        #     return redirect(url_for('home'))
        # else:
        #     flash('Starting recording', 'danger')
    return render_template('login.html', title='Login', form=form)
Esempio n. 12
0
def new():
    form = EntryForm()
    if form.validate_on_submit():
        Entry.create(title=form.title.data,
                     date=form.date.data,
                     timespent=form.timespent.data,
                     body=form.body.data,
                     resources=form.resources.data)
        return redirect(url_for('index'))
    return render_template('new.html', form=form)
Esempio n. 13
0
def new():
    form = EntryForm()
    if form.validate_on_submit():
        models.Entry.create(
            title=form.title.data.strip(),
            date=form.date.data,
            time_spent=form.time_spent.data,
            what_you_learned=form.what_you_learned.data.strip(),
            resources_to_remember=form.resources_to_remember.data.strip())
        return redirect(url_for('index'))
    return render_template('new.html', form=form)
Esempio n. 14
0
def index():
	form = EntryForm()
	if(form.validate_on_submit()):
		#filename = secure_filename(form.filepath.data.filename)
		print(form.filename.data, form.index.data)
		session['filename'] = form.filename.data
		session['index'] = form.index.data
		session['title'] = form.title.data
		#form.filename.data.save('uploads/'+form.filename.data)
		return redirect(url_for('output'))
	return render_template('index.html', form=form)
Esempio n. 15
0
File: views.py Progetto: moba/summy
def add_entry(project):
    form = EntryForm(request.form)
    if not form.validate():
        return str(form.errors)
    name = form.name.data
    value = form.value.data
    project_id = form.project_id.data

    entry = Entry(name, value, project_id)
    db.session.add(entry)
    db.session.commit()
    return redirect(url_for('view_project',name=project))
Esempio n. 16
0
def edit(entry_id):
    entry = Entry.get(Entry.id == entry_id)
    form = EntryForm(obj=entry)
    if form.validate_on_submit():
        entry.title = form.title.data
        entry.date = form.date.data
        entry.timespent = form.timespent.data
        entry.body = form.body.data
        entry.resources = form.resources.data
        entry.save()
        return redirect(url_for('index'))
    return render_template('edit.html', form=form)
Esempio n. 17
0
def create():
    form = EntryForm()
    if request.method == 'POST':
        form = EntryForm(request.form)
        if form.validate():
            entry = form.save_entry(Entry(author = g.user))
            db.session.add(entry)
            db.session.commit()
            flash('Blog: %s ,Created! ' %entry.title, 'success')
            return redirect(url_for('entries.detail', slug = entry.slug))
        else:
            form = EntryForm()
    return render_template('entries/create.html',form = form)
Esempio n. 18
0
def edit(slug):
    entry = get_entry_or_404(slug, g.user)
    if request.method == 'POST':
        form = EntryForm(request.form, obj=entry)
        if form.validate():
            entry = form.save_entry(entry)
            db.session.add(entry)
            db.session.commit()
            flash('Blog: %s ,Edited! ' %entry.title, 'success')
            return redirect(url_for('entries.detail', slug = entry.slug))
    else:
        form = EntryForm(obj = entry)
        return render_template('entries/edit.html', entry = entry, form = form)
Esempio n. 19
0
def add_entry():
    form = EntryForm()
    if form.validate_on_submit():
        post = EntryModel(
            title=form.title.data,
            text=markdown(form.text.data),
            slug=make_slug(form.title.data)
        )
        try:
            post.put()
        except CapabilityDisabledError:
            flash(u'Read-only mode.')
    return redirect(url_for('projects'))
Esempio n. 20
0
def post_entry(request, next=None):
    """
    Post a entry.

    HTTP POST is required. If ``POST['submit'] == "preview"`` or if there are
    errors a preview template, ``guestbook/preview.html``, will be rendered.
    """

    # Require POST
    if request.method != 'POST':
        return http.HttpResponseNotAllowed(["POST"])

    # Fill out some initial data fields from an authenticated user, if present
    data = request.POST.copy()

    if request.user.is_authenticated():
        if not data.get('name', ''):
            data["name"] = request.user.get_full_name()
        #if not data.get('email', ''):
        #    data["email"] = request.user.email

    # Do we want to preview the entry?
    preview = data.get("submit", "").lower() == "preview" or \
              data.get("preview", None) is not None

    # Construct the entry form
    form = EntryForm(data=data)

    # Check security information
    if form.security_errors():
        return HttpResponseBadRequest(
            "The entry form failed security verification: %s" % \
                escape(str(form.security_errors())))

    # If there are errors or if we requested a preview show the entry
    if form.errors or preview:
        return render_to_response("guestbook/preview.html", {
            'form' : form, 'entry': data
            }, RequestContext(request)
        )

    # Otherwise create the entry
    entry = form.get_entry_object()
    entry.ip = request.META.get("REMOTE_ADDR", None)
    if request.user.is_authenticated():
        entry.user = request.user

    # Save the entry and signal that it was saved
    entry.save()

    return {'form': form}
Esempio n. 21
0
File: views.py Progetto: jpknie/flog
def add_entry():
	form = EntryForm(request.form)
	page_title = 'Add new blog entry'
	if request.method == 'POST' and form.validate_on_submit():
		entry = Entry()
		entry.user_id = g.user.user_id
		entry.create_time = datetime.datetime.utcnow()
		form.populate_obj(entry)
		db.session.add(entry)
		db.session.commit()
		return redirect(url_for('entries'))
	tags = Tag.query.all()
	tags = list(chunks(tags, COLS_IN_TAG_TABLE))
	return render_template('entry_editor.html', form_action = 'add_entry', form = form, tags = tags, page_title = page_title)
Esempio n. 22
0
def add(time, day, sem):
    title = "Add Entry"
    user = User.query.get_or_404(g.user.id)
    entry = EntryClone.query.filter_by(EntryDay=day,
                                       EntryTime=time,
                                       SemesterId=sem)

    if user.role != ROLE_ADMIN:
        flash('Sorry. You need special permissions to carry out this task!',
              category='danger')
        abort(404)

    form = EntryForm()

    if form.validate_on_submit():
        for e in entry:
            if (e.userInitial == form.UserInitial.data):
                flash('Sorry. You already have an entry in this slot!',
                      category='danger')
                myurl = app.config[
                    "SERVER_BASE"] + "/timetable/" + sem + "?tutorial=&btn=edit"
                return redirect(myurl)

            if (e.RoomId == form.RoomId.data):
                flash('Sorry. This room is already occupied!',
                      category='danger')
                myurl = app.config[
                    "SERVER_BASE"] + "/timetable/" + sem + "?tutorial=&btn=edit"
                return redirect(myurl)

        entry = EntryClone(EntryDay=day,
                           EntryTime=time,
                           RoomId=form.RoomId.data,
                           SemesterId=sem,
                           CourseCode=form.CourseCode.data,
                           CourseType=form.CourseType.data,
                           userInitial=form.UserInitial.data)
        db.session.add(entry)
        db.session.commit()
        flash('Slot Added', category='success')
        myurl = app.config[
            "SERVER_BASE"] + "/timetable/" + entry.SemesterId + "?tutorial=&btn=edit"
        return redirect(myurl)
    return render_template('add.html',
                           title=title,
                           form=form,
                           time=time,
                           day=day,
                           sem=sem)
Esempio n. 23
0
def edit_entry(post_id):
    post = EntryModel.get_by_id(post_id)

    if not post:
        return render_template('404.html'), 404
    form = EntryForm()
    if form.validate_on_submit():
        post.title = form.title.data
        post.text = markdown(form.text.data)
        post.slug = make_slug(post.title)
        try:
            post.put()
        except CapabilityDisabledError:
            flash(u'Read-only mode.')
    return redirect(url_for('projects'))
Esempio n. 24
0
File: views.py Progetto: jpknie/flog
def edit_entry(entryid):
	entry = Entry.query.get(int(entryid))
	if entry.user_id != g.user.user_id:
		flash("Cannot edit this entry.", 'error-message')
		return redirect(url_for('entries'))
	form = EntryForm(request.form, obj=entry)
	page_title = 'Edit blog entry'
	if request.method == 'POST' and form.validate_on_submit():
		# save new data in entry here
		form.populate_obj(entry)
		entry.create_time = datetime.datetime.utcnow()
		db.session.add(entry)
		db.session.commit()
		return redirect(url_for('entries'))
	return render_template('entry_editor.html', form_action = 'edit_entry', form = form, tags = None, page_title = page_title)
Esempio n. 25
0
def update_image(entry_id):
    timestamp = datetime.now()
    form = EntryForm()
    image = request.files[form.image.name]
    # The new image is uploaded to cloudinary and its url and id are retrieved
    uploaded_image = cloudinary.uploader.upload(
                                                image, width=800,
                                                quality='auto'
                                                )
    image_url = uploaded_image.get('secure_url')
    new_image_id = uploaded_image.get('public_id')
    the_entry = entries.find_one({"_id": ObjectId(entry_id)})
    # The previous image in is deleted from cloudinary to not crowd it with
    # unused images
    cloudinary.uploader.destroy(the_entry["image_id"])
    # Image fields are updated in the database
    if the_entry["user_id"] == playground_id or the_entry["user_id"] == current_user.id:
        update_field(
            {"image": image_url,
             "image_id": new_image_id,
             "updated_on": timestamp},
            entry_id)

        return update_success_msg("Image", timestamp, image_url)
    else:
        return render_template('pages/403.html',  title="Forbidden")
Esempio n. 26
0
def update_tags(entry_id):
    timestamp = datetime.now()
    form = EntryForm()
    the_entry = entries.find_one({"_id": ObjectId(entry_id)})
    if the_entry["user_id"] == playground_id or the_entry["user_id"] == current_user.id:
        # If the tag list sent to python is empty, remove field from db
        if len(form.tags.data) == 0:
            entries.update_one(
                                {"_id": ObjectId(entry_id)},
                                {"$unset":
                                    {
                                        "tags": "",
                                        "updated_on": timestamp
                                    }
                                 }
                             )
            return update_success_msg("Tags", timestamp)

        else:
            # If there is a list of tags, turn tags to a lowercase list and
            # remove any duplicates
            lowercase_tags = form.tags.data.lower().split(',')

            final_tags = []
            for tag in lowercase_tags:
                if tag not in final_tags:
                    final_tags.append(tag)
            update_field(
                {"tags": final_tags,
                 "updated_on": timestamp},
                entry_id)
            return update_success_msg("Tags", timestamp)
    else:
        return render_template('pages/403.html',  title="Forbidden")
Esempio n. 27
0
def add_entry():
    form = EntryForm(request.form)
    page_title = 'Add new blog entry'
    if request.method == 'POST' and form.validate_on_submit():
        entry = Entry()
        entry.user_id = g.user.user_id
        entry.create_time = datetime.datetime.utcnow()
        form.populate_obj(entry)
        db.session.add(entry)
        db.session.commit()
        return redirect(url_for('entries'))
    tags = Tag.query.all()
    tags = list(chunks(tags, COLS_IN_TAG_TABLE))
    return render_template('entry_editor.html',
                           form_action='add_entry',
                           form=form,
                           tags=tags,
                           page_title=page_title)
Esempio n. 28
0
def edit_entry(entryid):
    entry = Entry.query.get(int(entryid))
    if entry.user_id != g.user.user_id:
        flash("Cannot edit this entry.", 'error-message')
        return redirect(url_for('entries'))
    form = EntryForm(request.form, obj=entry)
    page_title = 'Edit blog entry'
    if request.method == 'POST' and form.validate_on_submit():
        # save new data in entry here
        form.populate_obj(entry)
        entry.create_time = datetime.datetime.utcnow()
        db.session.add(entry)
        db.session.commit()
        return redirect(url_for('entries'))
    return render_template('entry_editor.html',
                           form_action='edit_entry',
                           form=form,
                           tags=None,
                           page_title=page_title)
Esempio n. 29
0
def create():
	if request.method == 'POST':
		form = EntryForm(request.form)
		if form.validate():
			# saved in the database as the author of that entry
			entry = form.save_entry(Entry(author=g.user))
			# entry = form.save_entry(Entry())
			try:
				db.session.add(entry)
				db.session.commit()
			except IntegrityError as err:
				db.session.rollback()
				flash('Entry "%s" did not create successfully.' % entry.title, 'warning')
			else:
				flash('Entry "%s" created successfully.' % entry.title, 'success')
				return redirect(url_for('entries.detail', slug=entry.slug))
	else:
		form = EntryForm()
	return render_template('entries/create.html', form=form)
Esempio n. 30
0
def new_entry(request):

    if not request.user.is_authenticated():
        return HttpResponseRedirect('/accounts/login/')

    if request.POST:
        form = EntryForm(request.POST)
        if form.is_valid():
            form.save()

            return HttpResponseRedirect('/newentry/')
    else:
        form = EntryForm()

    args = {}
    args.update(csrf(request))

    args['form'] = form

    return render_to_response('newentry.html', args)
def homepage():
    form = EntryForm()
    similar = None
    exact = None

    if form.validate_on_submit():
        similarity = check_uid_test(form)

        print "Similarity", similarity
        if len(similarity["exact"]) > 0:
            exact = similarity["exact"]
        else:
            exact = None

        if len(similarity["similar"]) > 0:
            similar = similarity["similar"]
        else:
            similar = None

    return render_template("test.html", form=form, similar=similar, exact=exact)
Esempio n. 32
0
def create():
    form = EntryForm()
    if request.method == 'POST':
        form = EntryForm(request.form)
        if form.validate():
            entry = form.save_entry(Entry(author=g.user))
            db.session.add(entry)
            db.session.commit()
            flash('Blog: %s ,Created! ' % entry.title, 'success')
            return redirect(url_for('entries.detail', slug=entry.slug))
        else:
            form = EntryForm()
    return render_template('entries/create.html', form=form)
Esempio n. 33
0
def edit(slug):
	# entry = Entry.query.filter(Entry.slug == slug).first_or_404()
	# entry = get_entry_or_404(slug)
	entry = get_entry_or_404(slug, author=None)
	if request.method == 'POST':
		# When WTForms receives an obj parameter, it will attempt to pre-populate the form  fields with values taken from obj
		form = EntryForm(request.form, obj=entry)
		if form.validate():
			entry = form.save_entry(entry)
			try:
				db.session.add(entry)
				db.session.commit()
			except IntegrityError as err:
				db.session.rollback()
				flash('Entry "%s" did not update successfully.' % entry.title, 'warning')
			else:
				flash('Entry "%s" has been saved.' % entry.title, 'success')
				return redirect(url_for('entries.detail', slug=entry.slug))
	else:
		form = EntryForm(obj=entry)
	return render_template('entries/edit.html', entry=entry, form=form)
Esempio n. 34
0
def update_rating(entry_id):
    timestamp = datetime.now()
    form = EntryForm()
    the_entry = entries.find_one({"_id": ObjectId(entry_id)})
    if the_entry["user_id"] == playground_id or the_entry["user_id"] == current_user.id:
        update_field(
            {"rating": int(form.rating.data),
             "updated_on": timestamp},
            entry_id)
        return update_success_msg("Rating", timestamp)
    else:
        return render_template('pages/403.html',  title="Forbidden")
Esempio n. 35
0
def update_fav(entry_id):
    the_entry = entries.find_one({"_id": ObjectId(entry_id)})
    form = EntryForm()
    timestamp = datetime.now()
    if the_entry["user_id"] == current_user.id:
        update_field({
            "is_fav": form.is_fav.data,
            "updated_on": timestamp
        }, entry_id)
        return update_success_msg("is_fav", timestamp)
    else:
        return render_template('pages/403.html', title="Forbidden")
Esempio n. 36
0
def create():
    form = EntryForm()
    if form.validate_on_submit():
        try:
            entry = Entry.create(
                title=form.title.data,
                date=form.date.data,
                time=form.time.data,
                learned=form.learned.data,
                resources=form.resources.data,
                slug=safe_slugify(form.title.data),
                user=g.user.id
            )
            process_tags(form.tags.data, entry)
        except IntegrityError:
            flash("An entry with that title already exists.")
        else:
            return redirect(url_for('index'))
    else:
        flash_errors(form)
    return render_template('new.html', form=form)
Esempio n. 37
0
def add_entry():
    """
    adding a post on the home page

    """
    idlist = r.lrange('idlist',0,-1)
    if 'user_id' not in session:
       return abort(401)
    form = EntryForm(csrf_enabled = False)
    if form.validate():
        user_com = g.user['username']
        idlist = r.incr('entries:LatestEntryId')
        r.lpush('idlist', idlist)
        filename = '{0}.png'.format(idlist)
        form.image.data.save(os.path.join(UPLOAD_FOLDER, filename))
        r.hmset('entries:%s' %idlist, {'title':form.title.data, 
                                       'text':form.text.data, 
                                       'user_com':user_com, 
                                       'time':time.time()})
        return redirect(url_for('show_entries'))
    return render_template('add_entries.html', 
                           form=form)
Esempio n. 38
0
def add(time,day,sem):
    title="Add Entry"
    user  = User.query.get_or_404(g.user.id)
    entry = EntryClone.query.filter_by(EntryDay=day,EntryTime=time,SemesterId=sem)

    if user.role != ROLE_ADMIN:
            flash('Sorry. You need special permissions to carry out this task!', category='danger')
            abort(404)


    form=EntryForm()

    if form.validate_on_submit():
        for e in entry:
            if (e.userInitial == form.UserInitial.data):
                flash('Sorry. You already have an entry in this slot!', category='danger')
                myurl=app.config["SERVER_BASE"]+"/timetable/"+sem+"?tutorial=&btn=edit"
                return redirect(myurl)

            if (e.RoomId == form.RoomId.data):
                flash('Sorry. This room is already occupied!', category='danger')
                myurl=app.config["SERVER_BASE"]+"/timetable/"+sem+"?tutorial=&btn=edit"
                return redirect(myurl)

        entry = EntryClone(
                EntryDay=day,
                EntryTime=time,
                RoomId=form.RoomId.data,
                SemesterId=sem,
                CourseCode=form.CourseCode.data,
                CourseType=form.CourseType.data,
                userInitial=form.UserInitial.data
                )
        db.session.add(entry)
        db.session.commit()
        flash('Slot Added', category='success')
        myurl=app.config["SERVER_BASE"]+"/timetable/"+entry.SemesterId+"?tutorial=&btn=edit"
        return redirect(myurl)
    return render_template('add.html',title=title,form=form,time=time,day=day,sem=sem)
Esempio n. 39
0
def new_post(request, usernameslug):
    if not check_user_authentication(request, usernameslug):
        return redirect('index')
    if request.method == 'GET':
        form = EntryForm()
        return render(request, 'new_post.html', {
            'usernameslug': usernameslug,
            'user': request.user,
            'form': form
        })
    elif request.method == 'POST':
        form = EntryForm(request.POST)
        title = request.POST['title']
        body = request.POST['body']
        profile = User.objects.get(
            username=request.user.username).profile_set.first()
        #TODO check validity
        entry = Entry(title=title, body=body, profile=profile)
        entry.save()
        return redirect('user_profile', usernameslug=usernameslug)
        #return render(request, 'profile.html', {'usernameslug':usernameslug,'user':request.user,'form':form,'entries':get_entries(usernameslug)})
    return redirect('index')
Esempio n. 40
0
def edit(id):

    detail = StudentDetails.query.get_or_404(id)
    form = EntryForm()
    if request.method == 'POST':
        flash(f"{form.name.data}'s data was edited", 'warning')
        detail.name = request.form['name']
        detail.roll_no = request.form['roll_no']
        detail.phone = request.form['phone']
        db.session.commit()
        return redirect('/details')
    else:
        return render_template('edit.html', detail=detail, form=form)
def subscribe(request):
    form = EntryForm()
    if request.method == 'POST':
        form = EntryForm(request.POST)
        if form.is_valid():
            form.save()
            success = True
            form = EntryForm()
            return render_to_response('subscribe.html', {
                'success': success,
                'form': form
            },
                                      context_instance=RequestContext(request))

    return render_to_response(
        'subscribe.html',
        {'form': form},
        context_instance=RequestContext(request),
    )
Esempio n. 42
0
def playground_entry(entry_id):
    form = EntryForm()
    the_entry = entries.find_one({"_id": ObjectId(entry_id)})
    form.name.data = the_entry["name"]
    form.description.data = the_entry["description"]
    form.rating.data = str(the_entry["rating"])
    form.hidden_id.data = entry_id
    if the_entry.get("tags") is not None:
        form.hidden_tags.data = ','.join(the_entry["tags"])
    return render_template('pages/entry.html',
                           title="Entry",
                           entry=the_entry,
                           form=form,
                           playground=True)
Esempio n. 43
0
def create_entry(request):
    """
    Create entry:
      Model form which automatically fills in the author and uses slugify to
      create a slug for the entry based on the tittle.
    """
    if request.method == 'POST':
        try:
            user = User.objects.get(username=request.user)
            new_entry = Entry(author=user)
            form = EntryForm(request.POST, instance=new_entry)
        except User.DoesNotExist:
            return HttpResponse("Invalid username")
        if form.is_valid():
            new_entry = form.save(commit=False)
            new_entry.slug = slugify(new_entry.title)
            new_entry.save()
            return HttpResponseRedirect("/")
    else:
        form = EntryForm()

    return render_to_response("mingus/create_entry.html",
                              {"form": form, },
                              context_instance=RequestContext(request))
Esempio n. 44
0
def entry(entry_id):
    form = EntryForm()
    the_entry = entries.find_one({"_id": ObjectId(entry_id)})
    if the_entry["user_id"] == current_user.id:
        form.name.data = the_entry["name"]
        form.description.data = the_entry["description"]
        form.rating.data = str(the_entry["rating"])
        form.hidden_id.data = entry_id
        if the_entry.get("tags") is not None:
            form.hidden_tags.data = ','.join(the_entry["tags"])
        return render_template('pages/entry.html',
                               title="Entry",
                               entry=the_entry,
                               form=form)
    else:
        return render_template('pages/403.html', title="Forbidden")
Esempio n. 45
0
def edit_entry(request, entry_id):
    """Редактирует существующую запись."""
    entry = Entry.objects.get(id=entry_id)
    topic = entry.topic
    if request.method != 'POST':
        # Исходный запрос; форма заполняется данными текущей записи.
        form = EntryForm(instance=entry)
    else:
        # Отправка данных POST; обработать данные.
        form = EntryForm(instance=entry, data=request.POST)
        if form.is_valid():
            form.save()
            return HttpResponseRedirect(
                reverse('learning_logs:topic', args=[topic.id]))
    context = {'entry': entry, 'topic': topic, 'form': form}
    return render(request, 'learning_logs/edit_entry.html', context)
def subscribe(request):
    form = EntryForm()
    if request.method == "POST":
        form = EntryForm(request.POST)
        if form.is_valid():
            form.save()
            success = True
            form = EntryForm()
            return render_to_response(
                "subscribe.html", {"success": success, "form": form}, context_instance=RequestContext(request)
            )

    return render_to_response("subscribe.html", {"form": form}, context_instance=RequestContext(request))
Esempio n. 47
0
def edit(slug):
    entry = get_entry_or_404(slug, author=None)
    if request.method == 'POST':
        form = EntryForm(request.form, obj=entry)
        if form.validate():
            entry = form.save_entry(entry)
            db.session.add(entry)
            db.session.commit()
            flash('Entry "%s" has been saved.' % entry.title, 'success')
            return redirect(url_for('entries.detail', slug=entry.slug))
    else:
        form = EntryForm(obj=entry)
    return render_template('entries/edit.html', entry=entry, form=form)
Esempio n. 48
0
def update_name(entry_id):
    form = EntryForm()
    new_name = form.name.data
    the_entry = entries.find_one({"_id": ObjectId(entry_id)})
    timestamp = datetime.now()
    if the_entry["user_id"] == current_user.id:
        if (len(new_name) > 0 and len(new_name) <= 30
                and text_regex.match(new_name)):
            update_field({
                "name": form.name.data,
                "updated_on": timestamp
            }, entry_id)
            return update_success_msg("Name", timestamp)
        else:
            return update_failure_msg("Name must be betwen 1 and 30 "
                                      "characters, and cannot start with"
                                      " a space.")
    else:
        return render_template('pages/403.html', title="Forbidden")
Esempio n. 49
0
def update_description(entry_id):
    timestamp = datetime.now()
    form = EntryForm()
    new_description = form.description.data
    the_entry = entries.find_one({"_id": ObjectId(entry_id)})
    if the_entry["user_id"] == playground_id or the_entry["user_id"] == current_user.id:
        if (len(new_description) > 0 and
                len(new_description) <= 2000 and
                text_regex.match(new_description)):
            update_field(
                {"description": form.description.data,
                 "updated_on": timestamp},
                entry_id)
            return update_success_msg("Description", timestamp)
        else:
            return update_failure_msg("Description must be betwen 1 and 2000 "
                                      "characters, and cannot start with a "
                                      "space or line break.")
    else:
        return render_template('pages/403.html',  title="Forbidden")
Esempio n. 50
0
def form(request, date=None):
    if request.user.is_authenticated():
        # get the date
        if date == None:
            date = datetime_date.today()
        else:
            date = parse_date(date)

        # get the entry
        try:
            entry = Entry.objects.filter(user=request.user).get(date=date)
        except Entry.DoesNotExist:
            entry = Entry(user=request.user,date=date)
            entry.save()

        if request.method == 'POST':
            # construct the form
            form = EntryForm(request.POST,groups=Group.objects.filter(user=request.user))

            if form.is_valid():
                values = form.cleaned_data

                for key in values:
                    field_id = key.split('_')[1]
                    value = values[key]

                    field = Field.objects.get(id=field_id)

                    record = Record.objects.filter(entry=entry).get(field=field)
                    record.value = value
                    record.save()
            else:
                print form.errors

            return HttpResponseRedirect(request.META.get('HTTP_REFERER'))
        else:

            fieldsets = []
            for group in Group.objects.filter(user=request.user):
                fieldset = {
                    'name': group.name,
                    'elements': []
                }

                for field in group.fields.all():
                    try:
                        record = field.records.get(entry=entry)
                    except Record.DoesNotExist:
                        record = Record(entry=entry,field=field)
                        record.save()

                    fieldset['elements'].append({
                        'field': field,
                        'record': record
                    })

                fieldsets.append(fieldset)

            return render(request,'form.html', {
                'fieldsets': fieldsets,
                'yesterday': date - datetime_timedelta(1),
                'today': date,
                'tomorrow': date + datetime_timedelta(1),
                'auth': True,
                'user': request.user
            })
    else:
        return HttpResponseRedirect('/login/')