Skip to content

Instantly share code, notes, and snippets.

@goldhand
Created July 19, 2013 05:43
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 3 You must be signed in to fork a gist
  • Save goldhand/6036901 to your computer and use it in GitHub Desktop.
Save goldhand/6036901 to your computer and use it in GitHub Desktop.
Updates any Task model without reloading using ajax
#views.py
class TaskUpdateView(generic.UpdateView):
model = Task
form_class = TaskForm
@json_view
def dispatch(self, *args, **kwargs):
return super(TaskUpdateView, self).dispatch(*args, **kwargs)
def form_valid(self, form):
form.save()
return {'success': True}
def form_invalid(self, form):
form_html = render_crispy_form(form)
return {'success': False, 'form_html': form_html}
def get(self, request, *args, **kwargs):
object = super(TaskUpdateView, self).get_object()
form_html = render_crispy_form(TaskForm(instance=object))
context = {'form_html': form_html}
return context
class TaskListUpdateView(generic.ListView):
model = Task
template_name = 'tasks/task_update_json.html'
#task_update_json.html
{% block content %}
<h1>Tasks</h1>
<select class="select" id="task_selector" name="task_selector">
<option value="" selected="selected">---------</option>
{% for task in task_list %}
<option value="{{ task.id }}" id="task-option-{{ task.id }}">{{ task.title }}</option>
{% endfor %}
</select>
<div id="task-form"></div>
{% endblock %}
{% block extra_js %}
<script>
var taskSelector = $('#task_selector');
var update_url = "/cpm/tasks/update/";
var taskId = $(taskSelector).val();
function getCookie(name) {
var cookieValue = null;
if (document.cookie && document.cookie != '') {
var cookies = document.cookie.split(';');
for (var i = 0; i < cookies.length; i++) {
var cookie = jQuery.trim(cookies[i]);
// Does this cookie string begin with the name we want?
if (cookie.substring(0, name.length + 1) == (name + '=')) {
cookieValue = decodeURIComponent(cookie.substring(name.length + 1));
break;
}
}
}
return cookieValue;
}
function getTaskForm(t_id) {
$.getJSON(update_url + t_id + '/', function (data) {
$('#task-form').replaceWith(data['form_html']);
}).done(function() {
submitAjax($("#submit-id-save_task"));
});
}
taskSelector.change(function() {
taskId = $(taskSelector).val();
getTaskForm(taskId);
});
function submitAjax(button) {
$(button).click(function(e) {
e.preventDefault();
console.log($('#task-form').serialize());
var task_form_title = $('#task-form').find('#id_title').val();
$.ajax({
url: update_url + taskId + '/',
type: "POST",
data: $('#task-form').serialize() + '&csrfmiddlewaretoken=' + getCookie('csrftoken'),
success: function(data) {
if (!(data['success'])) {
$('#task-form').replaceWith(data['form_html']);
}
else {
$('#task-option-' + taskId).text(task_form_title);
$('.error').removeClass('error');
$('.help-block').hide();
}
},
error: function () {
}
}).done(function() {
submitAjax($("#submit-id-save_task"));
});
return false;
});
}
</script>
{% endblock extra_js %}
@schinckel
Copy link

I'd suggest you store the full url as the value of the option (preferably generated using {% url %}), so it is a bit more robust if you move the url location later.

@goldhand
Copy link
Author

I did try but my "tasks:update" url uses a pk. Should I add another url pattern and do something like:

url: '{% url "tasks:update-no-pk" %}' + taskId + '/',

or is there another way?

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment