如何使我的request.method == post工作?我的代码转到其他代码,然后退出到主屏幕。我无法获取用户信息

时间:2018-09-11 17:37:11

标签: python django

  

打开创建页面时,即使我没有填写任何信息,也不会给我错误,所有字段都是必填字段,而是每次它注销我并返回首页时。我认为我的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')

1 个答案:

答案 0 :(得分:0)

您是否以用户身份登录?您需要具有一个单独的查看功能,该功能将对您的用户进行身份验证并保持用户登录到会话中。建议这样做,因为我没有看到任何登录视图功能或有关如何登录应用程序的参考。

编辑:如何使用django登录(来自文档)

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