dfrojas
dfrojas

Reputation: 723

get a variables by GET in method get in DetailView django

Im trying to get the variable "segundos" by GET in the Detail View, im trying to get it by the method get:

the js file:

$(document).ready(function(){
    var segundos=340;
    console.log(segundos);
    $.ajax({
        data : {'segundos':segundos},
        url : '/ajax/puzzle-1/',
        type : 'GET',    
    });
});

views.py

class PuzzleView(DetailView):
    model = Puzzle
    template_name = 'puzzle.html'

    def get (self,request,*args,**kwargs):
        seconds = request.GET["segundos"]
        self.object = self.get_object()
        ranking = Ranking.objects.create(puzzle_id=self.object.id,usuario=self.request.user,segundos=seconds,puesto=89)
        context = self.get_context_data(object=self.object)
        return self.render_to_response(context) 

class RankingView(ListView):
    model = Ranking
    template_name = 'ranking.html'
    queryset = Ranking.objects.filter(puzzle_id=1).order_by('segundos')[:3]

class PuzzleAjaxView(TemplateView):
    template_name = 'ranking.html'

But i get the famous error "MultiValueDictKeyError". If i try the same method "get" but with a TemplateView, i can get the variable, but not with DetailView

Just in case, my urls.py:

urlpatterns = patterns('puzzle.views',
    url(r'^actividad/puzzle/(?P<slug>[-_\w]+)/$',PuzzleView.as_view(),name='puzzle'),
    url(r'^ajax/puzzle-1/.*$', PuzzleAjaxView.as_view(),name='ajax'),
    url(r'^ranking/.*$', RankingView.as_view(),name='ranking'),

    )

Upvotes: 0

Views: 1904

Answers (1)

 seconds = request.GET("segundos")

You can't just call the GET MultiValueDict. You must access by dictionary lookup. It is a subclass of a dict.

request.GET.get('segundos')
request.GET['segundos']

Update

For future reference, your exception traceback would have explained all of this, but the error message should be pretty clear: something along the lines of segundos not being a valid key in the MultiValueDict.

I assume your PuzzleView (what you are calling the DetailView) never gets passed any GET parameters because your example shows GET params only with your AJAX call, which is mapped to your PuzzleAjaxView (what you are calling the TemplateView

What is determining whether or not your get function works or not isn't based on the fact that your view class is a TemplateView or DetailView, it's the fact that segundos is only passed to your AJAX view.

In other words.. any view (TemplateView, DetailView, doesn't matter) accessing a GET dict via direct lookup request.GET['foobar'] will fail if that get parameter isn't passed in.

Upvotes: 3

Related Questions