'CSRF verification failed. Request aborted [New] 2021

I am completely tired with the csrf issue. I have created a sign in form and register form. I am able to login and logout, even register a user. The main problem I am facing is the refresh-after-signin. After signing in, if I refresh the page it simply gives a csrf verification failed error. I have literally searched for it since past two days with no solution, all the answers are almost 4-5 years older, which are not helping.

This is the views.py signin function.

def signin(request):
  if request.method=="POST":
    username = request.POST.get('username')
    password = request.POST.get('password')

    user = authenticate(username=username,password=password)

    if user is not None:
      login(request,user)
      messages.success(request,"Logged in Successfully!")
      return render(request,'authtest/index.html')
    else:
      messages.error(request,"Bad Credentials")
      return redirect('index')

  return render(request,'authtest/signin.html')

This is the HTML form that is returning POST request

<form action="{% url 'signin' %}" method="POST">
  <!-- I have no idea what this thing does -->
  {% csrf_token %} 
  <!-- I have no idea what this thing does end -->
  <input type="hidden" id="csrf_token" value='{"csrfmiddlewaretoken": "{{ csrf_token }}"}'>

  <label for="username">UserName</label>
  <input type="text" name="username" id="username" required>
  
  <label for="password">Password</label>
  <input type="password" name="password" id="password" required>

  <button type="submit">SignIn</button>
</form>

Refreshing Error



Solution 1:[1]

Due to some security issues to keep each user's session safe, it is not possible to authenticate and render the url in the same view functions. Therefore, you must perform the rendering operation in another URL after redirecting something like this

def signin(request): 
   if request.method=="POST":
       ........
       if user is not None:
            ..........
            return redirect ('dashboard')\

and that dashboard func is like this

def dashboard(request): 
    .......
    return redirect ('dashboard')

Solution 2:[2]

A very simple check for whether all the elements in a list are the same is

len(set(l)) == 1

So if you need to check if each element of a list contains idenitcal elements:

result = [len(set(s)) == 1 for s in l[0]]

This returns a list of booleans, which you can then transform into strings or whatever you want. For example:

for b in result:
    print(f'Both item1 & item2 are {"" if b else "not "} the same')

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1
Solution 2 Mad Physicist