Here goes another star rating question. I want to use bootstrap-rating-input to input rating value (1 to 5) and have django-ratings save the rating to the database. Although I'm a little green with javascript, I really want users to be able to vote using star rating instead of a number input form. Could you show me how to hook up these two apps to make them play nice with each other?
What does the view and templates look like?
And how do I configure the javascript to make the whole thing work?
Thanks!
OK, boostrap-rating-input is not specifically for django, meaning you will have to do some work to get it going.
I suggest you create a widget for it based on the django-bootstrap-datetime-picker which has implemented a similar bootstrap input field to work nicely with django.
Once that is done, you will be able to add a ratinginput widget to your form which will automatically return a number when the form is submitted, as for django ratings, as long as you have a rating = RatingField(range=5) field in your models you can override it with a rating = ratingWidget() and everything else should take care of itself.
I might try implement the widget later today.
Add this in your head part for test:
<script src="https://raw.githubusercontent.com/javiertoledo/bootstrap-rating-input/master/src/bootstrap-rating-input.js"></script>
now add this code where you want to give a rating
<input class="my_class rating" data-clearable=""
data-max="5" data-min="1" id="some_id"
name="your_awesome_parameter" value=""
type="number"
onchange="console.log($('input.my_class').rating().val())"/>
and simply you get the no. of rating in console now make a ajax call and add it to your DB .
Note: In case when you try static ratings for user view use code like that
max.times do |i|
%i{class: "glyphicon glyphicon-star#{'-empty' if i>val}"}
remember download bootstrap-rating-input.js file after success
Related
I am working on a form (which comes from the Laserfiche Forms application) and I am trying to change the text on a button that currently reads "Auto Fill" which is very non-descriptive since I have 5 of those buttons.
A little backstory: My code used to work and then all of a sudden one day it doesn't and creates an error where the user can only see the "Submit" button and the title of the form, but as soon as I comment out the below code the form works again but then I have those non-descriptive buttons again.
Is something wrong with my code?
document.getElementById("lookup1573").innerHTML = "Fill Section";
On button inspection, I see something a little odd:
<button id="lookup1573" class="autofill" type="button vo="d">Auto fill</button>
You had a typo in the html:
type="button vo="d"
This is the correct way:
<button id="lookup1573" class="autofill" type="button">Auto fill</button>
Here is the full example:
https://jsfiddle.net/o2er21v0/
That is not a typo but a customer parameter of Forms.
So here is the easy way to use these kind of things with forms:
Firstly, give all of your elements classes. Whilst outside of using Forms it is recommended to use ID's to reference your elements, doing that with Forms will give you more work, tenfold.
To note about Autofill buttons: they only appear on lookups that you have enabled them on (unless you are using an old version of Forms) and will appear next to the last element in your lookup (if that makes sense).
To change the name of your autofill buttons you are going to have to do so after the page has loaded.
Below is example code to do just that, assuming that the element that has the Autofill button you have given it a class of "vendorName".
The "vo" is actually very useful as you can use it to easily interact with your field content in conjunction with your classes. In the below example I am changing what is in the field without having to go into the code and work out what the number of the id is. This makes any code you make more portable as you can then implement it in other projects, projects where you ID numbers will be different. This is so flexible that it does not matter if the "vendorName" element is a normal text input, multi-line text area or a drop down menu as that same piece of code will work the same.
4:
$(function() {
$( ".vendorName .autofill").text( "Fill Section" );
});
5:
$( ".vendorName [vo]").val( "A New Vendor Name" );
Forms already uses the jQuery library so this will work just fine. Remember to give all of your elements a class (I usually name it the same as the variable). You can also give them multiple classes by separating the classes with a space.
I am having a big problem. I have the following tables
db.define_table('post',
Field('user_email', default=auth.user.email if auth.user_id else None),
Field('title', 'string', requires=IS_NOT_EMPTY()),
Field('body', 'text', requires=IS_NOT_EMPTY()),
Field('votes', 'integer', default=0, readable=False, writable=False),
auth.signature
)
db.define_table('comm',
Field('post','reference post'),
Field('body','text'),
auth.signature
)
So basically the user is able to create a post when he is logged in. I want to add the feature of adding comments on a post without reloading the whole page. In this case I would think I have to use the ajax function.
I don't quiet understand the way 'reference' works. I think that when I insert a new text I have to specify which post is coming from, but as I said, I am confused. Can u provide a brief explanation of how to relate the two tables? because I have to code a python function in which I have to specify the comments to be displayed on a specific post.
<div class="well">
<h1>{{=post.title}}</h1>
{{=post.body}}
</div>
{{if field_var_created_by == auth.user_id:}}
Edit Post
{{pass}}
<form>
<div class="form-group">
<label for="comment">Comment:</label>
<textarea class="form-control" rows="5" id="comment"></textarea>
<script>
document.write('hello');
</script>
</div>
</form>
Add Comments
As you can see I retrieved all the data of a post on a view by using a python function in the controller. I want to get the input of text area, put it in the database and then somehow display it on this post.
https://wwu39.pythonanywhere.com/prostudy
I have my website booted up on pythonanywhere. The problem I am having is in the forum page. To access the forum you have to log in. Don't worry I am not going to spam you. This is a small app no one will use. Go to forum, select a post and you will see the problem. The add comment button doesn't do anything yet. I have disabled the user authentication feature to make things easier for you
Web2py load component will be the best solution to your problem, exact same example is explained in
web2py book, read LOAD. If you use web2py component, you don't need to write any javascript code, also you can easily use same component at other places.
Go through the above example. You have to do few changes in table definition, controller and load url.
Add post column to comment schema, just like you did and make post column readable and writable false.
Because you don't want to show that column in form
db.define_table('comment_post',
Field('post','reference post', readable=False, writable=False),
Field('body','text'),
auth.signature
)
Then while embedding load component, pass post id as vars
{{=LOAD('comments','post.load', vars={'post_id': parent_post_id}, ajax=True)}}
Pass parent_post_id from parent controller, in your case i think request.args(0) contains parent id.
In controller, now use post_id passed from load url and set it to field post
def post():
db.comment_post.post.default = request.vars.post_id
return dict(form=SQLFORM(db.comment_post).process(),
comments=db(db.comment_post).select())
Hope this helps.
The question I have is very specific. I wanted to have an app where I can create forms, as on Wufoo, with easy to use interface. Which means, draggable elements.
My problem is that I cannot figure out how will the state be saved in the database once the use changes the ordinal position of the form elements. I can do the front-end side, and there are libraries available for that but how do I save a particular instance of the form in the backend so that the next time use logs in, the order is same.
I would love to use Django for this app. So, the basic classes I can think of are:
class Form(models.Model):
"""...objects..."""
class TextField(models.Model):
"""...objects..."""
#FK to Form()
class TitleArea(models.Model):
"""...objects..."""
#FK to Form()
I can also have specific ID's on the elements in the HTML form:
<input id="Field2" name="Field2" type="text"/>
How do they (Wufoo) do this? Is my Model not correct? I know it is naive. Thanks.
You can use ModelForm to create forms using a model instance. Just save the model after a user is done editing, and then when you create the form for them again use the model as an instance to your ModelForm (or formset):
form = YourForm(instance=model_instance)
hidden input fields for the win.
suppose:
$("#submitForm").click(function() {
// Check out the state of the union and change the hidden fields accordingly..
// Something like:
for (var i = 0; i < $(".orderedElements").length; i++) {
$("#ordered-" + ((Number) i + 1)).attr('value', $(".orderedElements").eq(i).attr('id'));
}
});
If you catch my drift.
Well, a good place to start is to think about a use-case. If I'm a user, what am I going to need available to me, to build a form? Textfields, sure -- but what else? Is the form going to have a title? A URL? An expiration date?
When you have this kind of information plotted out, then you can start building out your models in Django.
I have a combo box that will be loaded with a list of choices. When the user selects a choice, I need a JavaScript to simply run a query of MySql (obviously based on the user choice in the combo box) which will return a simple, discrete value that then needs to be displayed on the page next to the combo box.
The query is nothing more than SELECT foo FROM tblexample WHERE id = blah (where blah is the combo box value). The value will be a simple number. If the user chooses a new value, then it should just re-query and display the result.
I'm open to reading the whole table in upon page load into an array or something too. I work in PHP but I don't know Javascript; I was only hoping for a sample code bit; I can read and extrapolate most of the time.
I just didn't want to put a submit button in a form and force the user to do that each time they look at a new combo box choice. I wanted a more seamless, quick display for them.
JavaScript is a client-side language. It will not run MySQL queries (safely, at least). Use PHP to dynamically create the HTML and JavaScript for the combo box.
PHP has an entire section of their documentation reserved for MySQL.
I think you are actually looking for a reference in Ajax programming using PHP on the backend and javascript on the front end.
My recommendation would be to look at using one of the excellent Javascript development frameworks. Great candidates would be JQuery or Prototype. They both give you solid libraries to simplify programming in javascript.
Rather than working with sample code, you'll probably get a lot further by developing javascript expertise. Ajax is complicated, and you'll need to at least get basic skills together before you can start to integrate javascript and PHP.
Here's a good query to get started- I'd recommend beginning with JQuery if you have to pick one.
http://www.google.com/search?sourceid=chrome&ie=UTF-8&q=ajax+php+jquery+tutorial
Once you get started on jQuery as Tim mentioned you could do this,
The select box,
<form name="formName" action="" method="">
<select name="selName">
<option value={uniqueId}>Option 1</option>
</select>
</form>
<p class="displayMsg">No message to display.... yet</p>
The javascript and jQuery in a script tag of the head tag,
$(document).ready(function() {
$('select[name=selName]').change(function() {
function processData(data, success) {
...do something with the query results echoed into var data...such as
$('p.displayMsg').txt(data); // which will update the text node of the p tag class displayMsg
} // end function processData
var formData = $('form[name=formName]').serialize(); // this will encode the variables from the form to pass into post headers. You can access in your ajax called script with $_POST['selName']
$.post('phpAjaxProcessScript.php',formData,processDataClose); // sends data to script and when it's done it calls function processData
}); // end select change event function call
}); // end document ready event function call
Greetings
I have extended my admin add screen (tabularinline) by using the http://www.djangosnippets.org/snippets/1594/
Now I have a field in my model:
start = models.CharField(max_length=5)
this is intended as a special time format, it will be in a HH:MM format such as 16:30 . Now I want to implement a way that site auto assigns ":" between those numbers and for that I have found this jquery application: http://digitalbush.com/projects/masked-input-plugin/
When I check my admin add panel by firebug, I see that the field that I want to implement this masking function is:
<input id="id_outage_set-0-start" class="vTextField" type="text" maxlength="5" name="outage_set-0-start"/>
where "id_outage_set-0-start" is increased each time I add new.
Now I am looking for a way to implement these 2 together, I am a jquery newbie thus really lost at it.
Regards
This should apply the mask plugin to all inputs with an id that begins with id_outage_set. Is that what you are after?
jQuery(function($){
$("input[id*='id_outage_set']").mask("99/99/9999",{placeholder:" "});
});
A good approach would be to define your own Widget, whose HTML rendering applies the JQuery mask.
Stuart Langridge gives some infos on how to change a field widget in the Admin interface : http://www.kryogenix.org/days/2008/03/28/overriding-a-single-field-in-the-django-admin-using-newforms-admin
That would be a good idea to package this into a small django app.