python - Django get model by querystring -


i want user able pass querystring in url https://example.com/models?id=232. query string optional. https://example/models should work too. im trying this:

def myview(request, model):         context = {         'model': model,         }         if request.get.get('id', none) != none , model.objects.get(pk=request.get.get('id', none)).exists():             id = request.get.get('id', none)             context['id'] = id             return render(request, 'tests.html', context)         else:             return render(request, 'tests.html', context) 

s going on in code above: want check if there query string (which models id) , if there exists model. bu tmy code not work. if both of these requirement not satisfied should load tests.html without id , without errors. how can that? id should number looking forward answers :d

you getting error attributeerror: 'modelname' object has no attribute 'exists', because .exists() function available .filter(...) method.

def myview(request, model):     id = request.get.get('id', none)     context = {'model': model, 'id': id}      if id not none , id.isdigit():         if modelname.objects.filter(pk=id).exists():             context['id'] = id     return render(request, 'tests.html', context) 

another way, can use exception of modelname.doesnotexist;

# ... django.http import http404  def myview(request, model):     id = request.get.get('id', none)     context = {'model': model, 'id': id}      if id not none , id.isdigit():         try:             obj = modelname.objects.get(pk=id)             context.update({'id': obj.id})         except modelname.doesnotexist:             raise http404      return render(request, 'tests.html', context) 

Comments

Popular posts from this blog

Is there a better way to structure post methods in Class Based Views -

performance - Why is XCHG reg, reg a 3 micro-op instruction on modern Intel architectures? -

jquery - Responsive Navbar with Sub Navbar -