I am attempting to create a page where a user can see what their current email is and change it if they would like. I am just testing with a very simple form and a very simple HttpResponseRedirect if the form is not valid. However neither my email is changing for the user nor is my failure response if the form is not valid working. I am not sure what is causing this
forms.py:
class ChangeEmail(forms.Form):
email1 = forms.EmailField(label=u'Type new Email')
email2 = forms.EmailField(label=u'Type Email again')
views.py:
def change_email(request, username):
if request.method == 'POST':
user1 = User.objects.get(username=username)
form1 = ChangeEmail(request.POST)
if form1.is_valid():
user1.email = form.cleaned_data['email1']
form1.save()
return HttpResponseRedirect('/register/success')
else:
return HttpResponseRedirect('/stupid')
else:
user = User.objects.get(username=username)
email = user.email
form = ChangeEmail()
variables = RequestContext(request, {
'form': form,
'email': email
})
return render_to_response('registration/email.html', variables
Thanks for your help in advance.
EDIT:
The URL that I have mapped to render the form is /user/testuser/email. I am attempting to put in invalid input in to the fields to get an error message but when I push submit it redirects me back to /user/testuser page which displays info about the user. My change email template is below:
{% extends "base.html" %}
{% block title %}Change Email{% endblock %}
{% block head %}Change Email{% endblock %}
{% block content %}
<p> Current Email: {{ email }} </p>
<form method="post" action=".">{% csrf_token %}
{{ form.as_p }}
<input type="submit" value="Change Email" />
</form>
{% endblock %}
ChangeEmail is a normal form. These don't have save methods - only ModelForms do. You're correctly setting the user email from the form's cleaned_data - but you should be saving the user1 object, not the form.
Also, it's best not to redirect away on validation failure. Leave out that first else clause, and move the variables/render_to_response lines back one indentation level, and the form will be redisplayed with any errors.
views.py:
def change_email(request, username):
# a common django idiom for forms
form1 = ChangeEmail(request.POST or None)
user1 = User.objects.get(username=username)
if form1.is_valid():
#check that emails are the same
if form.cleaned_data['email1'] == form.cleaned_data['email2']:
user1.email = form.cleaned_data['email1']
#Save the user object here, since we're not dealing with a ModelForm
user1.save()
return HttpResponseRedirect('/register/success')
# We're presenting them with the empty form if something went wrong
# and redisplaying. The form's field errors should be printed out in
# the template
else:
user = User.objects.get(username=username)
email = user.email
variables = RequestContext(request, {
'form': form,
'email': email
})
return render_to_response('registration/email.html', variables)
Related
I am trying to implement some functionality that allows a user to edit their personal information in a Django project using Django forms. When a user enters the new value in the form and hits enter, they are brought back to the main profile page which is correct however, the values remain the same as before. Below is how I have tried to implement the functionality:
Forms
class UpdateProfile(forms.ModelForm):
email = forms.EmailField(required=False)
first_name = forms.CharField(required=False)
last_name = forms.CharField(required=False)
age = forms.IntegerField(required=False)
height = forms.IntegerField(required=False)
weight = forms.IntegerField(required=False)
class Meta:
#Here are the fields that i want editable
model = User
fields = ('email', 'first_name', 'last_name', 'age', 'height', 'weight')
#Here im trying to commit the changes to the user and return the user
def save(self, commit=True):
super(UpdateProfile, self).__init__(commit)
if commit:
user.save()
return user
Views
def update_profile(request):
args = {}
if request.method == 'POST':
form = UpdateProfile(request.POST, instance=request.user)
if form.is_valid():
form.save()
return HttpResponseRedirect(reverse('account/profile.html'))
else:
form = UpdateProfile()
args['form'] = form
return render(request, 'account/edit_profile.html', args)
HTML
% block head %}
<title>Profile</title>
{% endblock %}
{% block body %}
<div class="container">
<form method="POST" action="{% url 'account:profile' %}">
{% csrf_token %}
{{ form.as_p }}
<button type="submit">Submit</button>
</form>
<br>
</div>
{% endblock %}
Your form is submitting directly to the view profile page. But that page is presumably not expecting to validate a form. You need to submit it back to the update_profile page, which you normally do by using an action of just "." in the form HTML element.
<form method="POST" action=".">
Once you've done that, you'll see some issues with your form save() method. That method does not do anything useful anyway; you should remove it and let the superclass one be called automatically.
This line seems wrong:
super(UpdateProfile, self).__init__(commit)
You're calling __init__ from the parent class, but the method being called is save()... Also you're refering to a user variable which is (hopefully) not defined in this scope.
I've got a Django project, which requires users to be able create accounts to access content.
I'm using the UserCreationForm to do this.
In views.py I have
def register_user(request):
if request.method == "POST":
user_form = UserCreationForm(request.POST)
if user_form.is_valid():
new_user = user_form.save(commit=False)
new_user.set_password(user_form.cleaned_data["password1"])
new_user.save()
template = "account/registration/registration_done.html"
context = {"new_user": new_user}
else:
# TODO: Handle exception
raise BaseException
elif request.method == "GET":
user_form = UserCreationForm()
template = "account/registration/register.html"
context = {"user_form": user_form}
else:
raise NotImplementedError
return render(request, template, context=context)
And then my template is:
{% extends "base.html" %}
{% block title %}Create an Account{% endblock %}
{% block content %}
<h1>Create an Account</h1>
<form action="." method="post">
{{ user_form.as_p }}
{% csrf_token %}
<p><input type="submit" value="Create my account"></p>
</form>
{% endblock %}
Which works okay. But when the create account form is displayed, it only has fields for the username, password, and password verification. There's no requirement that the user enter a valid email.
What I'd like to do is have a have the user be required to enter an email address, and then send them an email to ensure that the address is valid, and that they have access to is etc.
Surely this is a common enough pattern that there's already a way to implement is using Django's authentication? Or will I need to write all the forms and handling etc myself?
Override the Meta class of the UserCreationForm
In your forms.py
from django.contrib.auth.forms import UserCreationForm
class YourUserCreationForm(UserCreationForm)
class Meta:
fields = ("username", "email")
and use YourUserCreationForm instead
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")
I've got a strange problem here. I have a user u=filip pw=filip123
The form returns false when I type in the correct user details BUT when I reverse the typing (typing in password in the username field and username in pw field) the form.is_valid() returns true.
The request.POST gets the right value
views.py
def login(request):
msg = "Login"
form = LoginForm(request.POST)
print (request.POST.get("username"))
print (request.POST.get("password"))
if form.is_valid():
msg = "valid"
print ("asdfa")
user = authenticate(username=request.POST.get("username"), password=request.POST.get("password"))
print (user)
context = {
"msg":msg,
"form": form,
}
return render(request, "login.html", context)
forms.py
class LoginForm(forms.ModelForm):
class Meta:
model = User
fields = [
"username",
"password"
]
login.html
{% block content %}
{% if form.errors %}
<p>Your username and password didn't match. Please try again.</p>
{{ form.errors }}
{% endif %}
<h1 style="color:red">{{ msg }}</h1>
<form method="post" action="">
{% csrf_token %}
username<input type="username" name="username">
password<input type="password" name="password">
<input type="submit" value="login" />
</form>
{% endblock %}
edit, the error message when I'm typing in a real user is "Your username and password didn't match. Please try again.
username
A user with that username already exists."
This is not the right use for a ModelForm. They are for creating and editing items in the database; the error message is because you have used this form as if you were creating a new user, and it's preventing you from doing that because the user with that username already exists.
Use a standard form instead. Or even better, use the LoginForm from django.contrib.auth.forms; the advantage of that is that it calls authenticate for you as part of the validation process, so that login errors will be included in the form errors (rather than completely ignored, as your code does).
I let a user sign up due to the following code:
def sign_up(request):
if request.POST:
userName = request.POST.get('username')
passWord = request.POST.get('password')
user = User.objects.create_user(username=userName, password=passWord)
user.save()
return HttpResponseRedirect(reverse('account:login'))
args = {}
args.update(csrf(request))
args['form'] = UserCreationForm()
return render_to_response('account/sign_up.html', args, context_instance=RequestContext(request))
TEMPLATE:
{% extends "base_login.html" %}
{% load staticfiles %}
<div id="sign_up"> {% block extension1 %}
<form action="/account/sign_up/" method="post"> {% csrf_token %}
{{ form }} <br/>
<input type="submit" value="Sign up"/>
</form> {% endblock %}
</div>
The user gets created. I can see this in the database. However, following this way, this newly created user wouldn't be albe to login. Though, users created the same way in shell will be able to login. I tried a lot and found:
users_able.password
'pbkdf2_sha256$12000$CczM6MmFkTrj$qA1QG7O4nBSSOh6...'
users_unable.password
'!KAXKN25DPijEmzj0TcrhpHYpyB1pLhue...'
So I suppose it has something to do with the password not set properly. Right? I use the default UserCreationForm for signing up. Any ideas?
Referring to How to use django UserCreationForm correctly:
You can directly save the UserCreationForm which will give you user object.
Allowing you to do something like this:
def sign_up(request):
if request.POST:
form = UserCreationForm(request.POST)
if form.is_valid():
user = form.save()
return HttpResponseRedirect(reverse('account:login'))
...
Django's UserCreationForm doesn't have a field named password. It has a named password1 and has a password2 field that when enetered should match password1. If you change request.POST.get('password') to request.POST.get('password1') I'm sure this would work. However, I would recommend you not use your method as it's built. You should be seeing if the form is valid before creating a user.