I read this and have the bug in code - I can send "null" by the form and there is no error message, its just go to 'thanks' page. I can write 'nothing' to the email field, and result will be the same. How to fix it?
models:
class Contact(forms.Form):
title = forms.CharField(max_length=100)
message = forms.CharField(max_length=255)
sender = forms.EmailField()
views:
def contact(request):
if request.method == 'POST':
form = Contact(request.POST)
if form.is_valid():
title = form.cleaned_data['title']
message = form.cleaned_data['message']
sender = form.cleaned_data['sender']
return HttpResponseRedirect('/thanks/')
else:
form = Contact()
return render(request, 'contact.html', {'form': form,})
template:
<form action="/contact/" method="post">
{% csrf_token %}
{{ form.non_field_errors }}
{{ form.title.errors }}
<label for="id_subject">Subject</label>
{{ form.title }}
{{ form.message.errors }}
<label for="id_message">Text</label>
{{ form.message }}
{{ form.sender.errors }}
<label for="id_sender">Email</label>
{{ form.sender }}
<p><input type="submit" value="Send" /></p>
</form>
I've got my money on you having mixed tabs and spaces.
I haven't seen this in a while - it used to be pretty common!
It appears the return statement is firing no matter what on POST.
Related
Good afternoon Community,
I hope you are all well.
I am building my first website and I have the following problem; when I try to create a new user, if the user enters the wrong data the template does not show the error. Any hints?
Template:
<form action= "" method='post'>
{% csrf_token %}
{% for field in form %}
<p>{{field.label}}{{field}}</p>
{% endfor %}
<button type="submit" class="btn btn-success">Create User</button>
Views.py:
def register_page(request):
form = UserForm
if request.method == 'POST':
form = UserForm(request.POST)
if form.is_valid():
form.save()
return HttpResponseRedirect('http://127.0.0.1:8000/login_user/')
context = {'form' : form}
return render(request, 'simple_investing/register.htm', context)
Forms.py:
class UserForm(UserCreationForm):
class Meta:
model = User
fields = ('username', 'email', 'password1', 'password2')
As is discussed in the rendering fields manually section of the documentation, for the fields you should also render {{ field.errors }}, and the {{ form.non_field_errors }} which deals with errors not specific to one form.
The template thus should look like:
<form action= "" method="post">
{% csrf_token %}
{{ form.non_field_errors }}
{% for field in form %}
<p>
{{ field.errors }}
{{ field.label }}
{{ field }}
</p>
{% endfor %}
<button type="submit" class="btn btn-success">Create User</button>
</form>
The section also discusses how to enumerate over the errors, and apply certain styling to these errors.
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'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' %}
here with this code the form errors are not displaying properly.The all error messages says, this field is required only.how can i define my custom form.error message in the template.
template
{% if form.errors %}
{% for field in form %}
{% for error in field.errors %}
<p> {{ error }} </p>
{% endfor %}
{% endfor %}
{% endif %}
<div class="form-group">
<h5>Full Name <span class="text-danger">*</span></h5>
<div class="controls">
<input type="text" name="name" class="form-control" title="Full Name is required" > </div>
</div>
<div class="form-group">
<h5>Courses<span class="text-danger">*</span></h5>
<div class="controls">
{% for course in courses %}
<input name ="courses" type="checkbox" id="course-{{course.id}}" value="{{course.id}}" autofocus title="Please Check at least one course">
<label for="course-{{course.id}}">{{course.title}}</label>
{% endfor %}
</div>
</div>
views.py
if request.method == 'POST':
form = AddStudentForm(request.POST, request.FILES)
if form.is_valid():
student = form.save(commit=True)
student.save()
messages.success(request, 'student with name {} added.'.format(student.name))
return redirect('admin:add_student')
else:
form = AddStudentForm()
return render(request, 'admin/add_student.html', {'form': form})
in your views.py pass the form with errors like this
if request.method == 'POST':
form = AddStudentForm(request.POST, request.FILES)
if form.is_valid():
student = form.save(commit=True)
student.save()
messages.success(request, 'student with name {} added.'.format(student.name))
return redirect('admin:add_student')
return render(request, 'admin/add_student.html', {'form': form})
else:
form = AddStudentForm()
return render(request, 'admin/add_student.html', {'form': form})
That means you should remove the else part
and in your template code
{% if form.errors %}
<div class="alert alert-danger">
{{ form.errors }}
</div>
{% endif %}
Updated the answer to get proper answer when you load the view first time
When I enter an invalid email adress I cant see an error message like "This is not an invalid email".
My comment_form.html:
{% load i18n %}
<form action="/comment/create/" method="post">
{% csrf_token %}
{{ form.errors }}
{% for field in form %}
<div class="fieldWrapper">
{{ field.label_tag }}
{{ field }}<p>
</div>
{% endfor %}
<input type="hidden" name = "object_id" value="{{object_id}}" />
<input type="hidden" name= "next" value="{{ next }}" />
<input type="submit" value="{% trans "Submit" %}">
</form>
my post_detail.html:
extends "base.html" %}
{% block content %}
<div id="exap">
{{ post.content }}
</div>
<div class="comment">
{% for comment in comments %}
<user>{{ comment.owner }}</user>
{{ comment.content}}
{% endfor %}
</div>
{% include "comment_form.html" %}
{% endblock %}
this is my comment.views
def create(request):
if request.method == 'POST':
form = CommentForm(request.POST)
email = request.POST.get('email')
next = request.POST.get('next')
if form.is_valid():
content_type = ContentType.objects.get(app_label="post", model="post")
object_id = request.POST["object_id"]
comment = Comment.objects.create(
content_type = content_type,
object_id = object_id,
content = request.POST.get('content'),
owner= request.POST.get('owner'),
email = request.POST.get('email')
)
else:
print form.errors
else:
form = CommentForm()
return HttpResponseRedirect(next)
Error message doesnt display in template ?
Where am I wrong ?
karthikr is trying to tell you what is wrong in the comments. You are not using the form to validate, so it won't show any errors. Instead of doing if validateEmail(email) you should have the email validation code inside the form class, and in the view you call if form.is_valid().
Plus, when you do write the form's clean_email method, you should not be catching ValidationError: that's the way that errors are passed on to the form's errors list.