Django modal forms with ajax tables - javascript

I am using modal forms with django ajax tables:
https://pypi.org/project/django-bootstrap-modal-forms/
https://pypi.org/project/django-ajax-tables/
How can I update data asychronously by the modal form?
Here is some example code:
Registered Views:
def index(request):
return render(request, 'proto/index.html')
class BookTableView(View):
model = Books
my_table = BooksTable
def get(self, request):
data = self.model.objects.all()
#filtering
table = self.my_table(data)
RequestConfig(request, paginate = {"per_page": 6, "paginator_class": LazyPaginator}).configure(table)
return HttpResponse(table.as_html(request))
class BookUpdateView(BSModalUpdateView):
model = Books
template_name = 'proto/books/update_book.html'
form_class = BookModelForm
success_message = 'Success: Book was updated.'
success_url = reverse_lazy('index')
Table:
class BooksTable(tables.Table):
column1 = tables.TemplateColumn(verbose_name='Read',
template_name='proto/columns/column1.html',
orderable=False)
column2 = tables.TemplateColumn(verbose_name='Update',
template_name='proto/columns/column2.html',
orderable=False)
class Meta:
model = Books
Column2 html template button
<button type="button" class="update-book btn btn-sm btn-primary" data-form-url="{% url 'update_book' record.id %}" onclick="updateBookModalForm()">
<span class="fa fa-pencil"></span>
Close update buttons on update_book.html modal form
<button type="button" class="close" data-dismiss="modal" aria-label="Close" onclick="update_books_id('', '/proto/books')">
<span aria-hidden="true">×</span>
</button>
...
<div class="modal-footer">
<button type="button" class="submit-btn btn btn-primary">Update</button>
</div>
Calling ajax tables on index.html and javascript for modals :
...
<div class="col-12 mb-3">
{% ajax_table "books_id" "books" %}
</div>
<script>
function updateBookModalForm() {
$(".update-book").each(function () {
$(this).modalForm({
formURL: $(this).data("form-url"),
asyncUpdate: true,
asyncSettings: {
closeOnSubmit: false,
successMessage: asyncSuccessMessageUpdate,
dataUrl: "books/",
dataElementId: "#books-table",
dataKey: "table",
addModalFormFunction: updateBookModalForm
}
});
});
}
updateBookModalForm();
</script>
Surprisingly this works and appears assyncronouse on the frontend even not adding a books/ url, but I get a Not Found proto/books on terminal as expected. My question is how to make the update asynchronous on the ajax table without redirecting to the homepage. I really have tried a lot of things with the javascript function, but any modifications I make, mostly taking things out makes it break the update. Really just making the update is enough, what i want is no redirection after the update or any advice on what is the best way to go from here.
Thank you for your time.
reivaJ

Related

Update single row of table in template page using ajax in Django

I am working on Django project and I have no idea of ajax that how to implement it. The scenario is my db contains a table name "demo" which contains the column stat_id. My database contains the following details:
table name = demo
id int primary key NOT NULL,
stat_id int(11) NOT NULL #value is 1
Now, the scenario is that I am getting the stat_id value from database and its purpose to show the running and complete button. If python script is running then it will display the running button and if python script has executed it will display the completed button.
status.html:
<td>
<form action = "/modules" method="get">
{% if status == 1 %}
{% csrf_token %}
<button link="submit" class="btn btn-default btn-sm">
<span class="badge badge-dot mr-4">
<i class="bg-success"></i>Completed</button>
</form>
{% else %}
<button type="button" class="btn btn-default btn-sm">
<span class="badge badge-dot mr-4">
<i class="bg-warning"></i>Running</button>
{% endif %}
views.py:
def process(request):
hash_id = request.session.get('hash_id')
print(hash_id)
check = request.session.pop('check_status',)
if hash_id and check:
stat = status_mod.objects.filter(hash_id = hash_id).order_by('-id').first()
if stat:
stat = stat.stat_id
print(stat)
return render(request, 'enroll/status.html', {'status': stat})
urls.py:
path('status', views.process, name='process')
models.py:
class status_mod(models.Model):
id = models.BigIntegerField(primary_key=True)
stat_id = models.BigIntegerField()
class Meta:
db_table = "demo"
jquery / ajax in my status.html page:
<script>
$(document).ready(function() {
setInterval(function() {
$.ajax({
type: 'GET',
url: "{% url 'process' %}",
success: function(response){
console.log(response)
},
error: function(response){
alert("NO DATA FOUND")
}
});
}, 2500);
});
</script>
Now, I want to update my table row as situation will be if status == 1 then completed button will display else running. Hence it is working fine without ajax but I have to refresh again and again when process function is executed. So, I want to use ajax in this case to update the table row automatically without reloading it.

Django jquery AJAX form submission in view and display results

There are a lot of different posts about all parts of this, I just can't quite figure out how it all fits together.
I have name that is displayed with an update button next to it. When the update button is clicked it shows a form to update the name. In the form is a save changes button. When the changes are saved, it should reload the name at the top, and should the update button be clicked again, the form should show the new name info.
urls.py
path('profile/<int:pk>/', views.customer_profile, name='profile'),
path('update-profile/<int:pk>/', views.update_profile, name='update-profile'),
views.py
def customer_profile(request, pk):
name = get_object_or_404(CEName, id=pk)
name_form = NameForm(instance=name)
return render(
request,
'customer/customer_profile.html',
{'name':name, 'NameForm': name_form}
)
def update_profile(request, pk):
if request.POST:
name_form = NameForm(request.POST)
if name_form.is_valid():
name_form.save()
name = get_object_or_404(CEName, id=pk)
context = {'name':name, 'NameForm': name_form}
html = render_to_string('customer/customer_profile.html', context)
return HttpResponse(html, content_type="application/json")
template.html
<div id="name" class="container d-flex justify-content-between pt-1">
{{ name }}
<button id="update_button" class="bold btn btn-main btn-sm button-main">UPDATE</button>
</div>
<div id="div_NameForm" class="container" style="display: none;">
<hr size="3px">
<form id="NameForm" method="POST" data-url-name="{% url 'customer:update-profile' name.id %}">
{% csrf_token %}
{{ NameForm.as_p }}
<br>
<button type="submit" id="save_changes" class="btn btn-main button-main btn-block">Save Changes</button>
</form>
</div>
<script src="{% static 'ce_profiles/ce_profiles_jquery.js' %}"></script>
jquery.js
$('#save_changes').click(function() {
var NameForm = $('#NameForm');
$.ajax({
type: 'post',
url: NameForm.attr('data-url-name'),
data: NameForm.serialize(),
dataType: 'json',
success: function(data, textStatus, jqXHR) {
$('#name').html(data);
}
});
});
The code for the update button toggle is not displayed.
In your jQuery, to start with.
- First, you could (some may say should) have put a submit event handler on the on the form instead of a click event for button.
- Second, you are doing an AJAX call so you should prevent form submission using .preventDefault() on the submit event that was trigged when the button was pressed. This will prevent the page from reloading.
- Third, in your ajax success callback you should use text() instead of html() since name I imagine is text and not html, however that's just an assumption.
$('#NameForm').on('submit', function(evt) {
evt.preventDefault();
var NameForm = $('#NameForm');
$.ajax({
...
success: function(response) {
$(#name).text(response); // or response.name or whatever
}
});
})

Django Ajax Update Div without Refresh

I'm trying to update <strong id="vote_count"> without having the refresh the page. Currently, the ajax request gets posted, but I have to manually refresh to page to update the vote count. recommendation.get_total_votes is originally a function in recommendation model.
html
<div id="vote_count">Vote Count: {{ recommendation.get_total_votes }}</div>
<br>
<button class="upvotes" data-recommendation="{{ recommendation.id }}" class="btn btn-primary" type="button">
<span class="glyphicon glyphicon-thumbs-up"></span>
Upvote1
</button>
ajax.js
$(document).on("click", ".upvotes", function(){
console.log('my message');
var recommendationid = $(this).attr("data-recommendation");
$.post('/upvote/', {recommendation_id: recommendationid}, function(data){
console.log('my message1');
$('#vote_count').html(data);
$('#upvotes').hide();
});
});
views.py
#csrf_exempt
#login_required
def upvote(request):
recommendation_id = None
if request.method == 'POST':
recommendation_id = request.POST['recommendation_id']
get_total_votes = 0
if recommendation_id:
recommendation = coremodels.Recommendation.objects.get(id=int(recommendation_id))
user = request.user
recommendation.votes.up(user)
get_total_votes = recommendation.votes.count()
return HttpResponse(get_total_votes)
models.py (edit):
class Recommendation(models.Model):
topic = models.ForeignKey(Topic)
user = models.ForeignKey(User)
title = models.CharField(max_length=300)
votes = VotableManager()
def get_total_votes(self):
total = self.votes.count()
return int(total)
Thanks for all the trouble shooting. I was able to work around this issue by changing
$('#vote_count').html(data);
$('#upvotes').hide();
to
$('.vote_count').html(data);
$('.upvotes').hide();
And use class instead of id tags in html. Still unsure why id tags are not working.

Add Friend with Ajax - Django

I'm using Django-Friends
I'm trying to have it so when a user clicks on the add friend, the button disappears(or ideally says Request sent). However, when I click the button, it doesn't disappears. I am new at Django and Ajax, so I'm assuming that this is an error on my part. Most likely the HttpResponse.
That part actually confuses me a lot. The HttpResponse, render, render_to_response, etc. I know that I can use render or render_to_response when I want to load a template. But what if I don't want to load up a new template or go to a new page? Like I want to be able to complete an action like add a friend, or add a page, etc; all on one page. I know you can use ajax to do it, but I don't know the django technical aspect of it.
Anyway, here's my code. Right now, nothing happens. The button doesn't disappear, and there is no friendships request sent.
profile.html
<div class="text-center">
<div>
"{{currUserprofile.tagline}}"
</div>
{{currUser.profile.city}}, {{currUser.profile.state}}
{{currUser.id}}
</div>
<!-- <button id="addfriend" data-profileid="{{currUser.id}}" class="btn btn-primary" type="button"> <span class="glyphicon glyphicon-plus"></span>
Request Friend</button>
--> <!--Find a way to signify looking or not looking to mentor -->
<button id="addfriend" data-profileid="{{currUser.id}}" class="btn btn-primary" type="button"> <span class="glyphicon glyphicon-plus"></span>
Request Friend</button>
ajax.js
$(document).ready(function () {
$('#addfriend').click(function () {
var profile_id = $(this).data("profileid");
$.get('/myapp/addfriend/id=' + profile_id, function (data) {
$('#addfriend').fadeOut();
});
});
})
views.py
#login_required
def profile(request, id):
context = RequestContext(request)
currUser = User.objects.get(pk = id)
profile = UserProfile.objects.filter(user = currUser)
return render_to_response('myapp/profile.html', {'currUser': currUser, 'UserProfile': UserProfile}, context)
#login_required
def addfriend(request, id):
context = RequestContext(request)
other_user = User.objects.get(pk=id)
new_relationship = Friend.objects.add_friend(request.user, other_user)
profile = UserProfile.objects.filter(user = other_user)
return HttpResponse(new_relationship)
Here is a working JSFiddle, but you can't post data {profile_id: profile_id}with a getyou should use a postor add the data as params, as I did:
HTML:
<button id="addfriend" data-profileid="{{currUser.id}}" class="btn btn-primary" type="button"> <span class="glyphicon glyphicon-plus"></span>
Request Friend</button>
JS:
$(document).ready(function () {
$('#addfriend').click(function () {
var profile_id = $(this).data("profileid");
$.get('/myapp/addfriend/?profile_id=' + profile_id, function (data) {
$('#addfriend').fadeOut();
});
});
});

Submitting form after JS logic in Django

I have a form that enables user input. Upon submit, some javascript will perform some logic to be passed to /test/ URL. Right now the issue is that I am not being redirected to/test/ URL.
JS:
$(document).ready(function() {
var testRun = document.getElementById("test-form");
testRun.addEventListener('submit', function(event) {
testData["timestamp"] = new Date().getTime();
event.preventDefault();
// more logic
return jsonData;
});
});
home_page.html
<form id="test-form" action="/test/" method="post"> {# pass data to /test/ URL #}
{% csrf_token %}
<div class="test-button-set">
<button type="button" id="hdfs-test" class="btn btn-default btn-lg selected">HDFS</button>
<button type="button" id="hive-test" class="btn btn-default btn-lg">HIVE</button>
<button type="button" id="hdfs-hive-test" class="btn btn-default btn-lg">BOTH</button>
</div>
{{ form.event_textarea }}
<button id="submit-test" type="submit" class="btn btn-default btn-lg">Submit</button>
</form>
forms.py
class TestForm(forms.Form):
event_textarea = forms.CharField(widget=forms.Textarea(attrs={'rows': '8', 'class': 'form-control', 'placeholder': 'Events...', 'id': 'event-textarea'}))
views.py
from django.shortcuts import render
from forms import TestForm
from django.http import HttpResponseRedirect
def home(request):
if request == 'POST':
# create a form instance and populate it with data from the request
form = TestForm(request.POST)
if form.is_valid():
# process the data in form.cleaned_data as required
form.cleaned_data()
# redirect to a new URL:
return HttpResponseRedirect('/test/')
# if a GET (or any other method) we'll create a blank form
else:
form = TestForm()
return render(request, 'home/home_page.html', {'form': form})
def test(request):
return render(request, 'home/test.html', {'post': request.POST})
My /test/ url is made to display the post request so I can see for sure what I am posting. Currently the JS logic (I've set up indicators of the output) is working but I am not being redirected so I'm not sure if anything is getting posted to the URL
This line will prevent the default event (the form submission) from happening:
event.preventDefault();
Remove that and the form should submit as expected.

Categories

Resources