I'm implementing RecaptchaV3 on a Django application.
I am currently following this github(https://github.com/kbytesys/django-recaptcha3) README text to set it up.
I have a feedback form that sends an email with the subject and text.
However, when I add RecaptchaField in django form, the POST request no longer passes the form.is_valid() in views.py.
Does anyone have a thought/fix on how to overcome this problem?
Thank you in advance
forms.py
class contactForm(forms.Form):
name = forms.CharField(max_length=50, required=True, widget=forms.TextInput(attrs={'placeholder': 'Name (required)'}))
email = forms.EmailField(max_length=100, required=True, widget=forms.TextInput(attrs={'placeholder': 'Email (required)'}))
subject = forms.CharField(max_length=200, widget=forms.TextInput(attrs={'placeholder': 'Subject'}))
message= forms.CharField(max_length=1000, widget=forms.Textarea(attrs={'placeholder': 'Message'}))
captcha = ReCaptchaField()
views.py
def homepage(request):
form = contactForm()
if request.method == 'POST':
form = contactForm(request.POST)
if form.is_valid():
print("form is valid")
form = contactForm()
return render(request, 'homepage/home.html', {'form':form, 'context':context,})
template
<form class="form-horizontal" id="contactForm" method="POST" action="?">
{% csrf_token %}
<div class="form-group">
<div class="form-group">
<label for="name">Your Name (required)</label><br>
{{ form.name }}
</div>
<div class="form-group">
<label for="email">Your Email (required)</label><br>
{{ form.email }}
</div>
<div class="form-group">
<label for="subject">Subject</label><br>
{{ form.subject }}
</div>
<div class="form-group">
<label for="message">Your Message</label><br>
{{ form.message }}
</div>
</div>
<button class="btn" type="submit">SEND</button>
</form>
in the header, i've added
{% recaptcha_init %}
{% recaptcha_ready action_name='Homepage' %}
Related
I'm using the basic django registration form and I'm not getting any errors displayed. I've seen a bunch of answers and nothing is working for me. I'm not sure if it's because I have custom css for the page or bootstrap or something else. Basically how do I display the errors in this particular case.
Here's my form:
<div class="form-content">
<h1>Sign Up</h1>
{% if user.is_authenticated == False %}
<form method="POST">
{% csrf_token %} {{form.as_p}}
<button class="btn form-btn">Sign Up</button>
<h4><span>or</span></h4>
<a
class="btn google-btn"
href="{% provider_login_url 'google' %}"
role="button"
style="text-transform: none; width: 100%"
>
<img
width="20px"
style="margin-bottom: 3px; margin-right: 5px"
alt="Google sign-in"
src="https://upload.wikimedia.org/wikipedia/commons/thumb/5/53/Google_%22G%22_Logo.svg/512px-Google_%22G%22_Logo.svg.png"
/>
Sign up with Google
</a>
</form>
{% else %}
<p>You're already registered...</p>
{% endif %}
</div>
Here's my view:
class UserRegistration(generic.CreateView):
form_class = RegisterForm
template_name = 'registration/registration.html'
def form_valid(self, form):
user = form.save()
form.registration_notification()
login(self.request, user, backend='django.contrib.auth.backends.ModelBackend')
return redirect(self.request.GET.get('next'))
and form:
class RegisterForm(UserCreationForm):
email = forms.EmailField()
first_name = forms.CharField(max_length=100)
last_name = forms.CharField(max_length=100)
class Meta:
model = User
fields = ('username', 'first_name', 'last_name', 'email', 'password1', 'password2')
def registration_notification(self):
email = self.cleaned_data['email']
username = self.cleaned_data['username']
if self.is_valid():
registration_notification_task.delay(email, username)
I'm not sure where to return the errors or where to validate the form and no answers for other questions have helped my situation. Now when I submit an invalid form there are no errors the page just doesn't submit. There's not even an error in the network tab so it's probably happening on the html side.
Updating my post following comments below:
**forms.py** (dont forget the import bit)
from django.contrib.auth.forms import UserCreationForm, AuthenticationForm
class RegisterForm(UserCreationForm):
class Meta:
model = User
fields = ["username", "email", "password1", "password2",]
views.py
def register_user(request):
if request.method == "POST":
form = RegisterForm(request.POST)
if form.is_valid():
new_user = form.save()
new_user = authenticate(username=form.cleaned_data['username'],
password=form.cleaned_data['password1'],)
login(request, new_user)
messages.success(request,("Registration succesful!"))
return HttpResponseRedirect("/home")
else:
form = RegisterForm()
return render(request,'main/registration/register_user.html',{'form':form})
registration template
{% load crispy_forms_tags %}
{% block content %}
<div class="container">
<div class="row">
<div class="col-md-5 mx-auto">
<div id="second">
<div class="myform form ">
<div class="logo mb-3">
<div class="col-md-12 text-center">
<h1 >Signup</h1>
</div>
</div>
<form method="POST" action = "{% url 'register_user' %}" class="form-group">
{% csrf_token %}
{{ form| crispy }}
<div class="col-md-12 text-center mb-3">
<button type="submit" class=" btn btn-block mybtn btn-primary tx-tfm">Let's do it!</button>
</div>
<div class="col-md-12 ">
<div class="form-group">
<p class="text-center">Already have an account?</p>
</div>
</div>
</div>
</form>
</div>
</div>
{% endblock %}
Maybe it might be an oversight but I do not know the point where I am getting it wrong.
My form is rendered correctly but it keeps failing without errors.
forms.py
from crispy_forms.helper import FormHelper
from django import forms
from django.utils.translation import ugettext as _
class BeneficiaryForm(forms.Form):
"""Add Beneficiary template form"""
# Form fields
account_currency = forms.ModelChoiceField(queryset=Currency.objects.all(), empty_label=_('Select account currency'))
bank_account_type = forms.CharField(max_length=50, required=False)
email = forms.CharField(max_length=150, required=False, help_text=_("We'll notify them when a transfer is made"))
name = forms.CharField(max_length=50, required=False)
swift_code = forms.CharField(max_length=11, required=False,
widget=forms.TextInput(attrs={'placeholder': 'MSBCCNBJ001'}))
iban = forms.CharField(max_length=34)
def __init__(self, *args, **kwargs):
super(BeneficiaryForm, self).__init__()
self.helper = FormHelper()
self.helper.form_show_labels = False
views.py
def beneficiaries(request):
"""View function for viewing Beneficiaries and adding a Beneficiary instance"""
if request.method == 'POST':
form = BeneficiaryForm(request.POST)
if form.is_valid():
print("Form is valid")
print(request.POST['bank_account_type'])
print(request.POST['email'])
print(request.POST['name'])
print(request.POST['iban'])
print(request.POST['swift_code'])
print("Form is invalid")
print(form.errors)
form = BeneficiaryForm()
context = {
'form': form
}
return render(request, 'dashboard/beneficiaries.html', context)
and in my rendered form. I have this block to show errors and nothing shows up
HTML
<form action="{% url 'beneficiary_index' %}" method="post">
{% csrf_token %}
{% if form.errors %}
{% for field in form %}
{% for error in field.errors %}
<div class="alert alert-danger">
{% if field != '__all__' %}
<strong>{{ field.label }}:</strong>
{% endif %}
{{ error|escape}}
</div>
{% endfor %}
{% endfor %}
{% endif %}
<div class="form-group">
<div class="form-label-group">
<label class="form-label" for="default-01">{% trans "Account currency" %}</label>'
</div>
{{ form.account_currency | as_crispy_field }}
</div>
<div class="form-group">
<div class="form-label-group">
<label class="form-label" for="default-01">{% trans "Bank Account type" %}</label>
</div>
{{ form.bank_account_type | as_crispy_field }}
</div>
<div class="form-group">
<div class="form-label-group">
<label class="form-label" for="default-01">Their email(optional)</label>
</div>
{{ form.email | as_crispy_field }}
</div>
<div class="form-group">
<div class="form-label-group">
<label class="form-label" for="default-01">Full name of account holder</label>
</div>
{{ form.name | as_crispy_field }}
</div>
<h6>{% trans "Recipient Bank Information" %}</h6>
<hr>
<div class="form-group">
<div class="form-label-group">
<label class="form-label" for="default-01">Swift code</label>
</div>
{{ form.swift_code | as_crispy_field }}
</div>
<div class="form-group">
<div class="form-label-group">
<label class="form-label" for="default-01">IBAN</label>
</div>
{{ form.iban | as_crispy_field }}
</div>
<div class="form-group">
<button class="btn btn-lg btn-primary btn-block">{% trans 'Add Beneficiary' %}</button>
</div>
</form>
This is the Html to the form. I have just tried all the suggestions and still without the errors.
Form is Invalid is the only thing printed on screen without the form.errors
You need to create the GET request empty form in the else block or return the request in the POST block.
You are re-creating an empty form before returning the response.
def beneficiaries(request):
"""View function for viewing Beneficiaries and adding a Beneficiary instance"""
if request.method == 'POST':
form = BeneficiaryForm(request.POST)
if form.is_valid():
print("Form is valid")
print(request.POST['bank_account_type'])
print(request.POST['email'])
print(request.POST['name'])
print(request.POST['iban'])
print(request.POST['swift_code'])
# do other stuff like saving to DB
# then redirect
else:
print("Form is invalid")
print(form.errors)
elif request.method == 'GET':
form = BeneficiaryForm()
else:
# maybe return 404
pass
context = {
'form': form
}
return render(request, 'dashboard/beneficiaries.html', context)
Or maybe you can try Class Based Views, to avoid the if-else block for GET and POST requests.
Try adding this to the place you want the error to appear (In the HTML file)
Better if you use it inside the tags.
{% if form.errors %}
<p>Form is invalid</p>
{% endif %}
I Hope this answers the question.
On my Django website, I'm unable to submit my form. Although I have every field filled out, my password field continues to say "This field is required" even as I have typed something in the password field as well.
I have tried removing the required attribute for the password tag but that has not helped.
Here is my code.:
F
views.py: specifically for the function signup, the code never reaches within the if form.is_valid() block.
def signup(request):
#If user completes the form (hits the sign up button)
#Send form data to url /signup-complete/ (see signup.html)
if request.method == 'POST':
form = SignUpForm(request.POST)
if form.is_valid():
user = User.objects.create(
username= form.cleaned_data['email'], #Note although there is an email field, we don't use it to prevent redundancy
first_name = form.cleaned_data['first_name'],
last_name = form.cleaned_data['last_name'],
password = form.cleaned_data['password'],
)
#Extended attribute, must be added seperately
user.user_extend.is_student = form.cleaned_data['is_student']
user.save()
print('user is now created')
return HttpResponseRedirect('')
#Render form
else:
form = SignUpForm()
return render(request, 'mainapp/signup.html', {'form': form})
signup.html
<!-- action="/signup_complete/"-->
<form action="" method="post">
<!--Security, Cross Site Request Forgery Protection -->
{% csrf_token %}
{{ form.non_field_errors }}
{% for field in form %}
<div class="form-group">
{{ field.errors }}
<!--or field.name == 'confirm_password'-->
{% if field.name == 'password' %}
{{ field.label_tag }}
<input name="{{ field.name }}" class="form-control" type="password" required>
{% elif field.name == 'email'%}
{{ field.label_tag }}
<input name="{{ field.name }}" class="form-control" type="email" required>
{% elif field.name == 'is_student'%}
<div class="float-right">
<input name="{{ field.name }}" type="checkbox">
{{ field.label_tag }}
</div>
<!--First and last name -->
{% else %}
{{ field.label_tag }}
<input name="{{ field.name }}" class="form-control" type="text" required>
{% endif %}
</div>
{% endfor %}
<!-- Sign up button -->
<button type="submit" class="btn btn-primary col-md-12" value="sign_up">Sign Up!</button>
</form>
models.py
class UserExtend(models.Model):
user = models.OneToOneField(User, on_delete=models.CASCADE)
is_student = models.BooleanField(default=None)
SignUpForm (forms.py)
class SignUpForm(forms.Form):
first_name = forms.CharField(label='First Name', max_length=50)
last_name = forms.CharField(label='Last Name', max_length=50)
email = forms.EmailField()
password = forms.CharField(widget=forms.PasswordInput, max_length=50)
is_student = forms.BooleanField(label="Are you a student? (Statistical purposes only)")
First i suggest you look the request carefully to find what field you pass through it.
you can show form simpler.
<form>
{{form.password.errors}}
<input name="password" class="classes">
</form>
Found my error. The problem is that my boostrap was displaying incorrectly that the password field ha an error when in actuality, the checkbox had an error because it did not have a default value.
I am still new to django. Playing around with a leadmanager app and I don't know why my form is not validating.
views
def index(request):
lead=LeadForm()
if request.method == 'POST':
lead=LeadForm(request.POST)
if lead.is_valid():
messages.success(request, f'Thank you for registering. Someone will be contacting you soon.')
return redirect('index')
else:
lead=LeadForm()
messages.error(request, f'Something went wrong. Please try again later.')
return render(request, "frontend/index.html", {'lead':lead})
in index.html
<form action="" method="POST" class="lead-form">
{% csrf_token %}
<fieldset class="lead-info">
<div class="form-control">
<label for="">Full Name</label>
{{ lead.fullname }}
</div>
<div class="form-control">
<label for="">Email</label>
{{ lead.email }}
</div>
<div class="form-control">
<label for="">Phone</label>
{{ lead.phone }}
</div>
<div class="form-control">
<label for="">City</label>
{{ lead.city }}
</div>
</fieldset>
<button type="submit" class="btn-pill">Submit</button>
</form>
in forms.py
class LeadForm(forms.ModelForm):
email = forms.EmailField()
class Meta:
model = Lead
fields = ['fullname', 'email', 'phone', 'city', 'contact_preference']
widgets = {'contact_preference': forms.RadioSelect }
Any help is appreciated. contact_preference is rendering FYI, I just cut the code to keep this question not that long.
i am working on login page but my form always gives me error, please find my code below, please see view.py it response always go to else statment of "if form.is_valid():" condition. please help
here you can see form.py
from django.contrib.auth.models import User
from django import forms
class LoginForm(forms.ModelForm):
password = forms.CharField(widget=forms.PasswordInput)
class Meta:
model = User
fields = ['username', 'password']
this is my view.py
def login_view(request):
template_name = 'user/login.html'
form_class = LoginForm
if request.method == "POST":
form = form_class(data=request.POST)
if form.is_valid():
username = form.cleaned_data['username']
password = form.cleaned_data['password']
user = authenticate(username=username, password=password)
try:
login(request, user)
return redirect('user:profile')
except:
form = form_class(None)
return render(request, template_name, {'form': form, 'custom_error': 'Error'})
else:
return HttpResponse("<h1>Data is invalid</h1>")
else:
if request.user.is_authenticated():
return redirect('user:profile')
else:
form = form_class(None)
return render(request, template_name, {'form': form,})
user/login.html
{% block body %}
<div class="section">
<div class="container">
<div class="row">
<form class="form-horizontal" role="form" action="" method="post" enctype="multipart/form-data">
{% csrf_token %}
<div class="col-md-5">
<img src="{% static 'user/images/favicon.png' %}" class="img-responsive">
</div>
<div class="col-md-6">
{% include 'user/form-template.html' %}
<div class="col-sm-offset-2 col-sm-10" align="right">
<button type="submit" class="btn btn-default" autofocus>Sign In</button>
</div>
</div>
</form>
</div>
</div>
</div>
{% endblock %}
and finally this is my form-template.html file
{% for field in form %}
<div class="col-md-8">
<div class="col-md-4">
<label>{{ field.label_tag }} </label>
</div>
<div class="col-md-4">
{{ field }}
<div>
<span>{{ field.errors }}</span>
</div>
<div>
<span class="text-danger small">{{ custom_error }}</span>
</div>
</div>
</div>
{% endfor %}
If you are using ModelForm, you are going to operate on django model objects, creating, updating, etc. If you are only trying to login, use Form instead.
Thanks its solved, I just Changed My Form no it looks like this.
class LoginForm(forms.Form):
username = forms.CharField()
password = forms.CharField(widget=forms.PasswordInput)
now i am not using built-in form and i also changed ModelForm to Form.