django 1.10 csrf_token not creating hidden input field - django

I have a form, but Django is not creating a hidden input like -
<input type="hidden" name="csrfmiddlewaretoken" value="80NGejzAPl2aCbEEuyLqIT3ppMTJLilY">
If trying send a form I have 403 mistake, CSRF token missing or incorrect.
This is my code:
html
<form class="get-info" action="{% url 'callback:send_callback' %}" method="post">{% csrf_token %} ... </form>
middleware
'django.middleware.csrf.CsrfViewMiddleware',
views.py
from django.core.mail import BadHeaderError, send_mail
from django.http import HttpResponse, HttpResponseRedirect, request
from django.shortcuts import render, render_to_response
from django.template import RequestContext
from django.template.context_processors import csrf
from django.contrib import messages
def callback(request):
phone = request.POST.get('phone', None)
lastpath = request.POST.get('lastpath', None)
if validatePhone(phone):
if sendMail(phone):
messages.success(request, 'Мы скоро перезвоним Вам')
return HttpResponseRedirect(lastpath)
else:
messages.error(request, 'Ошибка в отправке запроса. Попробуйте позже.')
return HttpResponseRedirect(lastpath)
else:
messages.error(request, "Неверный формат номера телефона. Телефон нужно вводить в формате +99999999999")
args = {}
zzz = lastpath.render(RequestContext(request, args))
return HttpResponse(zzz)
Callback url -
urlpatterns = [
url(r'^callback/', views.callback, name='send_callback'),
]
Form rendering on the main page:
<form class="get-info" action="/callback/callback/" method="post">
<input type="hidden" name="_subject" value="karpaty-perezvonite-mne">
<input id="callback" name="phone" type="tel" class="form-control" placeholder="+ 380 ___-__-__">
<input type="text" class="form-control" placeholder="" name="lastpath" value="/" style="display: none">
<button type="submit" class="btn btn-default" value="Send">Отправить</button>
</form>
I'm trying submit form to the main page - "/" and now have such mistake
UserWarning: A {% csrf_token %} was used in a template, but the context did not provide the value.
This is usually caused by not using RequestContext.
How can I fix it?

Related

How to use Django-simple-captcha on the admin login page?

I would like to add captcha on my django login form using Django Simple Captcha found here: http://code.google.com/p/django-simple-captcha/
This works great if you create a new form but I'm using the django.contrib.auth.forms the one that comes with django. Any idea how I might be able to implement captcha with the existing django auth views or any ways? Thank you!
Please do not suggest using Google reCaptcha.
My urls.py
from django.contrib.auth import views as auth_views
urlpatterns = [
path('login/', auth_views.LoginView.as_view(template_name='login.html'), name='login')
,...
]
My login.html
<form class="fadeIn second" method="post">
{% csrf_token %}
{{ form.as_p }}
<button type="submit" class="btn btn-primary"> Login </button>
</form>
My Forms.py
from captcha.fields import CaptchaField
class MyFormCaptcha(forms.Form):
captcha = CaptchaField()
This video and this GitHub project solved my problem. You can customize the project code according to your needs. For me it is as follows.
My urls.py
urlpatterns = [
...
path('captcha/',include('captcha.urls')),
path('submit',submit,name='submit')
]
My forms.py
from captcha.fields import CaptchaField
class MyForm(forms.Form):
captcha=CaptchaField()
My login.html
<form action="/submit" method="post">
{% csrf_token %}
<div>
<label for="fullname">Full Name</label>
<input type="text" id="fullname" name="fullname">
</div>
<br>
<div>
<label for="email">Email</label>
<input type="text" id="email" name="email">
</div> <br>
{{form.captcha}}
<button type="submit">Submit</button>
</form>
My views.py How to log a user in?
from django.contrib.auth import authenticate, login
def test(request):
form=MyForm()
return render(request,'captcha/home.html',{'form':form})
def submit(request):
if request.method == 'POST':
form=MyForm(request.POST)
if form.is_valid():
name=request.POST['fullname']
email=request.POST['email']
print('success')
print(name)
print(email)
user = authenticate(request,username=username,password=password)
if user is not None:
login(request, user)
return redirect('/homepage') # Redirect to a success page.
else:
# Return an 'invalid login' error message.
print('fail')
messages.success( request,f 'login failed! username or passwoed is wrong!'
return redirect('login')

Form.is_valid() returns False?

Why am I asking question despite already been asked? I read many question posted on Stack Overflow but I am not able to fix the code as I am new to Python Language.
What am I trying to do: Simply trying to take the input from user and return an HttpResponse (if successfully). Otherwise, an error HttpResponse message to return.
Problem : The MyForm.is_valid() in Forms.py is always returning False! I tried many solutions posted on previous questions and also read the documentary thrice but not able to understand, what am I doing wrong?
Views.Py
from django.http import HttpResponse
from .forms import PostForm
.
.
. <<code here>>
def register(request):
if request.method == 'POST':
Myform = PostForm(request.POST)
if Myform.is_valid():
return HttpResponse("<h1>Is_Valid is TRUE.</h1>")
else:
return HttpResponse("<h1>Is_Valid is False.</h1>")
else:
return HttpResponse("<h1> GET REQUEST>>>> </h1>")
Forms.Py
from django.forms import ModelForm
from .models import Post
class PostForm(ModelForm):
class Meta:
model= Post
fields = ['Username']
Models.Py
from django.db import models
class Post(models.Model):
Username = models.CharField(max_length = 20)
def __str__(self):
return self.name
HTML CODE
{% block body %}
<div class="container-fluid">
<form method="POST" class="post-form" action="{% url 'submit' %}">
{% csrf_token %}
<div class="form-group"> <!-- Full Name -->
<label for="Username" class="control-label">Full Name</label>
<input type="text" class="form-control" id="Username" name="full_name" placeholder="Enter the name of Patient here.">
</div>
<div class="form-group"> <!-- Submit Button -->
<button type="submit" class="btn btn-primary"> Submit!</button>
</div>
</form>
</div>
<hr/>
{% endblock %}
Urls.Py
from django.conf.urls import url
from . import views
urlpatterns = [
url(r'^/submit$', views.register , name = 'submit'),
]
The name of your input should be username:
This is how you send this value to the form.
NOTE: It's better to use the django form, that you've already done with ModelForm
<input type="text" class="form-control" id="username" name="username" placeholder="Enter the name of Patient here.">

Django simple Post request is not working

I am new to Django and trying to build a simple web page. I am trying for post request but there no values getting inserted into the database.I hope the problem should be in views.py forms.is_valid() Since no logs are recorded after this line.Please assist
model.py
from django.db import models
from django.contrib.auth.models import User
from django.db.models import Q
from django.forms import ModelForm
from django import forms
# Create your models here.
class aws_cred(models.Model):
aws_access_user_id = models.ForeignKey(User,null=False,related_name="aws_acc_user")
access_key = models.CharField(max_length=300)
secret_key = models.CharField(max_length=300)
class aws(ModelForm):
class Meta:
model = aws_cred
fields = ['access_key','secret_key','aws_access_user_id']
views.py
from django.shortcuts import render_to_response,HttpResponseRedirect,render,redirect,reverse
from django.contrib.auth.decorators import login_required
from django.template import RequestContext
from s3comp.models import aws_cred,aws
import logging
#login_required
def fileinput(req):
logging.basicConfig(filename='log_filename.txt',level=logging.DEBUG, format='%(asctime)s - %(levelname)s - %(message)s')
if req.method == 'POST':
form = aws(req.POST)
logging.debug(form)
try:
logging.debug('step 4')
if form.is_valid():
logging.debug('step 5')
access_key_val = req.POST.get('access key','')
secret_key_val = req.POST.get('secret key','')
aws_access_user_id_val = req.POST.get('aws access user id', '')
logging.debug(access_key_val+" " +secret_key_val+" " +aws_access_user_id_val)
cred_obj = aws(access_key = access_key_val,secret_key =secret_key_val,aws_access_user_id = aws_access_user_id_val)
cred_obj.save()
return HttpResponseRedirect(reverse('s3comp:fileinput'))
except Exception as e:
logging.debug(e)
else:
form = aws()
return render(req,'s3comp/fileinput.html',{'form':form})
html file
<form action="{% url 'fileinput_home' %}" method="post">
{% csrf_token %}
<p><label for="Aws access user id">User:</label><input type="text" name="Aws access user id" value={{ user.get_username }}/></p>
<p><label for="Access Key">Access Key:</label><input type="text" name="Access Key"/></p>
<p><label for="Secret Key">Secret Key:</label><input type="text" name="Secret Key"/></p>
<input type="submit" value="Submit">
</form>
You are using wrong name attribute value in template and views, So update according to below code
<form action="{% url 'fileinput_home' %}" method="post">
{% csrf_token %}
<p><label for="Aws access user id">User:</label><input type="text" name="aws_access_user_id" value={{ user.get_username }}/></p>
<p><label for="Access Key">Access Key:</label><input type="text" name="access_key"/></p>
<p><label for="Secret Key">Secret Key:</label><input type="text" name="secret_key"/></p>
<input type="submit" value="Submit">
</form>
Views.py
access_key_val = req.POST.get('access_key','')
secret_key_val = req.POST.get('secret_key','')
aws_access_user_id_val = req.POST.get('aws_access_user_id', '')

DJANGO - Redirect to different page with form data

Hi i want to redirect to a destination page with the from data. For example when user fills a form the data inputted in the form, i want that to be outputted on the destination page
my codes are as follows:-
source page(experiment.html), I am unsure what the action should be for the form so please help me with it
<form action="{% url 'lazer.views.about_experiment' exp.link_name %}" method="POST">
{% csrf_token %}
<label>Researcher Name(s):<input type="text" name="researcher">
<lable>Study Summary<textarea rows="10" cols="50" placeholder="here you go" maxlength="500" class="form-control" name="study"></textarea>
<br>
<input type = "submit" value="Submit" class="btn btn-primary" />
</form>
destination page (about_experiment.html)
<h3>Holding page for {{ exp.name }}.</h3>
<h2> {{ form }} </h2>
views.py
from .forms import AboutHelp
from django.shortcuts import render
from django.http import HttpResponseRedirect
def about_experiment(request):
if request.method == 'POST':
form = AboutHelp(request.POST)
if form.is_valid():
researcher = form.cleaned_data['researcher']
study = form.cleaned_data['study']
else:
form = AboutHelp()
return render(request, 'about_experiment.html', {'form': form})`
forms.py
from django import forms
class AboutHelp(forms.Form):
researcher = forms.CharField(max_length=100)
study = forms.CharField(max_length=500)
urls.py
url(r'^about/(?P<ex_link_name>\w+)', lazer.views.about_experiment, name='lazer.views.about_experiment'),

Django: POST form (I'm doing smt wrong with csrf_protect)

What am I doing wrong?
...
from django.views.decorators.csrf import csrf_protect
from django.template import RequestContext
#csrf_protect
def home(request):
return render_to_response('home/home.html', {}, RequestContext(request))
def mail(request):
if request.method == 'POST':
...
Form:
<form method="POST" action="sendemail">
{% csrf_token %}
<input name="name" type="text" placeholder="Namr">
<input name="email" type="text" placeholder="mail">
<input type="submit">
</form>
URL:
url(r'^sendemail$', 'openshift.views.mail')
Thank you.
The #csrf_protect decorator should be on the view that handles the form, not the one displaying the form.
Besides, if you have the CSRF middleware installed, then all POST views are automatically protected.
See the docs: https://docs.djangoproject.com/en/dev/ref/contrib/csrf/