Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
169 views
in Technique[技术] by (71.8m points)

Django: form CSRF verification failed

This is my first Django project, however, I have a problem submitting the form. I'm getting 'CSRF verification failed'. It's a very simple form just 2 fields(frontpage) and on submit to display the same page.

views.py

def newsletter(request):
    if request.method == 'POST':
        name = request.POST('name') 
        email = request.POST('email')

        newsletter = Newsletter(name = name, email = email)
        newsletter.save()
        return HttpResponseRedirect('')

models.py

class Newsletter(models.Model):
    name = models.CharField(max_length = 200)
    email = models.CharField(max_length=100)
    publish_date = models.DateTimeField(default = datetime.now, blank = True)
    
    def __str__(self):
        return self.name

admin.py

class NewsletterAdmin(admin.ModelAdmin):
    list_display = ('name','publish_date')
admin.site.register(Newsletter, NewsletterAdmin)

urls.py

urlpatterns = [
    path('admin/', admin.site.urls),
    path('', home_view, name = 'home'),
    path('events/', events, name = 'events'),
    path('news/', news, name = 'mainnews'),
    path('about/', about, name = 'about'),
    path('', newsletter),
] + static(settings.MEDIA_URL, document_root = settings.MEDIA_ROOT)

html>

<div>
    <form method = 'post'>
        {% csrf_token %} {{ form.as_p }} 
        <input name = 'name' type = 'text' value = "{{ newsletter.name }}">
        <input name = 'email' type = 'email' value = "{{ newsletter.email }}">
        <button type = 'submit' name = 'save'>Send</button>
    </form>
</div>
question from:https://stackoverflow.com/questions/65848693/django-form-csrf-verification-failed

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

Write your form like this:

<form method="post">
    {% csrf_token %}
    {{ form.as_p }}
    <button type="submit" value="Submit"></button>
</form>

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...