开启代码之旅 Launch With Code
1364 浏览 6 years, 1 month
12 Use Custom Django Middleware to Track Shares
版权声明: 转载请注明出处 http://www.codingsoho.com/添加middleware处理分享页
- 添加middleware类
- 从middleware中获取reference值 (url中的内容),并将这个值存入session
- 在view中将session中的值拿到,并根据这个值get到join
https://docs.djangoproject.com/en/1.10/topics/http/middleware/
MIDDLEWARE_CLASSES = (
'django.middleware.common.CommonMiddleware',
'django.contrib.sessions.middleware.SessionMiddleware',
'django.middleware.csrf.CsrfViewMiddleware',
'django.contrib.auth.middleware.AuthenticationMiddleware',
'django.contrib.messages.middleware.MessageMiddleware',
# Uncomment the next line for simple clickjacking protection:
# 'django.middleware.clickjacking.XFrameOptionsMiddleware',
'lwc.middleware.ReferMiddleware',
)
创建lwc/middleware.py
from joins.models import Join
class ReferMiddleware():
def process_request(self, request):
ref_id = request.GET.get("ref")
try:
obj = Join.objects.get(ref_id = ref_id)
except:
obj = None
if obj:
request.session['join_id_ref'] = obj.id
def home(request):
try:
join_id = request.session['join_id_ref']
obj = Join.objects.get(id=join_id)
except:
obj = None
form = JoinForm(request.POST or None)
if form.is_valid():
new_join = form.save(commit = False)
email = form.cleaned_data['email']
new_join_old, created = Join.objects.get_or_create(email = email)
if created:
new_join_old.ref_id = get_ref_id()
new_join_old.ip_address = get_ip(request)
new_join_old.save()
return HttpResponseRedirect("/%s" %(new_join_old.ref_id))
context = {"form":form}
template = "home.html"
return render(request, template, context)