这个问题已经被较早回答,但是那些解决方案对我不起作用。 我的设置将Django 1.9和MongoDB作为后端。我有自定义的用户模型。
我有一个要上传文件的网页。该流程运行良好。现在,我必须对该页面登录名进行保护。
当我尝试访问https://localhost/upload
时,它会将我重定向到https://localhost/login_page?next=/upload
我提供的凭据正确,我在django日志中看到它将我重定向到/upload
,但再次将我引回到登录页面。
models.py
class Uploadedfiles(models.Model):
docfile = models.FileField(upload_to='uploads')
views.py
from django.contrib.auth.decorators import login_required
import os
@login_required()
def uploadfiles(request):
if request.method == 'POST':
form = UploadForm(request.POST, request.FILES)
if form.is_valid():
newdoc = Uploadedfiles(docfile=request.FILES['docfile'])
newdoc.save()
return HttpResponseRedirect(reverse('upload'))
else:
form = UploadForm() # A empty, unbound form
ufiles = Uploadedfiles.objects.all()
return render(
request,
'upload.html',
{'ufiles': ufiles, 'form': form}
login_page.html
<div>
{% if next %}
<form action="/login/?next={{ request.path }}" method="post" >
{%else%}
<form action="/login_page/" method="post" >
{% endif %}
{% csrf_token %}
<p><b>Login</b></p>
<input type="email" name="email" placeholder="Email" required="">
<input type="password" name="password" placeholder="Password" id="new_password">
<span id="message"></span>
<button type="submit" name="Login"><b>Login</b></button>
</form>
</div>
登录视图
def LoginPage(request,*args, **kwargs):
msg = "Please provide details"
next = request.POST.get('next', request.GET.get('next', ''))
if 'email' in request.POST and 'password' in request.POST:
password=request.POST['password']
email=request.POST['email']
payload = { "password" : password, "email":email}
response = requests.post('https://localhost/login',data=payload)
code=response.status_code
if '200'==code or 200==code:
msg="Your are login successfully"
print(msg)
return HttpResponseRedirect("/upload")
else:
msg=response[msg]
response = render(request,'login_page.html',{'msg':msg})
else:
response = render(request,'login_page.html',{})
return response
urls.py
urlpatterns = [
url(r'^login$', Login.as_view(), name=r"login"), #This is REST API
url(r'^login_page/$', LoginPage, name=r"loginpage")
]
请有人帮助我。
编辑1 :添加自定义用户模型
from mongoengine import fields, Document
class User(Document):
id = fields.IntField(primary_key=True)
username = fields.StringField(required=True)
email = fields.EmailField()
name = fields.StringField()
password = fields.StringField(required=True)
答案 0 :(得分:0)
A simple solution would be to use LOGIN_REDIRECT_URL
LOGIN_REDIRECT_URL = '/upload'