V
V
Vic Shostak2018-02-09 11:47:01
Django
Vic Shostak, 2018-02-09 11:47:01

How to add the initial value of cookies on the first visit to the site?

Good time!
Django 2.x. I want to add some parameters to cookies the first time I visit the site (the default site currency value). I do it through middleware like this:

# /app/middlewares.py

class CurrencyMiddleware:
    def __init__(self, get_response):
        self.get_response = get_response

    def __call__(self, request):
        response = self.get_response(request)

        if not request.COOKIES.get('currency'):  # проверяю куку, если нет, то добавляем
            response.set_cookie('currency', 'dollar', max_age=1000)

        return response

I add this middleware to the settings file:
# /app/settings.py

MIDDLEWARE = [
    ...
    'app.middlewares.CurrencyMiddleware',
]

I wrote select in the template, where by clicking on the option, this cookie should change to the value passed to the function (Vue.js + vue-cookies is responsible for this). I use Bulma CSS framework:
// /templates/header.html

<div class="dropdown-menu switcher" id="dropdown-menu" role="menu">
  <div class="dropdown-content">
    {% if request.COOKIES.currency != 'euro' %}
      <a @click="changeCurrency('euro')" class="dropdown-item">
        <span class="icon"><i class="fas fa-euro-sign"></i></span>
        <span>{% trans 'Euro' %}</span>
      </a>
    {% endif %}
    {% if request.COOKIES.currency != 'dollar' %}
      <a @click="changeCurrency('dollar')" class="dropdown-item">
        <span class="icon"><i class="fas fa-dollar-sign"></i></span>
        <span>{% trans 'Dollar' %}</span>
      </a>
    {% endif %}
    {% if request.COOKIES.currency != 'ruble' %}
      <a @click="changeCurrency('ruble')" class="dropdown-item">
        <span class="icon"><i class="fas fa-ruble-sign"></i></span>
        <span>{% trans 'Ruble' %}</span>
      </a>
    {% endif %}
  </div>
</div>

// /static/js/script.js

import Vue from 'vue'
import VueCookies from 'vue-cookies'

Vue.use(VueCookies)

const switcher = new Vue({
  el: '.switcher',
  methods: {
    changeCurrency: function (cur) {
      if (this.$cookies.isKey('currency')) { // проверка на наличие куки
        this.$cookies.remove('currency') // если есть, то удаляем старую куку
      }
      
      this.$cookies.set('currency', cur) // задаём новую куку
      location.reload() // перезагружаем страницу
    }
  }
})

This currency switcher is end-to-end, that is, it is on every page and (in theory) should work the same way everywhere. But, for some unknown reason, on some pages, the switcher does not replace the cookie when clicked, but adds a new one and only changes its value (as if there is no duplicate)! Here:
5a7d6356a72f6052256899.png
These pages are ordinary views, where it is done getaccording to querysetthe model. For example:
class PayOrderView(LoginRequiredMixin, View):
    """
    Pay Order by ID
    """

    template_name = 'orders/orders_payment_choose.html'

    def get(self, request, order_id):
        # Get Orders object
        order = BasicOrder.objects.get(id=order_id)

        if request.user.id == order.user.id:
            return render(request, self.template_name, {'order': order})

        return Http404

Tell me how to be? Maybe I'm doing something wrong?
I will be glad to sensible comments!

Answer the question

In order to leave comments, you need to log in

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question