Search code examples
pythondjangodjango-modelsdjango-formscsrf-token

form post getting 403 forbidden error while using django


<form  action="{% url 'create'%}" method="POST" >
{% csrf_token %}

this in my template file.

def create(request):
    return render(request, "auctions/create.html")
    if request.method == "POST":
        title = request.GET["title"]
        des = request.GET["description"]
        bid = request.GET["startingBid"]
        imageurl= request.GET[ "imageUrl"]
        category = request.GET["category"]
        image = request.GET["image"]
        listing= Auctionlisting(request,title=title,description=des,startingBid=bid,imageUrl=imageurl,category=category)
        return render(request, "auctions/index.html",{
        "listing":Auctionlisting.objects.all()
        })

and this is in my views.py. still after using csrf token i am getting 403 forbidden error. please some guide me. Also these title, description and all are my inputs...


Solution

  • Just re-arrange your code like this:

    def create(request):
        if request.method == "POST":
            title = request.GET["title"]
            des = request.GET["description"]
            bid = request.GET["startingBid"]
            imageurl= request.GET[ "imageUrl"]
            category = request.GET["category"]
            image = request.GET["image"]
            listing= Auctionlisting(request,title=title,description=des,startingBid=bid,imageUrl=imageurl,category=category)
            listing.save() # save before getting them from database
            return render(request, "auctions/index.html",{
            "listing":Auctionlisting.objects.all()
            })
        else:
            return render(request, "auctions/create.html")