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();
});
});
});
Related
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
I'm triying to paginate the response of an API. This API, have 15 items per page.
Actualy, i'm using something like this:
vm.next = function(currentPage){
$http.get('/api?page='+vm.firstPage++)
.then(function(data){
vm.chuck = data.data.Response;
});
}
vm.previous = function(currentPage){
$http.get('/api?page='+vm.firstPage--)
.then(function(data){
vm.chuck = data.data.Response;
});
}
and
vm.firstPage = 1;
My html view for buttons:
<div class="text-center">
<button type="button" class="btn btn-warning" ng-click="$ctrl.previous()">Previous</button>
<button type="button" class="btn btn-warning" ng-click="$ctrl.next()">Next</button>
</div>
The idea was to had the increment/decrement on every click. It works, but only after the second click. Also, if i change the value of vm.firstPage to 2, it works since the very first click, but when i click Previous, it becomes a mess.
What can i do to have the increment/decrement on the buttons?
I'm using AngularJs and javascript
I think it's about the operator precedence. Make vm.firstPage++/vm.firstPage-- before API call
vm.next = function(currentPage){
vm.firstPage++;
$http.get('/api?page='+vm.firstPage)
.then(function(data){
vm.chuck = data.data.Response;
});
}
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.
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.
is there a way to pass additional data to bootstrap modal function callback?
for example, lets say my link that causes the modal to open has an extra attribute in it with a bit of useful data in it, how could I reference that attr?
HTML
<span listid="80" href="#editTaskList" data-toggle="modal" class="btn btn-mini right"><i class="icon-edit"></i> Edit Task List</span>
JS
$('#editTaskList').on('show', function () {
// get the source of the click, and then get the data i need.
});
Could this work for you ?
<span listid="80" href="#editTaskList" data-toggle="datamodal" class="btn btn-mini right"><i class="icon-edit"></i> Edit Task List</span>
var $editTaskList = $('#editTaskList');
$('body').on('click.modal.data-api', '[data-toggle="datamodal"]', function (e) {
var $this = $(this);
$editTaskList.data('anyAttr',$this.data('anyAttr'));
$editTaskList.modal('show');
e.preventDefault();
})
$editTaskList.on('show', function () {
var myData = $editTaskList.data('anyAttr');
});
I know that this is an old question, but this is the first thing i've found on google. So, I want to put some important information here...
You NEED to put your callback function binded on events BEFORE you call the modal, for example:
$('#modal').on('shown', function(){
// Do something when the modal is loaded
});
$("#modal").modal();
This is very important and helped me a lot, so, here it is...
Like this -
<span id="modal_opener" data-extrastuff="stuff" listid="80" href="#editTaskList" data-toggle="modal" class="btn btn-mini right"><i class="icon-edit"></i> Edit Task List</span>
$('#modal_opener').click(function() {
var stuff_i_want = $(this).attr('data-extrastuff');
});