Answer the question
In order to leave comments, you need to log in
Can anyone share generic ajax examples for Django?
I'm learning Django, I want to make a vote on the page so that the voting results are shown without reloading the page. At the same time, I don’t want to learn js, and indeed the frontend.
Does anyone have a ready-made example for getting data from a form into a view, with a different url than the current one? Issues in template div with context?
And if possible, then you can show =)
template in my example:
<div>
<form id="photo_vote_form" action="{% url "vote" photo.id %}" method="post">
{% csrf_token %} {{ form.as_p }}
<input type="hidden" name="next" value="{{ request.path }}" />
<input type="submit" value="Отправить" />
</form>
</div>
url(r'^$', FeedMainView.as_view(), name='feed'),
url(r'^(?P<pk>\d+)/vote/$', 'feed.views.vote', name= 'vote'),
class FeedMainView(LoggedInMixin, TemplateView):
template_name = 'feed/base_feed.html'
def get_context_data(self, **kwargs):
context = super(FeedMainView, self).get_context_data(**kwargs)
context["form"] = VoteForm()
return context
def vote(request, pk):
photo = Photo_vote.objects.get(pk=pk)
if request.method == 'POST':
form = VoteForm(request.POST)
if form.is_valid():
temp =form.save()
...
return HttpResponseRedirect(photo.get_absolute_url())
return http.HttpResponseRedirect(photo.get_absolute_url)
Answer the question
In order to leave comments, you need to log in
If you need something universal, then the REST Framework is taken , but, of course, you need to read the documentation on it.
In my practice, usually such scripts are written every time, as for the first time) Depends on the project, of course.
In theory, you need to make a minimum of changes in your code.
First, you need to adjust the view so that it returns json data. Here you can choose from several options. For example, with class-based-views or use the render_to_json decorator for a regular view from the handy auxiliary package .
In the client side, a very simple code will turn out if you use the popular JQuery framework, of course.
$('.vote').on('click', function(ev){
ev.preventDefault();
var $this = $(this);
$.post($this.attr('data-url'))
.success(function(data){
if (data.error){
alert(data.error);
}else if (data.voted){
alert('Спасибо за ваш голос!');
}
})
.fail(function(){
alert('Возникла ошибка. Попробуйте позже.');
})
});
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question