Django Form - include a "reset" button - django

I've managed to include a form in my django project using FilterSet. It works very well - no issues.
When I have typed something in the form to make a search ('for instance BMW'), the table in my template is filtered on ('BMW'), though my search 'BMW' stays in the field. Hence, I would like to include a button 'clear' on which the user can click and 'BMW' disappears from the field & the search result goes back to the initial table. How can I realise this?
Currently I have included a button in my template (but nothing happens when I click on it)
<button type="reset" class="btn btn-primary" onclick="resetEffort()"">
<span class="glyphicon glyphicon-search"></span> Clear
</button>
And this is my view.py:
def cars_overview(request):
car = CarFilter(request.GET, queryset=Car.objects.all())
return render(request, 'cars/cars.html', {'filter': car})
many thanks !

You can intercept the event, pause it, clear the values, and then submit the form using js.
document.querySelector('button[type="reset"]').addEventListener('click', function (e) {
e.preventDefault();
this.parentElement.reset();
this.parentElement.submit();
})

Related

Is it possible to load bootstrap modal directly with flask

In flask we can render a page using render_template('home.html, data=data).
In the same way is possible to load bootstrap modal without having to use javascrpt?
For e.g if an element is clicked in the page,
<span class="example" data-toggle="modal" data-target="#showExample" Testing</span>
A call is made to function in flask function and it trigger the modal pop-up and pass data that can used to populate field
If i'm understand what you mean, you can do this in JavaScript (just paste it in bottom of your page, in the tag "script":
document.getElementById('showExample').addEventListener('click', function() {
// Do some stuff, that you need to do...
});
Or, if you want, you can do this without JavaScript (i guess that you using Jinja2):
Insert it into your page template:
{% if show_example_modal %}
<span class="example" data-toggle="modal" data-target="#showExample" Testing</span>
{% endif %}
Python view code:
#app.add_route('/something/')
def something():
return render_template("something.html", show_example_modal=True)

Inputs on Ember refresh page when a user hits Enter key

I'm using Ember CLI and have noticed odd behaviour. When the user clicks into the input and presses the enter key, the page refreshes.
My page has a basic element like this that is NOT part of any form:
<input type="text" class="form-control" id="per_page" value="50">
I am currently serving the page via:
ember cli
So node is hosting and has the fancy live reload thing going on so that when I update a page that is part of the underlying app.
So what is causing a page reload the enter key pressed inside an input? Could it be node or live reload? Are inputs just supposed to refresh a page when a user presses the enter key and I missed that in my HTML for dummies book?
**Better still, how can I intercept and instead call a function via:
{{action** "myFunction"}}
That happens because when you hit Enter, form gets submitted which results in page reload. what you need to do is set onsubmit="return false" on the form so nothing happens during submit. you can bind input to execute some action by adding action attribute action="doSomething"
<form onsubmit="return false">
{{input type="text" action="createComment" value=topic id="inputTopic"}}
</form>
Edit: In Ember 3+ you now use the {{on}} modifier to setup events on elements.
<form {{on 'submit' this.submitForm}}>
<!-- the rest of your form here -->
<button type='submit'>Submit</button>
</form>
And the action defined like so
#action
submitForm(event) {
event.preventDefault();
// Your code
}
Historically Ember has handled this use case with the following code:
<form {{action 'submitForm' on='submit'}}>
<!-- the rest of your form here -->
<button type='submit'>Submit</button>
</form>
This prevents the form from refreshing the page.
There is another method that gives you more control, by giving you the event so you can manage that yourself:
<form onsubmit={{action 'submitForm'}}>
<!-- the rest of your form here -->
<button type='submit'>Submit</button>
</form>
In this case, you will get an event and will have to call event.preventDefault() to stop the page refresh.
actions: {
submitForm(event) {
event.preventDefault();
}
}
This is a running example of the two: https://ember-twiddle.com/827820958e054f7af57b7677630729fc?openFiles=controllers.application.js%2C
I had the same problem - what worked for me, was to overwrite the keyPress Event in the input component like this:
keyPress: function (e) {
var keyCodeEnter = 13;
if (e.keyCode === keyCodeEnter) {
return false;
}
}
Hope it will help someone in the future! :)

Adding needs: ['ApplicationController'] makes my view dissapear

My Ember.js app is set up roughly like this:
Router:
App.Router.map ->
#resource('site', { path: '/' }, ->
#resource('dashboard')
#resource('account')
#resource('pages', { path: '/:page_slug'}))
Routes:
App.ApplicationRoute = Ember.Route.extend
model: ->
return App.Site.find(1)
App.PagesRoute = Ember.Route.extend
model: (params)->
return App.Page.find(params.page_slug)
EDIT:
Controller (JS not Coffee):
App.PagesController = Ember.ObjectController.extend({
needs: 'ApplicationController',
...
});
I have an ApplicationController and a PagesController. When I'm on a page, I want to call an action to delete the current page. If I place it in the PagesController it works kind of ok, but a navigation menu with a list of pages in the ApplicationView doesn't get updated until I refresh the page. So... I assume I need to place the action in the ApplicationController and add needs: ['ApplicationController'] to my PagesController.
However, when I do that, everything in my Pages template disappears.
I have an {{outlet}} in my Application template and another on in the Site template which ultimately displays the Pages template. Yeah, complicated, I know and there's probably a better way to do it, so any suggestions would be greatly appreciated. Oh and BTW, I'm a real Ember.js newb, so examples need to be spelled out explicitly. (Drawing them with pretty colors in crayon would actually be ideal.)
Thanks in advance for any help.
Here's the refresh issue. In the root resource site I'm loading in one Site model which the Rails backend returns using the url being sent in. Eventually, this app will be used with multiple domains, and each domain will be served it's own website (roughly based on the WP-Multisite concept). Then in the pages route, I'm loading one page of the site based on its slug attribute. That's all working fine. So, now I want to allow the user to be able to add and remove pages as they want.
So, the issue is this. When I delete a page at the PagesController level, the page deletes just fine, but the ApplicationController doesn't get notified. Namely, my nav menu:
<ul class="left">
{{#each page in page}}
<li>{{#link-to 'pages' page.slug}}{{page.menu_name}}{{/link-to}}</li>
{{/each}}
<li id="add-page-button"><a data-tooltip title="Click here to add a new page to your site." href="#" data-reveal-id="addPageModal" data-reveal>+</a></li>
</ul>
doesn't get notified that a page is missing and so it doesn't update the nav menu by removing that page from the list. Adding works fine, the nav list is updated when a new page is added, but I'm doing that at the ApplicationController level like so:
addNewPage: ->
# Get the site
site = #get('model')
# Get all the pages associated with the site
pages = site.get('page')
title = this.get('newTitle')
if (!title.trim())
return
slug = this.get('newSlug')
if (!slug.trim())
return
menu_name = this.get('newMenuName')
if (!menu_name.trim())
return
# Create a new page passing in our title, slug and menu_name
pages.create({title: title, slug: slug, menu_name: menu_name})
# Save the pages
pages.save()
if (pages.isError)
console.log(pages.errors)
else
#set('newTitle', '')
#set('newSlug', '')
#set('newMenuName', '')
$('#addPageModal').foundation('reveal', 'close')
And this is my deletePage code on the PagesController (sorry, I've got a mix of JS and CoffeeScript):
deletePage: function (slug) {
var page = this.get('model');
this.get('ApplicationController').deletePage(page);
this.toggleProperty('isEditingTitle');
this.toggleProperty('isShowingDeleteConfirmation');
this.transitionToRoute('site.index');
}
When I try this, Ember rather helpfully lets me know I need to add needs but again, when I do that, my Pages template is blank.
Oh yes, I have even tried setting the target attribute on the button calling the deletePage action.
I realize what I need to do is somehow access the Site model in my PagesController, but how should I go about that.
This post has taken on epic proportions. Sorry about that. Thanks again for any help.
needs doesn't do anything on the route, if you want to access a controller from a route you can just use this.controllerFor('application')
Additionally when using needs in a controller definition it should be like this needs: 'application' or needs: ['foo', 'application']...
Okay, all, I figured it out. For posterity's sake (and others who go looking for this). Here's how to delete an object in a model that has a belongsTo association.
ApplicationController:
deletePage: function () {
# First we find the Site which all pages belongTo
# Just ignore the hard-coded '1' it's something I have to do to get it to work
site = App.Site.find(1);
# Then we get the current model, i.e., the 'page' we're on and about to delete
page = this.get('model');
# Then, we get all 'pages'
pages = site.get('page');
# We remove the object from the page which updates the navigation menu
pages.removeObject(page);
# We delete the record and save the 'pages' model
page.deleteRecord();
pages.save();
}
Pages template:
{{#if isShowingDeleteConfirmation}}
<div class="large-7 large-offset-5">
<label class="inline left">Are you sure? (Can't be undone)</label>
<button {{action 'deletePage'}} class='button tiny alert'>Yes</button>
<button {{action 'cancelDeletePage'}} class='button tiny'>Cancel</button>
</div>
{{else}}
<div class="large-2 right">
<button {{action 'showDeleteConfirmation'}} class='button tiny alert'>Delete Page</button>
</div>
{{/if}}
I can show you the attributes and logic behind the if...else statement if you need me to.
Basically, the user clicks on the 'Delete' button, showing the other buttons 'yes' and 'cancel'. Once 'yes' is clicked, the deletePage action gets called.
I found very little documentation on the deleteRecord method and basically had to piece this all together myself. Perhaps there's a better way and this can be refactored. Just let me know in the comments.

emberjs-RC2 render helper scope and action bubbling not allowing form to save

The jsfiddle.
From the posts#index template, I can create a new comment by using the #linkTo helper which goes to the PostNewComment Route and renders the post/newcomment form. If I click save the newly created comment is persisted using the 'save event' inside the PostNewComment Route.
You can uncomment the line below in post/comments" template, to see it working
{{#linkTo "post.newComment"}} Add comment{{/linkTo}}
I changed my UI to use a controller isAddingNew button and the render helper to determine When to display the form and now if I click the save button, I get:
Uncaught TypeError: Cannot call method 'one' of null
This how I render it:
<p> {{render "post.newComment" }} </p>
I suspect it is a scope issue because the error is only triggered when 'save' is clicked after using the render helper.
To reach the 'add new comment' button:
click -> post -> a post title -> click comments link -> add comment
Is there a way to make the 'Post/newComment form' displayed via the 'render helper' in the post/comments template to use the 'save event' defined in the PostNewComment Route.
Right now clicking on the 'save button' which is defined in that form goes directly to the parent route ie PostCommentsRoute instead of going to its own route probably because I displaying the form via the render helper.
I thought calling 'save' should go to its own controller and then bubble to its own route where it is actually defined, before attempting to bubble up the hierarchy to the PostComments Route.
There's probably a few alternatives, but this works and is pretty idiomatic: http://jsfiddle.net/GabSY/4/
In particular:
{{#if model}}
<form {{action save content on='submit'}}>
{{view Ember.TextArea valueBinding="content.body" placeholder="body"}}
<button type="submit"> save comment </button>
<button {{action cancel}}> Cancel</button>
</form>
{{else}}
<button {{action open}}> Add comment </button>
{{/if}}
The reason you were getting the Uncaught TypeError: Cannot call method 'one' of null error was that the PostNewCommentController's model was never set. What I ended up doing was using the open action on the PostNewCommentController to set the model of the controller, which can be used in a Handlebars {{if}} to determine whether the form should be displayed or not.
I prefer this approach to the alternative of setting content/model (they are aliases to each other) of the PostNewCommentController from within the PostCommentsRoute's setupController method because if you go down that route, it's easy to start mixing concerns between not-very-related controllers and routes. In my approach, all the logic for setting the content/model of the new comment takes place in the controller for new comments, which makes sense since a new comment no longer has its own route to initialize this data.

Prevent TextField with an action to submit its form

I have a {{view Ember.TextField action="foo"}} nested in a <form> tag:
My form:
<form>
{{view Ember.TextField action="foo"}}
</form>
I hoped pressing enter in this textfield will call the action foo, without triggering a submit event on its form (because, by default, Ember.TextField#bubbles is set to false). But it is not the case: the page is reloaded.
For semantic and integration purpose, I would like to keep the <form> tag, and do not write an Ember.Form view.
You can test it in this JSFiddle.
How could I achieve this ?
PS: I'm using ember-latest:
version: v1.0.0-pre.4-31-g16442c5
last commit: 16442c5 (2013-01-23 23:48:09 -0800)
<form {{ action "" on="submit" }}> will prevent the form submission. (This is basically equivalent to the onsubmit="return false;" suggestion in another answer.)
I think the simpliest way is to add onsubmit="return false;" on the form element. Or with jQuery , preventDefault();
I'm sure this is not the best way but it work!