python - Getting error 403 (CSRF token missing or incorrect) -


i'm need email form , i'm trying this:

views.py

def send_email(request):     if request.method != 'post':         form = emailform()         return render_to_response('mail_form.html', {'email_form': form})      form = emailform(request.post, request.files)        if form.is_valid():         subject = form.cleaned_data['subject']         message = form.cleaned_data['message']         email = form.cleaned_data['email']         attach = request.files['attach']         try:             mail = emailmessage(subject, message, settings.email_host_user, [email])             mail.attach(attach.name, attach.read(), attach.content_type)             mail.send()             return render(request, 'mail_form.html', {'message': 'sent email %s'%email})         except:             return render(request, 'mail_form.html', {'message': 'either attachment  big or corrupt'})         return render(request, 'mail_form.html', {'message': 'unable send email. please try again later'}) 

forms.py

class emailform(forms.form):     email = forms.emailfield()     subject = forms.charfield(max_length=100)     attach = forms.field(widget=forms.fileinput)     message = forms.charfield(widget = forms.textarea) 

mail_form.html

... {{message}} <form method="post" action="">     {% csrf_token %}     {{ email_form.as_p }}     <input type ="submit"  name = "send" value = "send"/> </form> ... 

but error 403. tried different solutions web, nothing helped. i'm doing wrong? i'm understand wrong csrf in views.py, don't understand problem concretely.

your problem render_to_reponse. doesn't have context instance can add it, render handles why not instead. can restructure view bit cleaner.

here's 1 example.

def send_email(request):      if request.method == 'post':         form = emailform(request.post, request.files)            if form.is_valid():             subject = form.cleaned_data['subject']             message = form.cleaned_data['message']             email = form.cleaned_data['email']             attach = request.files['attach']             try:                 mail = emailmessage(subject, message, settings.email_host_user, [email])                 mail.attach(attach.name, attach.read(), attach.content_type)                 mail.send()                 messages.succes(request, 'sent email %s' % email)             except:                 messages.error(request, 'either attachment  big or corrupt')     else:         form = emailform()         messages.info(request, "send email!")     return render(request, 'mail_form.html', {'email_form': form}) 

then can use {% if messages %} in template display messages user / iterate on them , display.

messages here django.contrib you'd need from django.contrib import messages


Comments

Popular posts from this blog

Django REST Framework perform_create: You cannot call `.save()` after accessing `serializer.data` -

Why does Go error when trying to marshal this JSON? -