Answer the question
In order to leave comments, you need to log in
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
# /app/settings.py
MIDDLEWARE = [
...
'app.middlewares.CurrencyMiddleware',
]
// /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() // перезагружаем страницу
}
}
})
get
according to queryset
the 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
Answer the question
In order to leave comments, you need to log in
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question