4

Is it possible to create function without template? Like I'm trying to create delete function and what I want to do is to delete something immediately after clicking the delete button and then redirect to other page.

I want to place a delete button on the page users can edit their post. html is like this

        <button type="submit" class="btn btn-outline-secondary">Save Changes</button>
        </form>

and I want to place delete button next to this button.

def edit_entry(request, entry_id):
    '''Edit a post.'''

    entry = Entry.objects.get(id=entry_id)

    if request.method != 'POST':
        form = EditEntryForm(instance=entry)
    else:
        form = EditEntryForm(instance=entry, data=request.POST)

            if form.is_valid():
            form.save()
            return HttpResponseRedirect(reverse_lazy('main:index'))
    return render(request, 'main/edit_entry.html', {'entry': entry, 'form': form})


def delete_entry(request, entry_id):
    '''Delete post'''
    #I don't wanna create template for this function.
    pass

Anyone who can give me tips?

2 Answers2

5

by the docs simple-view you can use the httpresponse

from django.http import HttpResponse

def delete_entry(request, entry_id):
    '''Delete post'''
    #I don't wanna create template for this function.
    return HttpResponse('done')
Brown Bear
  • 19,655
  • 10
  • 58
  • 76
  • 1
    Do I have to set the view function in urls.py? How can I call the function when I click the button? –  Jul 03 '18 at 08:12
  • 1
    Yes of course, you should add the function to the urls.py, and call it using jquery or othe front adn solution. – Brown Bear Jul 03 '18 at 08:16
0

Usually it make sense to use ajax for this purpose. In this case the handling of click splits into steps:

1) You click the button

2) jQuery (or any other javascript code) catches click event and sends AJAX request (usually post request, because post is used to for data modifications in REST agreement) to defined url on your server (like /delete/my/some/thing/) in urls.py

3) Djnago routes request to the delete_something view (or function)

4) delete_something takes request, checks what you want to check (like some permissions of current user), deletes what you actually want to delete and makes ajax response.

5) jQuery takes this response (which it actually waits on 3-4 steps) and checks response content to detect if server says everything is ok or there is some error.

So this is the code to create ajax request from jQuery:

$('#delete-button').click(function(){

var delete_id = (#delete-button).data()

$.ajax
({ 
    url: '/delete/my/some/thing/',
    data: {"id": delete_id},
    type: 'post',
    success: function(result)
    {
        // here you can write code to show some success messages
    },
    error: function(result) {
       // here you can write code to show some error messages or re-send request
    }
});

});

You also can use not $.ajax() method, but $.post(), if you want.

This is the code from this answer to make Django json response:

return HttpResponse(json.dumps(response_data), content_type="application/json")

It could look like this:

import json
from django.http import HttpResponse

def delete_something(request):
    resp_data = {}

    user = request.user
       delete_id = request.POST.get('delete_id') # or None, if there is no delete_id
    # here you can check user permissions, if your site has them
    # for example check that user can delete something and can delete this entity by writing check_user_can_delete() function

    if delete_id and check_user_can_delete(user):
      # do your deletion
      resp_data = {'status': 'ok'}
    else:
      resp_data.update(errors=[])

      if no delete_id:
         resp_data['errors'] = 'no delete_id'
      if not check_user_can_delete(user):
         resp_data['errors'] = 'you cave no permissions to delete delete_id'   
    resp = json.dumps(resp_data)
    return HttpResponse(resp, content_type='application/json')

Also note that Django 1.7 has JsonResponse object, as shown in SO answer I mentioned.

Paul
  • 6,641
  • 8
  • 41
  • 56