且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

实现一个计数器,用django计数请求

更新时间:2023-12-02 16:27:40

这可能有点混乱,但是您应该从会话中获得基本概念,而不是get方法
model / .py吸引朋友的模型

This might be a little messed up but you should get the basic concept you get it from the session not the get methods model/.py the model that tracts your friend

friend = models.ForeignKey("self", related_name="referral", null=True, blank=True) 

view.py这是您计数的朋友

view.py this is how many friends you have counted

cool_obj = cool.objects.get(ref_id=ref_id)
obj = cool.objects.filter(friend=cool_obj)
count = cool_obj.referral.all().count()

这是如何通过中间件获取内容的方法

this how you get your stuff through the middleware

def home(request):
try:
    cool_id = request.session['cool_id_ref']
    obj = cool.objects.get(id=cool_id)
except:
    obj = None 
form = CoolJoin(request.POST or None)
if form.is_valid():
    new_cool = form.save(commit=False)
    email = form.cleaned_data['email']
    new_cools, created = cool.objects.get_or_create(email=email)
    if created:
        new_cools.ref_id = get_ref_id()
        if not obj == None:
            new_cools.friend = obj
        new_cools.ip_adress = get_ip(request)
        new_cools.save()

    return HttpResponseRedirect("/%s" %(new_cools.ref_id))
context = {"form": form}
template = "home.html"
return render(request, template, context)

中间件/

class ReferMiddleware():
def process_request(self, request):
        ref_id = request.GET.get("ref")
        try:
            obj = cool.objects.get(ref_id = ref_id)
        except:
            obj = None   
        if obj:
            request.session['cool_id_ref'] = obj.id