Django:如何在页面加载时清除会话变量,这样分页器就不会清除它们

Django: how to clear session variables on page load, that way that paginator won't clear them

提问人:DR4NKR1D3R 提问时间:3/14/2023 更新时间:3/14/2023 访问量:39

问:

我正在会话变量中存储筛选器数据。如何仅在用户重新加载或导航到该页面时清除它们,但在用户使用分页时保留它们?

def boxes(request):        
    user = request.user
    
    log_in_form = CustomUserLogInForm()
    filter_form = FilterForm()

    # THAT MAKES SESSION VARIABLES USABLE ONLY ONCE, THAT IS GREAT UNLESS USER IS USING PAGINATION
    if filter := request.session.get("box_filter"):
        boxes = Box.objects.all().filter(id__in=filter)
        form_city = request.session.get("form_city")
        form_radius = request.session.get("form_radius")
        
        del request.session["box_filter"]
        del request.session["form_city"]
        del request.session["form_radius"]
    else:
        boxes = Box.objects.all()
        form_city = ""
        form_radius = ""
    
    paginator = Paginator(boxes, 5)
    page = request.GET.get("page")
    boxes = paginator.get_page(page)
    
    if boxes.paginator.num_pages < 5:
        page_numbers = range(1, boxes.paginator.num_pages + 1)
    else:
        if boxes.number < 3:
            min = 1
        else:
            min = boxes.number - 2
            
        if boxes.number > boxes.paginator.num_pages - 2:
            max = boxes.paginator.num_pages + 1
        else:
            max = boxes.number + 3

        page_numbers = list(range(min, max))
        page_numbers.append("...")
        page_numbers.append(boxes.paginator.num_pages)

    log_in(request)
    
    if request.method == "POST":
        form = FilterForm(request.POST)

        if form.is_valid():
            cities = pd.read_csv(settings.BASE_DIR / "static/cities_db.csv", sep=";")
            
            city = form.cleaned_data["city"]
            radius = form.cleaned_data["radius"]
            
            request.session["form_city"] = city
            request.session["form_radius"] = radius
            
            city_row = cities.loc[cities["Name"] == city.title()]
            
            city_lat, city_lon = str(city_row["Coordinates"].iloc[0]).split(", ")
            
            tmp_box_filter = []
            
            for box in Box.objects.all():
                if geopy.distance.geodesic((float(city_lat), float(city_lon)), (float(box.lat), float(box.lon))).m <= float(radius):
                    tmp_box_filter.append(box.id)
            
            request.session["box_filter"] = tmp_box_filter
            
            return redirect("boxes")

我找不到任何关于这方面的信息,似乎我应该使用更高级的过滤方法?或者也许只做可选的布尔参数和清除变量?if not parameter

python django 分页 django-filters

评论


答: 暂无答案