django开发中处理登录重定向

2021年10月20日 18:31 by wst

django

问题

在网页开发中,有很多需要鉴权的页面:检测用户是否登录,如果未登录则跳转到登录页,登录成功后再跳回原来的界面。

解决方法

1. 在需要鉴权的view中,检测是否登录,如未登录则绑定原始页面地址到next参数中。具体如下:

from django.shortcuts import render

# Create your views here.
from django.shortcuts import render, redirect

# 对应的路径为/rights/
def index(request):
    if not request.session.get('is_login', None):
        return redirect('/authen/login?next={}'.format(request.path))
    return render(request, "rights/nav.html")

2. 在登录页的get请求中,储存目标地址。

if request.method == 'GET':
    request.session['login_from'] = request.GET.get('next')
    return render(request, 'authen/login.html', {"message": "如果登录缓慢请刷新!"})

3. 在登录的post请求中,如果登录成功则跳转回原始地址。

if request.method == "POST":
    username = request.POST.get('username', None)
    password = request.POST.get('password', None)
    print("request:",request.POST)
    message = "所有字段都必须填写!"
    if username and password:  # 确保用户名和密码都不为空
        username = username.strip()
        # 用户名字符合法性验证
        # 密码长度验证
        # 更多的其它验证.....
        try:
            logger.info("start get user...")
            user = User.objects.get(email=username)
            logger.info("have got user.")
            if user.password == password:
                request.session['is_login'] = True
                request.session['user_id'] = user.id
                request.session['user_name'] = user.name
                logger.info("start redirect...")
                return redirect(request.session['login_from'])

登录view的完整代码如下

def login(request):
    logger.info("login start...")
    if request.method == 'GET':
        request.session['login_from'] = request.GET.get('next')
        return render(request, 'authen/login.html', {"message": "如果登录缓慢请刷新!"})

    elif request.method == "POST":
        username = request.POST.get('username', None)
        password = request.POST.get('password', None)
        print("request:",request.POST)
        message = "所有字段都必须填写!"
        if username and password:  # 确保用户名和密码都不为空
            username = username.strip()
            # 用户名字符合法性验证
            # 密码长度验证
            # 更多的其它验证.....
            try:
                logger.info("start get user...")
                user = User.objects.get(email=username)
                logger.info("have got user.")
                if user.password == password:
                    request.session['is_login'] = True
                    request.session['user_id'] = user.id
                    request.session['user_name'] = user.name
                    logger.info("start redirect...")
                    return redirect(request.session['login_from'])
                else:
                    message = "密码不正确!"
            except:
                message = "用户名不存在!"
        logger.info("start view page.")
        return render(request, 'authen/login.html', {"message": message})
    return render(request, 'authen/login.html', {"message": "如果登录缓慢请刷新!"})

 

在此做个记录,希望能帮助到其他人。

如有问题,请在下方留言!


Comments(124) Add Your Comment

Voinfi
order atorvastatin <a href="https://lipiws.top/">order atorvastatin 10mg generic</a> order lipitor 10mg sale
Gcmzij
cipro without prescription - <a href="https://cipropro.top/bactrimos/">bactrim 480mg over the counter</a> order augmentin 625mg
Lwtqgy
order cipro 500mg without prescription - <a href="https://metroagyl.top/clindamycin/">order bactrim 480mg</a> how to buy augmentin
Eshhfn
metronidazole us - <a href="https://metroagyl.top/azithromycin/">purchase zithromax without prescription</a> brand azithromycin 500mg
Vbkupt
buy ciplox 500 mg sale - <a href="https://septrim.top/chloromycetin/">where can i buy chloramphenicol</a> where to buy erythromycin without a prescription
Xtkvpx
valtrex us - <a href="https://gnantiviralp.com/">valtrex 500mg oral</a> order zovirax for sale
Agaiat
ivermectin generic - <a href="https://keflexin.top/cefixime/">cefixime 200mg pills</a> tetracycline 500mg for sale
Hafbdo
buy flagyl pills - <a href="https://metroagyl.top/azithromycin/">order generic zithromax</a> order azithromycin pill
Shrerl
generic acillin <a href="https://ampiacil.top/">buy acillin tablets</a> where to buy amoxil without a prescription
Usrtvk
buy furosemide online - <a href="https://antipathogenc.com/medex/">buy warfarin pill</a> captopril 25mg usa
Bxfozw
order glucophage 1000mg pills - <a href="https://gnantiacidity.com/">glucophage 1000mg cheap</a> buy generic lincomycin
Ohfgop
order zidovudine 300mg - <a href="https://canadiangnp.com/zyloprim/"></a> order allopurinol 100mg online
Oxhszs
buy clozapine for sale - <a href="https://genonlinep.com/accupril/">purchase accupril online cheap</a> buy pepcid pills for sale
Zomrpi
quetiapine 50mg usa - <a href="https://gnkantdepres.com/bupron/">order bupropion without prescription</a> order eskalith online cheap
Sixhsz
clomipramine 25mg uk - <a href="https://antdeponline.com/celexa/">celexa 20mg canada</a> sinequan over the counter
Qgmylb
atarax 25mg brand - <a href="https://antdepls.com/pamelor/">nortriptyline for sale</a> buy generic amitriptyline 10mg
Kpahpg
amoxil pills - <a href="https://atbioxotc.com/cefadroxil/">cefadroxil uk</a> cipro cheap
Vopqaw
amoxiclav over the counter - <a href="https://atbioinfo.com/linezolid/">buy zyvox without prescription</a> ciprofloxacin 500mg cost
Ganukr
order cleocin 150mg - <a href="https://cadbiot.com/oxytetracycline/">where can i buy terramycin</a> chloromycetin brand
Kthnxc
purchase azithromycin sale - <a href="https://gncatbp.com/btetracycline/">tetracycline 250mg usa</a> buy generic ciprofloxacin for sale
Zsdbmu
ivermectin 6mg over the counter - <a href="https://antibpl.com/">ivermectin tablets for sale walmart</a> cefaclor generic
Wtbshi
albuterol 4mg over the counter - <a href="https://antxallergic.com/xsseroflo/">buy seroflo generic</a> buy theo-24 Cr 400 mg online cheap
Xdltgf
buy clarinex 5mg - <a href="https://rxtallerg.com/getaristocort/">aristocort online</a> albuterol cost
Nbchlh
buy depo-medrol tablets - <a href="https://ntallegpl.com/loratadine/">cheap loratadine</a> azelastine 10 ml canada
Ipeouw
glyburide 2.5mg tablet - <a href="https://prodeprpl.com/">buy generic micronase for sale</a> forxiga generic
Ohnsgu
repaglinide 2mg pill - <a href="https://depressinfo.com/jardiance25/">jardiance cost</a> buy jardiance cheap
Kncemx
order metformin 500mg pills - <a href="https://arxdepress.com/acarbose50/">buy precose 50mg</a> precose generic
Qatfav
order terbinafine sale - <a href="https://treatfungusx.com/xgrifulvinvs/">order griseofulvin pill</a> buy cheap generic griseofulvin
Urgxsf
oral rybelsus 14mg - <a href="https://infodeppl.com/glucovance5/">purchase glucovance</a> buy DDAVP online
Ssturc
buy ketoconazole medication - <a href="https://antifungusrp.com/">ketoconazole 200mg sale</a> purchase sporanox
Oggnka
famvir 250mg uk - <a href="https://amvinherpes.com/gnvalaciclovir/">buy generic valaciclovir for sale</a> valaciclovir order online
Humzew
buy lanoxin 250 mg - <a href="https://blpressureok.com/furosemidediuret/">order generic furosemide 100mg</a> buy furosemide 40mg sale
Jqyokg
microzide 25mg cheap - <a href="https://norvapril.com/bisoprolol/">buy bisoprolol 5mg for sale</a> zebeta drug
Nkwvmb
medication to stop heart attack - <a href="https://bloodpresspl.com/olmesartan/">olmesartan 20mg price</a> order nifedipine 10mg generic
Fyejnw
order nitroglycerin pills - <a href="https://nitroproxl.com/valsartan/">buy generic diovan 160mg</a> valsartan drug
Cnnawg
crestor without prescription - <a href="https://antcholesterol.com/pravastatin/">pravachol online suppress</a> caduet pills thump
Rsqiqq
simvastatin due - <a href="https://canescholest.com/fenofibrate/">fenofibrate company</a> atorvastatin sunset
Qwotlb
viagra professional edward - <a href="https://edsildps.com/superkamagra/">kamagra reef</a> levitra oral jelly online vital
Ovoxdm
dapoxetine dust - <a href="https://promedprili.com/zudena/">zudena flee</a> cialis with dapoxetine elsewhere
Xjknbn
cenforce refresh - <a href="https://xcenforcem.com/brandviagrasildenafil/">brand viagra pills matter</a> brand viagra pills read
Bwwcpu
brand cialis master - <a href="https://probrandtad.com/">brand cialis probable</a> penisole propose
Ohrwly
cialis soft tabs dick - <a href="https://supervalip.com/cavertapills/">caverta online blanket</a> viagra oral jelly online difficulty
Yqllld
brand cialis lean - <a href="https://probrandtad.com/forzestpills/">forzest inner</a> penisole flicker
Xdmehd
cialis soft tabs pills stage - <a href="https://supervalip.com/viagraoraljelly/">viagra oral jelly online lord</a> viagra oral jelly online glare
Ngvckq
generic cenforce - <a href="https://xcenforcem.com/zenegrasildenafil/">zenegra side</a> brand viagra us
Ccalxu
acne treatment tight - <a href="https://placnemedx.com/">acne treatment lett</a> acne treatment well
Rlbpay
inhalers for asthma specimen - <a href="https://bsasthmaps.com/">asthma medication response</a> inhalers for asthma fantastic
Dbmoam
uti medication idle - <a href="https://amenahealthp.com/">treatment for uti nod</a> treatment for uti passion
Fwhqwq
prostatitis treatment bore - <a href="https://xprosttreat.com/">prostatitis medications heaven</a> prostatitis medications whom
Uuzwrs
valtrex ridge - <a href="https://gnantiviralp.com/">valtrex pills without</a> valtrex online article
Hubgeu
loratadine medication force - <a href="https://clatadine.top/">claritin pills chocolate</a> claritin pills throat
Pbepcb
priligy visible - <a href="https://prilixgn.top/">priligy scholar</a> dapoxetine tomb
Wlywbz
claritin pills wood - <a href="https://clatadine.top/">loratadine medication staff</a> loratadine medication area
Hfuiqi
promethazine mood - <a href="https://prohnrg.com/">promethazine nephew</a> promethazine thirty
Ekmtsc
ascorbic acid seat - <a href="https://ascxacid.com/">ascorbic acid instruction</a> ascorbic acid gloomy
Ngvwxb
biaxin clatter - <a href="https://gastropls.com/">biaxin credit</a> cytotec wolf
Ymujnv
fludrocortisone wizard - <a href="https://gastroplusp.com/omepprilosec/">prilosec pills even</a> lansoprazole pills descend
Gbizoz
buy bisacodyl paypal - <a href="https://gastroinfop.com/loperamide/">order generic loperamide</a> buy generic liv52 for sale
Xkwlvw
order aciphex 10mg sale - <a href="https://gastrointesl.com/metoclopramide/">metoclopramide 20mg cost</a> buy domperidone tablets
Vhqhri
bactrim 480mg pills - <a href="https://ketiracet.com/">oral levetiracetam 1000mg</a> tobramycin 10mg drops
Fslydb
zovirax buy online - <a href="https://cerazestrel.com/">brand cerazette 0.075 mg</a> dydrogesterone 10mg sale
Ombuui
dapagliflozin 10mg pill - <a href="https://precarbos.com/">buy precose 25mg generic</a> order acarbose 25mg for sale
Qmorue
griseofulvin price - <a href="https://fulviseoful.com/">fulvicin online order</a> buy gemfibrozil 300 mg online
Spfmsx
enalapril pills - <a href="https://vasolapril.com/">cost vasotec 5mg</a> order zovirax sale
Eewyeo
buy dimenhydrinate 50mg generic - <a href="https://bisacolax.com/">buy dimenhydrinate sale</a> actonel generic
Ocsona
purchase monograph generic - <a href="https://etodograph.com/">buy etodolac online</a> cilostazol 100 mg cheap
Nyscgy
order feldene 20mg online - <a href="https://rivastilons.com/">generic rivastigmine</a> buy cheap exelon
Tltenq
nootropil 800mg without prescription - <a href="https://nootquin.com/">piracetam 800mg cost</a> buy sinemet 20mg
Robtyw
buy hydrea tablets - <a href="https://hydroydrinfo.com/pentoxifylline/">trental online order</a> buy robaxin paypal
Aqxxuz
divalproex 250mg for sale - <a href="https://adepamox.com/topiramate/">buy generic topamax for sale</a> buy topamax pill
Lilnow
cost disopyramide phosphate - <a href="https://anorpica.com/">purchase norpace online cheap</a> order generic chlorpromazine
Ltdnng
cyclophosphamide tablets - <a href="https://cycloxalp.com/antivert/">buy generic antivert 25 mg</a> trimetazidine ca
Mdcduo
spironolactone online - <a href="https://aldantinep.com/phenytoin/">dilantin 100mg cheap</a> buy generic naltrexone 50 mg
Obdhov
where can i buy cyclobenzaprine - <a href="https://abflequine.com/olanzapine/">olanzapine 10mg ca</a> vasotec pills
Qasang
buy zofran without a prescription - <a href="https://azofarininfo.com/">buy zofran pill</a> brand requip
Nmkhwq
ascorbic acid 500 mg generic - <a href="https://mdacidinfo.com/isosorbidedinitrate/">isosorbide dinitrate medication</a> brand compro
Mzxugl
buy cheap durex gel - <a href="https://xalaplinfo.com/durexcondoms/">how to order durex condoms</a> cheap zovirax
Sxszoy
minoxidil where to buy - <a href="https://hairlossmedinfo.com/">buy minoxidil generic</a> oral propecia
Cfgnxb
leflunomide price - <a href="https://infohealthybones.com/calciumcarbonate/">oral calcium carbonate</a> purchase cartidin sale
Vagkwt
cheap atenolol 100mg - <a href="https://heartmedinfox.com/carvedilol/">coreg oral</a> carvedilol 6.25mg for sale
Ccubfe
buy calan 120mg pill - <a href="https://infoheartdisea.com/valsartan/">order diovan 80mg pills</a> tenoretic pill
Gxuvqc
oral atorvastatin - <a href="https://infoxheartmed.com/enalapril/">cost vasotec 10mg</a> order bystolic 20mg generic
Puqqxg
buy lasuna for sale - <a href="https://infoherbalmz.com/diarex/">cheap diarex sale</a> himcolin usa
Edyuqq
gasex without prescription - <a href="https://herbalinfomez.com/">buy gasex paypal</a> diabecon pills
Dntqit
noroxin tablets - <a href="https://gmenshth.com/confido/">buy confido for sale</a> buy confido online
Jdjonm
buy speman online cheap - <a href="https://spmensht.com/himplasia/">cheap himplasia generic</a> buy finasteride without a prescription
Gzhpid
how to buy finax - <a href="https://finmenura.com/doxazosin/">order cardura sale</a> buy generic uroxatral for sale
Fazhzr
terazosin online buy - <a href="https://hymenmax.com/dutasteride/">buy dutasteride generic</a> buy priligy 90mg online cheap
Qckral
trileptal for sale - <a href="https://trileoxine.com/levothyroxine/">buy levoxyl without prescription</a> order synthroid 100mcg pills
Exlwxy
imusporin medication - <a href="https://asimusxate.com/methotrexate/">methotrexate online buy</a> colcrys ca
Uvfana
duphalac order - <a href="https://duphalinfo.com/">buy duphalac bottles</a> buy betahistine 16mg online cheap
Udeswy
besivance tubes - <a href="https://besifxcist.com/carbocysteine/">carbocysteine tablet</a> sildamax drug
Savakm
cheap deflazacort sale - <a href="https://lazacort.com/brimonidine/">purchase brimonidine for sale</a> alphagan where to buy
Sbjach
order gabapentin 600mg pills - <a href="https://aneutrin.com/sulfasalazine/">buy azulfidine 500 mg for sale</a> cheap azulfidine 500 mg
Mnsifm
buy probenecid medication - <a href="https://bendoltol.com/carbamazepine/">buy carbamazepine 200mg sale</a> cost tegretol 400mg
Wxhgkh
how to buy mebeverine - <a href="https://coloxia.com/">buy colospa without a prescription</a> cilostazol order
Uwpqbx
order diclofenac sale - <a href="https://dicloltarin.com/">buy diclofenac generic</a> order aspirin 75mg pills
Hkcxkf
buy rumalaya medication - <a href="https://rumaxtol.com/amitriptyline/">order elavil 50mg</a> amitriptyline us
Kjgqpk
mestinon 60 mg price - <a href="https://mestonsx.com/asumatriptan/">order sumatriptan 25mg pill</a> imuran 50mg brand
Gqpzqt
diclofenac cheap - <a href="https://vovetosa.com/animodipine/">order nimodipine pills</a> nimotop medication
Nxpuha
order baclofen 25mg without prescription - <a href="https://baclion.com/nspiroxicam/">buy piroxicam for sale</a> purchase feldene sale
Mbrtgw
mobic drug - <a href="https://meloxiptan.com/">purchase meloxicam online cheap</a> cost ketorolac
Zdwrgf
purchase artane for sale - <a href="https://voltapll.com/diclofenacgel/">where can i purchase diclofenac gel</a> where can i purchase diclofenac gel
Tcxtmp
buy omnicef pills - <a href="https://omnixcin.com/aminocycline/"></a> buy cleocin online cheap
Hplalg
isotretinoin 20mg us - <a href="https://aisotane.com/asavlosulfon/">order dapsone 100 mg without prescription</a> brand deltasone 10mg
Yxsjbi
deltasone 5mg us - <a href="https://apreplson.com/">generic deltasone 20mg</a> permethrin buy online
Onyotp
permethrin price - <a href="https://actizacs.com/tretinoin/">buy generic retin online</a> buy retin no prescription
Zwfvbv
cheap betamethasone 20 gm - <a href="https://betnoson.com/">betamethasone 20gm sale</a> buy monobenzone sale
Zckazg
oral flagyl 200mg - <a href="https://ametronles.com/">how to buy flagyl</a> buy generic cenforce 100mg
Rmmhnh
buy amoxiclav online - <a href="https://alevonted.com/">buy levothyroxine online</a> synthroid over the counter
Cqnhuq
purchase cleocin for sale - <a href="https://indometnp.com/">order indomethacin online</a> buy indocin 50mg generic
Trxpzu
cozaar 50mg ca - <a href="https://cozartan.com/">cozaar over the counter</a> buy keflex 125mg sale
Dgxqsv
order crotamiton generic - <a href="https://aeuracream.com/caczone/">aczone uk</a> purchase aczone generic
Aqxgya
provigil where to buy - <a href="https://sleepagil.com/phenergan/">promethazine online buy</a> meloset 3mg generic
Lxfrpp
order generic zyban - <a href="https://bupropsl.com/">buy zyban for sale</a> purchase shuddha guggulu for sale
Oppovu
order capecitabine 500 mg online cheap - <a href="https://xelocap.com/mefenamicacid/">buy generic ponstel for sale</a> order danocrine 100 mg online cheap
Ooijog
progesterone 100mg oral - <a href="https://apromid.com/clomiphene/">buy clomid 100mg online cheap</a> purchase fertomid without prescription
Dluzbo
buy fosamax without prescription - <a href="https://pilaxmax.com/tamoxifen/">order nolvadex sale</a> medroxyprogesterone 10mg pill
Slfcbd
norethindrone 5mg generic - <a href="https://norethgep.com/">buy norethindrone 5 mg online cheap</a> cheap yasmin
Chrtnf
estradiol pills - <a href="https://festrolp.com/ginette-35/">buy ginette 35 pills</a> buy arimidex without a prescription
Uxobxs
order cabergoline generic - <a href="https://adostilin.com/alesse/">order alesse</a> buy alesse without a prescription
Drakix
バイアグラ - 50mg/100mg - <a href="https://jpedpharm.com/">シルデナフィル の購入</a> タダラフィル 飲み方
Ltavwy
プレドニン通販で買えますか - <a href="https://jpaonlinep.com/jamoxicillin/">アモキシルは薬局で買える?</a> アジスロマイシン 薬局で買える
Xdelfi
プレドニン通販 安全 - <a href="https://jpanfarap.com/">プレドニン 副作用</a> イソトレチノイン どこで買える