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/
Related
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')
Do you have any security concerns with what I've done being implemented in a production web app? Either in the Django HTML Template or my views logic?
I would prefer to have the form in actual html rather than using {{ form }}. Is it ok to allow the user to implement very basic passwords?
views.py is:
from django.shortcuts import render, redirect
from django.contrib.auth import get_user_model
User = get_user_model()
from django.contrib.auth import authenticate, login as auth_login
from django.contrib import auth
from memberships.models import UserMembership
from django.contrib.auth.decorators import login_required
from companies.models import Profile
# Create your views here.
def register(request):
if request.method == "POST":
# User has info and wants an account now!
if request.POST['password1'] == request.POST['password2']:
try:
user = User.objects.get(email=request.POST['email'])
return render(request, 'accounts/register.html', {'error': 'Email has already been taken'})
except User.DoesNotExist:
user = User.objects.create_user(request.POST['email'], password=request.POST['password1'])
auth.login(request, user)
company = Profile()
company.businessperson = request.user
company.first_name = request.POST['firstname']
company.last_name = request.POST['lastname']
company.company_name = request.POST['companyname']
company.phone_number = request.POST['phonenum']
company.save()
return redirect('memberships:payment')
else:
return render(request, 'accounts/register.html', {'error': 'Passwords must match'})
# User wants to enter info
return render(request, 'accounts/register.html')
def login(request):
if request.method == "POST":
user = authenticate(email=request.POST["email"], password=request.POST["password"])
if user is not None:
# Our backend authenticated the credentials
auth_login(request, user)
return redirect('dashboard')
else:
# Backend did not authenticate the credentials
return render(request, 'accounts/login.html', {"error": "Incorrect email and or password"})
else:
return render(request, 'accounts/login.html')
def logout(request):
if request.method == "POST":
auth.logout(request)
return redirect('login')
forms in login.html and register.html:
<!-- login.html -->
<form action="{% url 'login' %}" method="POST">
{% csrf_token %}
<div class="form-group">
<input type="email" name="email" id="exampleInputEmail">
</div>
<div class="form-group">
<input type="password" name="password" id="exampleInputPassword" >
</div>
<input type="submit" value="Login">
</form>
<!-- register.html -->
<form action="{% url 'register' %}" method="POST" >
{% csrf_token %}
<input type="text" name="firstname" id="exampleFirstName" >
<input type="text" name="lastname" id="exampleLastName" >
<input type="text" name="companyname" id="exampleInputCompany" >
<input type="tel" name="phonenum" id="exampleInputPhone" placeholder="Phone Number">
<input type="email" name="email" id="exampleInputEmail" placeholder="Email" required>
<input type="password" name="password1" id="exampleInputPassword" placeholder="Password" required>
<input type="password" name="password2" id="exampleRepeatPassword" placeholder="Repeat Password" required>
<input type="submit" value="Register Account">
</form>
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'),
i am having trouble validating my django form. my form is not validating. can anyone please examine my code and point out exactly where i am doing wrong. here are my codes.
models.py-
from django.db import models
classcommentbox
(models.Model) :
box=models.CharField(max_length=
50 )
forms.py-
from django.forms import ModelForm
from . models import commentbox
class commentboxForm(ModelForm):
class Meta:
model=commentbox
fields=['box']
views.py-
from django.http import HttpResponse
from . models import commentbox
from . forms import commentboxForm
def submit(request):
if request.method=="POST":
form=commentboxForm(request.
POST)
if form.is_valid():
return HttpResponse('valid')
else:
return HttpResponse('not
Valid')
else:
return HttpResponse("error")
template-
<form action="{% url 'poll:submit'
%}"method="POST">
{%csrf_token%}
<label for"comment"> say something:
</label>
<textarea class="form-control"
rows="3" id="comment"> </textarea>
<button type="button"> submit
</button>
</form>
add name attribute in textarea tag
<textarea class="form-control" name="box" rows="3" id="comment"> </textarea>
You need to add name for the input,
In your template,
<textarea class="form-control" rows="3" name="box" id="comment"> </textarea>
Or,
<input type="text" name="box" class="form-control">
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?