[英]How to make my request.method==post work? my code goes to else code and logs me out to home screen.I am unable to take users information
when create page opens up, even if i don't fill any information ,it does'nt gives me the error all fields are required , rather every time it logs me out and goes to home page. 当创建页面打开时,即使我没有填写任何信息,也不会给我错误,所有字段都是必填字段,而是每次它注销我并返回首页时。 I think my if(request.method==post) block is not processed at all,rather it logs me out , and takes me back to my signup/home page 我认为我的if(request.method == post)块根本没有被处理,而是注销了我,并带我回到我的注册/主页
from django.shortcuts import render,redirect
from django.contrib.auth.decorators import login_required
from .models import Product
from django.utils import timezone
def home(request):
return render(request,'products/home.html')
@login_required
def create(request):
if request.method == 'POST':
if request.POST['title'] and request.POST['body'] and request.POST['url'] and request.FILES['icon'] and request.FILES['image']:
product = Product()
product.title=request.POST['title']
product.body=request.POST['body']
if request.POST['url'].startswith('http://') or request.POST['url'].startswith('https://'):
product.url=request.POST['url']
else:
product.url= 'http://'+ request.POST['url']
product.icon=request.FILES['icon']
product.image=request.FILES['image']
product.pub_date= timezone.datetime.now()
product.hunter=request.user
product.save()
return redirect('create')
else:
return render(request,'products/create.html',{'error':'All fields are required'})
else:
return render(request,'products/create.html')
Did you log in with your user? 您是否以用户身份登录? You'd need to do have a separate view function which will authenticate your user and keep the user logged in to a session. 您需要具有一个单独的查看功能,该功能将对您的用户进行身份验证并保持用户登录到会话中。 Suggesting this since I don't see any login view function or any reference on how you're logging in your app. 建议这样做,因为我看不到任何登录视图功能或有关如何登录应用程序的参考。
EDIT: How to login using django (from the docs) 编辑:如何使用Django登录(来自docs)
from django.contrib.auth import authenticate, login
def my_view(request):
username = request.POST['username']
password = request.POST['password']
user = authenticate(request, username=username, password=password)
if user is not None:
login(request, user)
else:
# send a message to show user is not logged in
pass
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.