These are chat archives for django/django

10th
Nov 2016
J. Dalton Childers
@jdaltonchilders
Nov 10 2016 02:57

Hey everyone, I’m trying to do use sweet alert modal and ajax to delete an object, but I just can’t see to get it right…here’s my code…I’ll gladly take any pointer/suggestions.

Views.py

class AjaxableResponseMixin(object):
    """
    Mixin to add AJAX support to a form.
    Must be used with an object-based FormView (e.g. CreateView)
    """
    def form_invalid(self, form):
        response = super(AjaxableResponseMixin, self).form_invalid(form)
        if self.request.is_ajax():
            return JsonResponse(form.errors, status=400)
        else:
            return response

    def form_valid(self, form):
        # We make sure to call the parent's form_valid() method because
        # it might do some processing (in the case of CreateView, it will
        # call form.save() for example).
        response = super(AjaxableResponseMixin, self).form_valid(form)
        if self.request.is_ajax():
            data = {
                'pk': self.object.pk,
            }
            return JsonResponse(data)
        else:
            return response

class StudyDeleteView(PermissionRequiredMixin, AjaxableResponseMixin, DeleteView):
    model = Study
    success_url = reverse_lazy('study_list')
    permission_required = ['view_study', 'delete_study’]

template snippits

<button class="btn btn-white btn-sm btn-bitbucket delete_study delete_form"><i class="fa fa-trash"></i> Delete</button>
<script>
    $(document).ready(function () {
        $('.delete_study').click(function () {
            swal({
                title: "Are you sure?",
                text: "Your will not be able to recover this study!",
                type: "warning",
                timer: 7000,
                showCancelButton: true,
                confirmButtonColor: "#DD6B55",
                confirmButtonText: "Yes, delete it!",
                cancelButtonText: "No, cancel please!",
                closeOnConfirm: false,
                closeOnCancel: false 
            },
            function(){

            delete_form(function(){

            var primaryKey = $(this).data('study.id');

            $.ajax({
            url: "{% url 'study_delete' pk=study.id %}",
            dataType:"json",
            type:"POST",
            data:{
              pk: primaryKey,
              csrfmiddlewaretoken:'{{csrf_token}}',
            },
            success:function(json)
            {
               alert(json);

            },
        });     
        }); 
        });
    });
</script>

I’m using sweet alert’s modal: http://t4t5.github.io/sweetalert/

Before I added the ajax code the modal would at least popup, but now when I click the button nothing happens.
Slava
@scream4ik
Nov 10 2016 07:04
what about errors at javascript console?
Romeu Mello
@romeumellobr
Nov 10 2016 11:16
'''Page not found (404)
Request Method: GET
Request URL: http://127.0.0.1:8000/static/css/blog.css
'css\blog.css' could not be found'''
Radoslav Georgiev
@RadoRado
Nov 10 2016 11:19
@romeumellobr can you check the JavaScript that ended up in the browser? I see that you are using django templates there
Maybe something there went wrong after parsing
Romeu Mello
@romeumellobr
Nov 10 2016 11:34
@RadoRado theres no JavaScript, my issue is Django can't find css file, Even with "python manage.py collectstatic" wont work
Slava
@scream4ik
Nov 10 2016 11:35
please recheck your STATIC_ROOT, STATICFILES_DIRS, STATICFILES_FINDERS
Radoslav Georgiev
@RadoRado
Nov 10 2016 11:38
well it was working before you added the $.ajax({}) right?
Romeu Mello
@romeumellobr
Nov 10 2016 12:00
Solved! My folder
/static/ was in wrong directory, thank you guys
Vaibhav Tulsyan
@xennygrimmato
Nov 10 2016 14:04
Damilare Onajole
@damilare
Nov 10 2016 14:28
question here, how do I slice a queryset I am using for a prefetch query. as I am getting this error AssertionError: Cannot filter a query once a slice has been taken.
anyone familiar with this problem?
Slava
@scream4ik
Nov 10 2016 14:30
you can slice in template
i am not using a template for it
just the queryset
J. Dalton Childers
@jdaltonchilders
Nov 10 2016 15:59
@RadoRado Just the popup window, but after added the Ajax snippet the pop doesn’t even work.
Does anyone know of a good example for using ajax with django class based views. I know the docs have the mixin snippet you need to add, but I’m trying to find an example of how the front end code should look roughly.
Damilare Onajole
@damilare
Nov 10 2016 16:22
Ajax is such an old word
just saying
J. Dalton Childers
@jdaltonchilders
Nov 10 2016 16:23
@damilare Yes, yes it is! lol
Damilare Onajole
@damilare
Nov 10 2016 16:23
@jdaltonchilders and makes me feel old knowing that lol
Mark Heppner
@mheppner
Nov 10 2016 16:24
@jdaltonchilders Nothing should be any different if you’re using class-based views
J. Dalton Childers
@jdaltonchilders
Nov 10 2016 16:26

@mheppner So, I should just add the ajax mixin:

class AjaxableResponseMixin(object):
    """
    Mixin to add AJAX support to a form.
    Must be used with an object-based FormView (e.g. CreateView)
    """
    def form_invalid(self, form):
        response = super(AjaxableResponseMixin, self).form_invalid(form)
        if self.request.is_ajax():
            return JsonResponse(form.errors, status=400)
        else:
            return response

    def form_valid(self, form):
        # We make sure to call the parent's form_valid() method because
        # it might do some processing (in the case of CreateView, it will
        # call form.save() for example).
        response = super(AjaxableResponseMixin, self).form_valid(form)
        if self.request.is_ajax():
            data = {
                'pk': self.object.pk,
            }
            return JsonResponse(data)
        else:
            return response

Then setup the ajax on the front end?

Slava
@scream4ik
Nov 10 2016 16:27
then you need inherit from AjaxableResponseMixin and for example CreateView (or UpdateView)
J. Dalton Childers
@jdaltonchilders
Nov 10 2016 16:27

@scream4ik

Like so?

class StudyUpdateView(AjaxableResponseMixin, PermissionRequiredMixin, UpdateView):
    model = Study
    permission_required = ['view_study', 'change_study']
    fields = ['name', 'start_date', 'end_date', 'quota’]
Slava
@scream4ik
Nov 10 2016 16:28
yes
then you need setup ajax on the front end
J. Dalton Childers
@jdaltonchilders
Nov 10 2016 16:29

Apologizes, I updated and posted the wrong view. I’m trying to do a popup for deleting a study.

class StudyDeleteView(AjaxableResponseMixin, PermissionRequiredMixin, DeleteView):
    model = Study
    success_url = reverse_lazy('study_list')
    permission_required = ['view_study', 'delete_study’]

I’m using sweetalert for the popup.

Screenshot 2016-11-10 10.29.40.png
Slava
@scream4ik
Nov 10 2016 16:33
do you try send html form?
J. Dalton Childers
@jdaltonchilders
Nov 10 2016 16:34
No, sweet alert structure this like this:
swal({
  title: 'Are you sure?',
  text: "You won't be able to revert this!",
  type: 'warning',
  showCancelButton: true,
  confirmButtonColor: '#3085d6',
  cancelButtonColor: '#d33',
  confirmButtonText: 'Yes, delete it!',
  cancelButtonText: 'No, cancel!',
  confirmButtonClass: 'btn btn-success',
  cancelButtonClass: 'btn btn-danger',
  buttonsStyling: false
}).then(function() {
  swal(
    'Deleted!',
    'Your file has been deleted.',
    'success'
  )
}, function(dismiss) {
  // dismiss can be 'cancel', 'overlay',
  // 'close', and 'timer'
  if (dismiss === 'cancel') {
    swal(
      'Cancelled',
      'Your imaginary file is safe :)',
      'error'
    )
  }
})

Currently, we have it setup to were you click a button

<a href="{% url 'study_delete' pk=study.id %}" class="btn btn-white btn-sm btn-bitbucket delete_study"><i class="fa fa-trash"></i> Delete</a>

And it takes you to this html page

{% extends "base.html" %}

{% load guardian_tags %}

{% block title %}Confirm Study Deletion{% endblock %}

{% block content %}
<p>Are you sure do you want to delete "<a href="{{object.get_absolute_url}}">{{object}}</a>"?</p>
<form method="POST">
    {% csrf_token %}
    <input type="submit" class="btn btn-primary" value="Delete">
</form>
{% endblock %}
Slava
@scream4ik
Nov 10 2016 16:36
redefine
def get(self, *args, **kwargs):
    return self.post(*args, **kwargs)
J. Dalton Childers
@jdaltonchilders
Nov 10 2016 16:36
It’s just a really basic page so I’m trying to convert it into more of a popup for the users.
@scream4ik Are you saying I need to add this to the views.py?
Slava
@scream4ik
Nov 10 2016 16:37
yes
J. Dalton Childers
@jdaltonchilders
Nov 10 2016 16:38
So:
class StudyDeleteView(AjaxableResponseMixin, PermissionRequiredMixin, DeleteView):
    model = Study
    success_url = reverse_lazy('study_list')
    permission_required = ['view_study', 'delete_study']

    def get(self, *args, **kwargs):
        return self.post(*args, **kwargs)
My assumption is under the Delete View
Slava
@scream4ik
Nov 10 2016 16:38
yes
J. Dalton Childers
@jdaltonchilders
Nov 10 2016 16:38
For future reference what exactly is this doing?
I understand Get/Post and some of the basic Django concepts. I’d just like to understand how this make’s it work correctly.
Mark Heppner
@mheppner
Nov 10 2016 17:38
You’re just reusing the same functionality for the other HTTP method
I honestly don’t see why you need that though
J. Dalton Childers
@jdaltonchilders
Nov 10 2016 17:56
@mheppner Which part?
Mark Heppner
@mheppner
Nov 10 2016 17:58
@jdaltonchilders adding the def get(). I think you’re fine with just inheriting the DeleteView
J. Dalton Childers
@jdaltonchilders
Nov 10 2016 17:58
@mheppner I’ll try it with and without. Currently, I’m just trying to make the ajax on the frontend work.
Saurabh K
@skulk001
Nov 10 2016 17:59
Is there a way to inspect the raw sql that django creates on model save?
Mark Heppner
@mheppner
Nov 10 2016 18:01
@skulk001 you can use django_debug_toolbar, which also provides a command to start a shell with SQL logging enabled. otherwise, the easiest way is to add your own log handler
@jdaltonchilders if you’re going to add additional ajax-y things, i’d recommend using django-rest-framework or tastypie. both are pretty easy to set up a simple api. it’s easier to keep your normal django views separate from your ajax stuff
Saurabh K
@skulk001
Nov 10 2016 18:04
@mheppner I am using DRF with DJDT. For some reason when I send the post request, the object data shows up when I hit "Post" but nothing gets saved to the postgresdb and I don't see the DjDt toolbar either.
J. Dalton Childers
@jdaltonchilders
Nov 10 2016 18:04
@mheppner I’ve never used Django-rest-framework…does the auth from regular django integrate out of the box or do I need to setup separate things?
Mark Heppner
@mheppner
Nov 10 2016 18:05
@jdaltonchilders it provides different auth mechanisms, but the “normal” session auth works out of the box.
Saurabh K
@skulk001
Nov 10 2016 18:05
@mheppner I am using session auth
Mark Heppner
@mheppner
Nov 10 2016 18:06
@skulk001 if you upgraded to django 1.10 and are using the latest debug_toolbar, you’ll have to adjust your settings. check out the new docs for installing debug_toolbar
@jdaltonchilders then you should be fine. check out the tutorial. towards the end, they’ll show you how to use a ModelViewSet, which provides you with full access for listing, getting, updating, creating, and deleting
Saurabh K
@skulk001
Nov 10 2016 18:08
@mheppner I can see DJDT bar on the main page, its only after I submit the post request that the bar disappears. Since the sql is generated after I submit - I cannot see it.
Mark Heppner
@mheppner
Nov 10 2016 18:09
@skulk001 where are you submitting the post request? on the browsable api page?
Saurabh K
@skulk001
Nov 10 2016 18:09
@mheppner yup
Mark Heppner
@mheppner
Nov 10 2016 18:10
@skulk001 then it should show up still and properly intercept the post’ed request. regardless, you can still just add a logging handler for all the sql calls and get it that way
Saurabh K
@skulk001
Nov 10 2016 18:10
@mheppner tried saving the model instance from shell as well. Using model.save()
@mheppner no errors but nothing gets created. Scratching my head on this for a while now
@mheppner do you mind elaborating this "regardless, you can still just add a logging handler for all the sql calls and get it that way"
Mark Heppner
@mheppner
Nov 10 2016 18:11
@skulk001 then i would imagine django isn’t connected to the db. or your db is in read-only mode or something. check the output of from django.conf import settings; dir(settings) to see what is set for your database connection
Saurabh K
@skulk001
Nov 10 2016 18:12
@mheppner here is the kicker, I am able to save data for other models in the same project and same db
Mark Heppner
@mheppner
Nov 10 2016 18:18
@skulk001 you can change your logging config and see the queries. if you can save other models, then i’d try reapplying the migrations for the table you’re having problems with
J. Dalton Childers
@jdaltonchilders
Nov 10 2016 18:20
@mheppner Awesome, for this project we're only using the default sessions for this project. So I'll take a look at that. Originally my supervisor was against using the rest framework, but if it could simplify things it maybe the better route. I'm not sure how much Ajax stuff will be in the project currently.
Mark Heppner
@mheppner
Nov 10 2016 18:21
@jdaltonchilders even if you just had that one route, it shouldn’t add too much complexity to the project. but if your boss is against it, just go back to your original class based views lol
Saurabh K
@skulk001
Nov 10 2016 18:21
@mheppner thanks man for the good pointers.
J. Dalton Childers
@jdaltonchilders
Nov 10 2016 18:21
There's a lot of things I'd rather have in modals so I'm assuming the instances will grow.
@mheppner yeah, I'll just have to see right now I need to get the Ajax working without the sweet alert and then add the alert stuff. I think by trying to add in the alert stuff then Ajax I'm over complicating the problem.