0

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

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 Answers1

0

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)

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
Mehran
  • 1,064
  • 5
  • 21