I have refrenced this stackoverflow page and tried to display my forms error on the html template.
I did:
{% if form.error %}
{% for field in form %}
{% for error in field.errors %}
<div class="alert alert-danger">
<strong>{{ error|escape }}</strong>
</div>
{% endfor %}
{% endfor %}
{% for error in form.non_field_errors %}
<div class="alert alert-danger">
<strong>{{ error|escape }}</strong>
</div>
{% endfor %}
{% endif %}
as said in the stackoverflow question I also tried simply doing:
{% if form.error %}
This should pop up if there is an error
{% endif %}
Nothing comes up regardless:
Heres my view.py code:
def register(request):
if request.method == 'POST':
form = UserCreationForm(request.POST)
if form.is_valid():
form.save()
username = form.cleaned_data.get('username')
password = form.cleaned_data.get('password2')
user = authenticate(username=username, password=password)
login(request, user)
return HttpResponseRedirect('/')
else:
print(form.errors)
form = UserCreationForm()
return render(request, 'registration/register.html', {'form': form})
I am able to get the form errors onto the django console but it refuses to show up on the template.
Printing form.errors prints to the console: <li>password2<ul class="errorlist"><li>The two password fields didn't match.</li></ul></li></ul>
forms.errors fired up, but at the end, you declare a new form form = UserCreationForm() just before you render your view.
After checking whether the form is valid or not, all your validation errors are inside form instance, remember processes run as sequence, at the end, you destroy the variable form with form = UserCreationForm() so no validation errors anymore.
What you can do is add this new form form = UserCreationForm() to else statement when your request method is GET to keep having an empty form. By adding the else statement you avoid the new assignment of the form; after the validation process, it will jump to render(request,....) with the form instance containing all validation errors
if request.method == 'POST':
form = UserCreationForm(request.POST)
if form.is_valid():
form.save()
username = form.cleaned_data.get('username')
password = form.cleaned_data.get('password2')
user = authenticate(username=username, password=password)
login(request, user)
return HttpResponseRedirect('/')
else:
print(form.errors)
else:
form = UserCreationForm()
return render(request, 'registration/register.html', {'form': form})
Note, the correct call for form errors in templates is form.errors with s not form.error
{% if form.error %} {% if form.errors %}
Related
Hello I am making Django App. I have a problem with my login form. Whenever I want to login,
form does not do anything or it throws csrf token error.
Views:
def loginView(request):
if request.method == 'POST':
form = AuthenticationForm(request.POST)
if form.is_valid():
form.save()
username = form.cleaned_data.get('username')
messages.success(request, f"You successfully logged in {username}")
return redirect('home-page')
else:
form = AuthenticationForm()
return render(request, 'shop/login.html', {'form': form})
HTML TEMPLATE:
{% extends 'shop/base.html' %}
{% block content %}
<div class = "form-container">
<form class="form" method="POST">{% csrf_token %}
<label for="username">Email:</label>
{{form.username}}
<label for="password">Passoword:</label>
{{form.password}}
<button type="submit">Login</button>
</form>
</div>
{% endblock content %}
you have to check whether user existed or not in db if yes then login and redirect if not throw error or redirect on other page
def my_login(request):
if request.method == 'POST':
form = AuthenticationForm(request.POST)
if form.is_valid():
username = form.cleaned_data["username"]
password = form.cleaned_data["password"]
user = authenticate(username=username, password=password)
if user:
login(request, user)
return redirect('path')
else:
return redirect('path')
else:
return redirect('path')
else:
form = AuthenticationForm()
return render(request, "shop/login.html", {'form': form})
still get error add the complete traceback & i will also suggest you to read the full documentation of django https://docs.djangoproject.com/en/3.2/ref/contrib/auth/
When i am running my Django project on local server. It is returning whole html code on webpage.
Like after executing command python manage.py runserver and copy and pasting url on browser i am getting whole HTML file code instead element i have used.
My Html file
{% extends "wfhApp/base.html" %}
{% block body_block %}
<div class="jumbotron">
{% if registered %}
<h1>Thank you for registration</h1>
{% else %}
<h1>Register here!</h1>
<h3>Fill out the form:</h3>
<form enctype="multipart/form-data" method="post">
{% csrf_token %}
{{ user_form.as_p }}
<input type="submit" name="" value="Register">
</form>
{% endif %}
</div>
{% endblock %}
My views.py
from django.shortcuts import render
from wfhApp.forms import UserForm
def register(request):
registered = False
if request.method == 'POST':
user_form = UserForm(data = request.POST)
if user_form.is_valid():
user = user_form.save()
user.set_password(user.password)
user.save()
registered = True
else:
print(user_form.errors)
else:
user_form = UserForm
return render(request, 'wfhApp/registration.html',
{'user_form': user_form},
{'registered': registered})
Above is from template inheritance.
Not 101% sure since you didn't really explained what you meant by "It is returning whole html code on webpage" but here:
return render(request, 'wfhApp/registration.html',
{'user_form': user_form},
{'registered': registered})
you're not correctly passing the template context - or, more exactly, you are passing {'user_form': user_form} as the context and {'registered': registered} as the response's content_type (which would else be the default "text/html").
What you want is (splitted on two lines for readability):
context = {
'user_form': user_form,
'registered': registered
}
return render(request, 'wfhApp/registration.html', context)
Entirely new to python and django framework.
Trying to build a login/registration system.'
After registering, redirects to home but user is not authenticated (returns false always)
views.py
def register(request):
if request.method == 'POST':
form = SignUpForm(request.POST)
if form.is_valid():
form.save()
username = form.cleaned_data.get('username')
fullname = form.cleaned_data.get('fullname')
password = form.cleaned_data.get('password1')
user = authenticate(username=username, fullname=fullname, password=password)
messages.success(request, f'Welcome to blaza {fullname}')
if user is not None:
login(request, user)
return redirect('home')
else:
form = SignUpForm()
return render(request, 'accounts/signup.html', {'form': form})
home.html
{% extends 'base.html' %}
{% block title %} Home {% endblock %}
{% block content %}
{% if user.is_authenticated %}
Welcome, {{user.username}}!
Logout
{% else %}
<P>You are not logged in</P>
<p>Login here</p>
{% endif %}
{% endblock %}
It returns false always. "You are not logged".
I have tried {% if request.user.is_authenticated %} still not working.
is_authenticated is a method not a property. I think you forgot the parenthesis.
Try this:
{% if request.user.is_authenticated() %}
Have you saved the user after signing up ?
myuser.save()
I have attached the code which worked for me.
def signup(request):
if request.method == 'POST':
username = request.POST['username']
name = request.POST['name']
email = request.POST['email']
pass1 = request.POST['pass1']
pass2 = request.POST['pass2']
myuser = User.objects.create_user(username, email)
myuser.set_password(pass1)
myuser.us_name = name
myuser.save()
messages.success(request, "Your account has been sucessfully created. ")
return redirect('signin')
return render(request, "authentication/signup.html")
I cobbled together a delete button and edited my view, it isn't working. Can someone help me fix it?
I've moved some code around and tried some things but I can't get it to work. I need someone to show me what I'm doing wrong.
My view:
def post_edit(request, pk):
post = get_object_or_404(Listing, pk=pk)
if request.method == "POST":
form = ListingForm(request.POST, instance=post)
if form.is_valid():
post = form.save(commit=False)
post.save()
return redirect('post_view', pk=post.pk)
else:
form = ListingForm(instance=post)
if request.POST.get('delete'):
post.delete()
return redirect('listings')
return render(request, 'post_edit.html', {'form': form})
My html:
{% extends 'base.html' %}
{% block title %}Post Edit{% endblock %}
{% block content %}
Hi {{ user.username }}!
<p>logout</p>
<h1>Edit listing:</h1>
<p>The listing will only be viewable to users if "Is Live" is checked.</p>
<form method="POST" enctype="multipart/form-data" class="post-form">{% csrf_token %}
{{ form.as_p }}
<button type="submit" class="save btn btn-default">Save</button>
<p>Click the button below to delete this listing. No second warning is given, once you click delete it will be
removed.</p>
<button type="delete" class="delete btn btn-default">delete</button>
</form>
{% endblock %}
"delete" is not a valid type for an HTML form control. You'l need to change it to "submit" (Since you still want to submit the form).
What you'll want to do is create two buttons with the same name, and different values like this:
<button type="submit" name="submit" value="submit" class="save btn btn-default">Save</button>
<p>Click the button below to delete this listing. No second warning is given, once you click delete it will be
removed.</p>
<button type="submit" name="submit" value="delete" class="delete btn btn-default">delete</button>
Then you can check in your view if the delete button was clicked, like this:
def post_edit(request, pk):
post = get_object_or_404(Listing, pk=pk)
if request.method == "POST":
if request.POST.get('submit') == 'delete':
post.delete()
return redirect('listings')
form = ListingForm(request.POST, instance=post)
if form.is_valid():
post = form.save(commit=False)
post.save()
return redirect('post_view', pk=post.pk)
else:
form = ListingForm(instance=post)
return render(request, 'post_edit.html', {'form': form})
Note that I move the check for the delete button to inside the if request.method == "POST": block, for two reasons:
You'll only want to check the POST values if it's actually a post method.
There is no use editing a post, then deleting it.
I have created a form to add users in my front-end but the form does not validate duplicated username.I am using auth.user model.
This is my code:
views.py
from django.contrib.auth.models import User, Group
#login_required(login_url='/login/')
#permission_required('auth.add_user',raise_exception=True)
def user_new(request):
if request.method == "POST":
form = NewUserForm(request.POST)
if form.is_valid():
user = form.save(commit=False)
user.set_password(user.password)
user.save()
return redirect('userdetail', user.id)
else:
form = NewUserForm()
return render(request, 'ace/user_edit.html', {'form': form})
forms.py
class NewUserForm(forms.ModelForm):
class Meta:
model = User
fields = ['username','first_name','last_name','password','email','is_active','is_staff','groups']
widgets = {
'username':TextInput(attrs={'class': u'form-control'}),
'first_name':TextInput(attrs={'class': u'form-control'}),
'last_name':TextInput(attrs={'class': u'form-control'}),
'password':PasswordInput(attrs={'class': u'form-control'}),
'email':EmailInput(attrs={'class': u'form-control'}),
'is_active':NullBooleanSelect(attrs={'class': u'form-control'}),
'is_staff':NullBooleanSelect(attrs={'class': u'form-control'}),
'groups':SelectMultiple(attrs={'class': u'form-control'}),
}
def clean_username(self):
username = self.cleaned_data['username']
user_exists = User.objects.get(username=username)
if user_exists:
raise ValidationError("User exists")
template
...
{% if form.errors %}
{% for field in form %}
{% for error in field.errors %}
<div class="alert alert-danger">
<strong>{{ error|escape }}</strong>
</div>
{% endfor %}
{% endfor %}
{% for error in form.non_field_errors %}
<div class="alert alert-danger">
<strong>{{ error|escape }}</strong>
</div>
{% endfor %}
{% endif %}
<form method="POST" class="service-form">{% csrf_token %}
{{ form.as_p }}
<button type="submit" class="save btn btn-info">Salvar</button>
<a href="{% url 'userlist' %}">
<button class="btn btn-danger" type="button">Cancelar</button>
</a>
</form>
...
When I create a new user OK, but when a try create a user that same username of other I get a error:
The view ace.views.user_new didn't return an HttpResponse object. It
returned None instead.
If I add a print line "print form.errors" in view i get in console:
usernameUser
exists
Your view does not have an else statement for if, form is not valid it should render the template with form errors.
You need to change your view like this,
def user_new(request):
if request.method == "POST":
form = NewUserForm(request.POST)
if form.is_valid():
user = form.save(commit=False)
user.set_password(user.password)
user.save()
return redirect('userdetail', user.id)
else:
return render(request, 'ace/user_edit.html', {'form': form})
else:
form = NewUserForm()
return render(request, 'ace/user_edit.html', {'form': form})
And also you need to add the tag {%for field in form%} {{field.error}}{%endfor%} along with the form fields and labels.
You need to make sure that your view returns a response for POST requests when the form is invalid. You can do this by moving the final return render() statement out of the else block.
def user_new(request):
if request.method == "POST":
form = NewUserForm(request.POST)
if form.is_valid():
...
return redirect('userdetail', user.id)
else:
form = NewUserForm()
return render(request, 'ace/user_edit.html', {'form': form})
For registration django.contrib.auth User needs the username field to be unique. If you want to use other model field as unique (as unique registration field) and not the username, for example the email field, you can use this approach or use other registration bakends like django registration or django registration redux.
Instead of fixing the bug in your code I suggest to not invent the wheel and use excellent django-allauth package. It handles user login, logout, change password, registration and social sign in. I always start new projects from adding django-allauth - it handles all authentication problems with no effort.
You can use the saved time and effort to write actual application code instead of solving trivial user management details.
Also, the proper way to check for existence of the model instance is this:
user_exists = User.objects.filter(username=username).exists()
if user_exists:
raise ValidationError("User exists")