我正在创建一个钱包应用程序,所以如果有人去http://127.0.0.1:8000/add_money/添加资金并且他们没有登录,他们将被重定向到登录页面,然后用户登录后应将其重定向回add_money但它被重定向到他们的个人资料。
//添加金钱视图
def add_money(request):
if not request.user.is_authenticated():
return render(request, 'registration/login.html', {"next": '/add_money/'})
else:
if request.POST:
username = request.user.username
add_amount = request.POST['amount']
wallet = Wallet.objects.filter(username=username).update(add_money(add_amount))
now = datetime.now()
trans = Transaction(from_name=username, wallet_id=wallet.id, date=now, amount=add_amount)
trans.save()
return render(request, 'user_profile.html', {'user': request.user})
return render(request, 'registration/login.html', {"next": '/add_money/'})
//登录视图
def user_login(request):
if request.POST:
username = request.POST['username']
password = request.POST['password']
user = authenticate(username=username, password=password)
if user is not None:
if user.is_active:
login(request, user)
if request.POST['next']:
return render(request, '/add_money/')
return render(request, 'user_profile.html',{'user': user, 'wallet': user.userprofile.wallet_id})
else:
return render(request, 'registration/login.html', {'error': 'User is not active'})
else:
return render(request, 'registration/login.html', {'error': 'User does not exist'})
else:
return render(request,'registration/login.html')
//登录模板
{% if next %}
<form action="/login/?next={{next}}" method="post">
<input type="hidden" name="next" value={{ next }}>
{%else%}
<form action="/login/" method="post" >
{% endif %}
USERNAME <input type="text" name="username">
PASSWORD <input type="password" name="password">
<input type="submit">
<input type="hidden" name="next">
{% csrf_token %}
</form>
// add_money模板
<form action="user_profile.html" method="post">
Amount:<input type="number" name="amount">
<input type="submit" value="Submit">
<button type="button" name="cancel">Cancel</button>
</form>
答案 0 :(得分:1)
我不确定它是如何设置到帐户页面的,因为您将render
标记混合为render
和redirect
。
return render(request, '/add_money/')
您应该将重定向响应返回到下一个网址
return HttpResponseRedirect(request.GET['next'])
此外,您已将next
传递给登录模板,而不是网址
if not request.user.is_authenticated():
return render(request, 'registration/login.html', {"next": '/add_money/'})
你应该在这里重定向到登录页面,下一步作为get参数
return HttpResponseRedirect('/login/?next={}'.format('/add_money/')
您还应该考虑使用提供的网址反转方法而不是硬编码网址
您还应该删除模板中的整个if next
,然后让登录操作成为页面的默认设置
{% if next %}
<form action="/login/?next={{next}}" method="post">
<input type="hidden" name="next" value={{ next }}>
{%else%}
<form action="/login/" method="post" >
{% endif %}
应该是
<form method="post" >