Ryan Chandra
Ryan Chandra

Reputation: 132

Django : Maintaining option selected in HTML template

when I use the django if function in the html template to set changes to the selected option tag, but its keep selecting the --SELECT-- option

 <form  method="post">

<select name="name">
<option >--SELECT--</option>
  {% for job in all_pekerjaan%}
  <option value="{{job.id}}"
         {% if job.id == current_name %}selected="selected"{% endif %}>
         {{job.name}}
     </option>
    {% endfor %}
</select>
{% csrf_token %}

  <input type="submit" class="btn btn-success" value="submit" >
</form>

and this is my views.py

from django.http import HttpResponse
from .models import daftartabel, Pekerjaan
from .forms import form1, form2
from django.template import loader
from django.shortcuts import render

def index(request):

    if request.method == 'POST':
        #print(request.POST['name'])
        current_name=request.POST['name']
        all_datas = daftartabel.objects.filter(pekerjaan_id=request.POST['name'])
    else:
        all_datas = daftartabel.objects.all()
    all_pekerjaan = Pekerjaan.objects.all()
    template = loader.get_template('tabel/index.html')
    #print(all_datas)
    #print(all_pekerjaan)
    context = {
        'all_datas' : all_datas,
        'all_pekerjaan' : all_pekerjaan,
        'current_name' : request.POST['name'],
    }
    #print (context)
    print(type(context['current_name']))

    return HttpResponse(template.render(context, request))

my forms.py class

class form2(forms.Form):
    name = forms.CharField(max_length=100)

anyone know how to fix this issue?

Upvotes: 6

Views: 3142

Answers (2)

Ryan Chandra
Ryan Chandra

Reputation: 132

The issue solved, changing 'current_name' into integer would help.

if request.method == 'POST':
        context = {
            'all_datas' : all_datas,
            'all_pekerjaan' : all_pekerjaan,
            'current_name' : int(request.POST['name']),
            }
    else:
                context = {
                    'all_datas' : all_datas,
                    'all_pekerjaan' : all_pekerjaan,
                    }

Upvotes: 6

Reynold Bhatia
Reynold Bhatia

Reputation: 139

Declare your variables before the condition. So something like this

def index(request):
    current_name = 0 /*0 or None based on what kind of value it carries*/ 
    all_datas = None
    if request.method == 'POST':
        #print(request.POST['name'])
        current_name=request.POST['name']
        all_datas = daftartabel.objects.filter(pekerjaan_id=request.POST['name'])
    else:
        all_datas = daftartabel.objects.all()

Moreover, remove the last comma in the assignment of context object

context = {
        'all_datas' : all_datas,
        'all_pekerjaan' : all_pekerjaan,
        'current_name' : request.POST['name']
    }

Upvotes: 0

Related Questions