刷新后保持Django选择的选项(窗体/选择)

时间:2020-05-14 19:32:14

标签: python django select filter

刷新后未保存我的Django应用中的

选择选项。下面是我的代码:

if (message.content === spam && message.author.id === "ID_HERE") {
<! –– jobs.html ––>
{% block content %}
<form id="job-main-form" method="get" action="#" class="job-main-form">
    <select form="job-main-form" name="specialization" class="form-control" id="specialization">
        <option selected="selected" value="all">Všechny obory</option>
        {% for specialization in specializations %}
        <option value="{{ specialization|lower }}">{{ specialization }}</option>
        {% endfor %}
    </select>
    <button type="submit" class="btn btn-outline-white-primary job-main-form__button">
        <i class="fa fa-search"></i>
    </button>
</form>
{% endblock %}
# views.py
from django.views import generic

from .models import Job
class JobListView(generic.ListView):
    model = Job
    template_name = 'jobsportal/jobs.html'
    context_object_name = 'jobs'
    paginate_by = 5
    specializations_list = [
        'Alergologie',
        'Anesteziologie',
    ]

    def get_queryset(self):
        q = self.model.objects.all()
        if self.request.GET.get('specialization') and self.request.GET.get('specialization') != "all":
            q = q.filter(specialization__icontains=self.request.GET['specialization'])
        return q
# models.py
from django.db import models

# Create your models here.


class Hospital(models.Model):
    PRAHA = 'PHA'
    STREDOCESKY = 'STC'
    REGIONS = [
        (PRAHA, 'Hlavní město Praha'),
        (STREDOCESKY, 'Středočeský kraj'),
    ]
    key = models.CharField(max_length=20)
    name = models.CharField(max_length=200)
    region = models.CharField(max_length=50, choices=REGIONS)
    city = models.CharField(max_length=50)
    website = models.CharField(max_length=300, default="")
    logo = models.CharField(max_length=300)
    objects = models.Manager()

    def __str__(self):
        return self.name


class Job(models.Model):
    title = models.CharField(max_length=300)
    specialization = models.TextField()
    detail = models.CharField(max_length=300, default="")
    hospital = models.ForeignKey(Hospital, on_delete=models.CASCADE)
    objects = models.Manager()

    def __str__(self):
        return self.title

所以我在select =“ all”中有默认选项。当我更改它并单击按钮进行过滤时,我得到了正确的过滤数据,但是选择选项又变回了“全部”。因此用户不会看到自己选择的选项,这不是预期的行为。

感谢您的帮助。

1 个答案:

答案 0 :(得分:0)

您将需要将“ selected”值传递回html,因此您可以将selected标志添加到正确的<option>

<option value="{{ specialization|lower }}" 
    {% if specialization.selected %} selected {% endif %} >
    {{ specialization }}
</option>