Search code examples
djangodjango-viewsdjango-formsdjango-csrf

CSRF verification failed in production sever Django 4.0


i have a form page which work perfectly in locally but after uploading it to railway it start showing this errorenter image description here

I also checked locally it worked perfectly fine and load the page when click forms submit button but in production it throws above mentioned error

here is my form template

<form action="{% url 'personal_readme:preview' %}" method="POST" enctype="multipart/form-data">
    **{% csrf_token %}**
    <div class="name_tag">
      <h2><iconify-icon icon="bi:person-circle"></iconify-icon> ( Title )</h2>
      {{ form.name.label_tag }} <span>{{ form.name }}</span>
  </div>
    <hr>
    <div class="support_tag">
    <h2><iconify-icon icon="fa-solid:handshake"></iconify-icon> ( Support )</h2>
    <iconify-icon icon="line-md:buy-me-a-coffee-filled"></iconify-icon> {{ form.buy_me_coffee.label_tag}} {{ form.buy_me_coffee}}
    <iconify-icon icon="simple-icons:patreon"></iconify-icon> {{ form.patreon.label_tag}} {{ form.patreon}}
  </div>
    <hr>
    <div class="genrate text-center">
      <button type="submit" class="gen_btn"><iconify-icon icon="bxs:file-md"></iconify-icon> Genrate File</button></div>
  </form>

my views.py for

def home(request):
    if request.method == 'POST':
        form = Personal_Readme_form(request.POST)
        if form.is_valid():
            form.save()
            return redirect('personal_readme:preview')
    else:
        form = Personal_Readme_form()
    return render(request, 'home.html', {'form': form})

any suggestion might be helpful


Solution

  • for django 4 first install

    pip install django-cors-headers
    

    add 'corsheaders' in installed apps

    INSTALLED_APPS = [
    'corsheaders',
    ]
    

    add in middleware too

    MIDDLEWARE = [
    'corsheaders.middleware.CorsMiddleware',
    ]
    

    then set csrf trusted origin in your settings.py

    CSRF_TRUSTED_ORIGINS = ['https://domain.name']
    

    and for including all the subdomain

    CSRF_TRUSTED_ORIGINS = ['https://*.domain.name']