Edit : I am unable to load a image, but here is a link : https://plus.google.com/113782760013016224132/posts/3kcamT13yNP
Using Django. This is my first question.
I keep getting the error: Profile() got an unexpected keyword argument 'name'. I dont really understand why I am getting this error. It was working yesterday and now its all weird. Help would be much appreciated.
My forms.py is:
class RegistrationForm(ModelForm):
username = forms.CharField(label=(u'User Name'))
email = forms.EmailField(label=(u'Email Address'))
password = forms.CharField(label=(u'Password'), widget=forms.PasswordInput(render_value=False))
verifyPass = forms.CharField(label=(u'Verify Password'), widget=forms.PasswordInput(render_value=False))
class Meta:
model = Profile
exclude = ('user',)
def clean_username(self):
username = self.cleaned_data['username']
try:
User.objects.get(username=username)
except User.DoesNotExist:
return username
raise forms.ValidationError("That username is already taken, please select another username.")
def clean(self):
password = self.cleaned_data.get('password', None)
verifyPass = self.cleaned_data.get('verifyPass', None)
if password != verifyPass:
#self.cleaned_data['password'] != self.cleaned_data['verifyPass']:
raise forms.ValidationError("Please try again, the passwords did not match.")
return self.cleaned_data
views.py:
def UserRegistration(request):
if request.user.is_authenticated():
return HttpResponseRedirect('/profile')
if request.method == 'POST':
form = RegistrationForm(request.POST)
if form.is_valid():
user = User.objects.create_user(username = form.cleaned_data['username'], email = form.cleaned_data['email'], password = form.cleaned_data['password'])
user.save()
users = Profile(user=user, name=form.cleaned_data['name'], date_of_birth=form.cleaned_data['date_of_birth'])
users.save()
return HttpResponseRedirect('/profile/')
else:
return render_to_response('register.html', {'form': form}, context_instance=RequestContext(request))
else:
''' user is not submitting the form, show them a blank registration form '''
form = RegistrationForm()
context = {'form': form}
return render_to_response('register.html', context, context_instance=RequestContext(request))
def LoginRequest(request):
if request.user.is_authenticated():
return HttpResponseRedirect('/profile/')
if request.method == 'POST':
form = LoginUserForm(request.POST)
if form.is_valid():
username = form.cleaned_data['username']
password = form.cleaned_data['password']
users = authenticate(username = username, password = password)
if users is not None:
login(request, users)
return HttpResponseRedirect('/profile/')
else:
return render_to_response('login.html', {'form' : form}, context_instance = RequestContext(request))
else:
return render_to_response('login.html', {'form' : form}, context_instance = RequestContext(request))
else:
''' user is not submitting the form, show the login form '''
form = LoginUserForm()
context = {'form': form}
return render_to_response('login.html', context, context_instance=RequestContext(request))
def LogoutRequest(request):
logout(request)
return HttpResponseRedirect('/')
def Profile(request):
render_to_response('profile.html')
def home(request):
return render_to_response("home.html")
class LoginUserForm(forms.Form):
username = forms.CharField(label=(u'User Name'))
password = forms.CharField(label=(u'Password'), widget=forms.PasswordInput(render_value=False))
models.py:
class Profile(models.Model):
user = models.OneToOneField(User)
date_of_birth = models.DateField()
name = models.CharField(max_length=100)
def __str__(self):
return self.name
Related
How to create view for the registered user to edit there profile in the user dashboard using django ? Please provide the view .
I have created the register profile without using the forms.py , Now I want to create the userprofile edit only without using forms.py. And Is it possible to submit the data again to the
database.
(Dont use forms.py)
Accounts/views.py
def register(request):
if request.method == 'POST':
#get form values
first_name = request.POST['first_name']
last_name = request.POST['last_name']
username = request.POST['username']
email = request.POST['email']
password = request.POST['password']
password2 = request.POST['password2']
#Check if passwords match
if password == password2:
#check username
if User.objects.filter(username = username).exists():
messages.error(request,'That username is taken')
return redirect('register')
else:
if User.objects.filter(email=email).exists():
messages.error(request,'That email is being used')
return redirect('register')
else:
#looks good
user = User.objects.create_user(username = username, password = password, email = email, first_name = first_name, last_name = last_name)
#login after register
# auth.login(request, user)
# messages.success(request, 'You are now logged in')
# return redirect('index')
user.save()
messages.success(request, 'You are now registered and can log in')
return redirect('login')
else:
messages.error(request,'passwords do not match')
return redirect('register')
else:
return render(request, 'accounts/register.html')
I don't think there is a possible way to edit profile and change a password in the same view without use forms.py, but the django.contrib.auth.forms has a PasswordChangeForm and a UserChangeForm which you can use.
Se more in documentation: https://docs.djangoproject.com/en/1.8/_modules/django/contrib/auth/forms/
In your views.py
from django.contrib.auth.forms import UserChangeForm, PasswordChangeForm
def edit_profile(request):
if request.method == "POST":
form = UserChangeForm(request.POST, instance=request.user)
if form.is_valid():
form.save()
messages.info(request, "Ok")
return redirect("main:homepage")
else:
messages.error(request, "Error")
return redirect("main:edit_profile")
else:
form = UserChangeForm(instance=request.user)
return render(request, "main/edit-profile.html", {'form': form})
def change_password(request):
if request.method == "POST":
form = PasswordChangeForm(data=request.POST, user=request.user)
if form.is_valid():
form.save()
messages.info(request, "ok")
update_session_auth_hash(request, form.user)
return redirect("main:edit_profile")
else:
messages.error(request, "error")
return redirect("main:change_password")
else:
form = PasswordChangeForm(user=request.user)
return render(request, "main/change-password.html", {'form': form})
I am trying to create a list of employee. I can assign username, password and email to that employee and also can update employee information where I should able to update username, password or email either. I could create an employee and also create the username and password along with update employee info but when changing the username or password or email of the employee a new user is created.
Here is what I have tried
class EmployeeForm(forms.ModelForm):
password = forms.CharField(widget=forms.PasswordInput)
class Meta:
model = models.Employee
fields = ('name', 'designation', 'section', 'phone_number', 'mobile_number',
'email', 'gender', 'role', 'username', 'password', 'avatar',)
def employee(request):
form = EmployeeForm(request.POST or None)
if request.method == "POST" and form.is_valid():
username = form.cleaned_data['username']
password = form.cleaned_data['password']
email = form.cleaned_data['email']
office_instance = OfficeSetup.objects.get(owner=request.user)
form = form.save(commit=False)
form.office = office_instance
user = User.objects.create_user(
username=username, password=password, email=email)
user.save()
form.save()
messages.success(request, 'Thank you')
return redirect('employee-list')
messages.warning(request, 'Error')
context = {
'form': form
}
return render(request, 'dashboard/hrm/employee.html', context)
Edit part
def edit_employee(request, id):
instance = get_object_or_404(Employee, id=id)
form = EmployeeForm(request.POST or None, instance=instance)
if request.method == "POST" and form.is_valid():
employee = Employee.objects.get(id=id)
prev_username = employee.username
username = form.cleaned_data['username']
password = form.cleaned_data['password']
email = form.cleaned_data['email']
office_instance = OfficeSetup.objects.get(owner=request.user)
form = form.save(commit=False)
form.office = office_instance
# change username or password or email if admin has done the changes in
# those field
try:
user_instance = User.objects.get(username=prev_username)
user_instance.username = username
user_instance.set_password(password)
user_instance.email = email
form.save()
user_instance.save()
except User.DoesNotExist:
messages.error(request, "Following User Does Not Exist!")
except:
user = User.objects.create_user(
username=username, password=password, email=email)
form.save()
user.save()
messages.success(request, "Thank you")
return redirect('employee-list')
messages.warning(request, "Error")
context = {
'form': form
}
return render(request, 'dashboard/hrm/employee.html', context)
Screenshot is to make the flow or use-case clear
UPDATED CODE
def edit_employee(request, id):
instance = get_object_or_404(Employee, id=id)
form = EmployeeForm(request.POST or None, instance=instance)
if request.method == "POST" and form.is_valid():
employee = Employee.objects.get(id=id)
prev_username = employee.username
username = form.cleaned_data['username']
password = form.cleaned_data['password']
email = form.cleaned_data['email']
office_instance = OfficeSetup.objects.get(owner=request.user)
form = form.save(commit=False)
form.office = office_instance
# change username or password or email if admin has done the changes in
# those field
user, created = User.objects.get_or_create(username=prev_username)
if created:
user.set_password(password)
user.email = email
form.save()
user.save()
return redirect('employee-list')
user.set_password(password)
user.email = email
form.save()
user.save()
return redirect('employee-list')
messages.warning(request, "Error")
context = {
'form': form
}
return render(request, 'dashboard/hrm/employee.html', context)
The get_or_create method is made for cases like this. I'd refactor to do something like this:
user, created = User.objects.get_or_create(username=username)
if created:
# Fields to only populated on creation
user.password = password
...etc...
# Fields to update on creation or update
user.email = email
...etc...
user.save()
Details here: https://docs.djangoproject.com/en/1.11/ref/models/querysets/#get-or-create
Good luck!
When I am trying to register, I'm getting an error:
Forbidden (403)
CSRF verification failed. Request aborted.
My Code:
#csrf_protect
def register(request):
if request.method == 'POST':
form = RegistrationForm(request.POST, request.FILES)
if form.is_valid():
first_name = form.cleaned_data.get("firstname")
last_name = form.cleaned_data.get("lastname")
username = form.cleaned_data.get("username")
password = form.cleaned_data.get("password")
user = User.objects.create_user(username=username,password=password)
user.first_name = first_name
user.last_name = last_name
user.set_password(password)
user.is_active = True
user.save()
return HttpResponseRedirect('/home/')
else:
form = RegistrationForm()
return render_to_response('registration/registerHome.html',dict(form=form,
context_instance=RequestContext(request) ) )
my form.py
class RegistrationForm(forms.Form):
"""
A registration form to create normal user.
"""
firstname = forms.RegexField(regex=r'^\[a-zA-Z]+$',
widget=forms.TextInput(attrs={ 'required':True,
'max_length':30,
'autocomplete':'off',
'class':'form-control input-sm',
'placeholder':'First Name' }),
error_messages={ 'invalid': _("Only alphabets are allowed.") }
)
lastname = forms.RegexField(regex=r'^\[a-zA-Z]+$',
widget=forms.TextInput(attrs={ 'required':True,
'max_length':30,
'autocomplete':'off',
'class':'form-control input-sm',
'placeholder':'Last Name' }),
error_messages={ 'invalid': _("Only alphabets are allowed.") }
)
username = forms.RegexField(regex=r'^\w+$',
widget=forms.TextInput(attrs={'required':True,
'max_length':30,
'autocomplete':'off',
'class':'form-control input-sm',
'placeholder':'username'}),
error_messages={ 'invalid': _("Only [a-z A-Z 0-9 _] are allowed.") }
)
password = forms.CharField(widget=forms.PasswordInput(attrs={
'required':True,
'max_length':30,
'autocomplete':'off',
'class':'form-control input-sm',
'placeholder':'password',
'render_value':False })
)
def clean_username(self):
try:
user = User.objects.get(username__iexact=self.cleaned_data['username'])
except User.DoesNotExist:
return self.cleaned_data['username']
raise forms.ValidationError(_("Username already exists."))
class Meta:
model = User
my template.html
<form action="." method="post" role="form" id="register-form">
{% csrf_token %}
{{ form.as_p }}
<input type="submit" value="submit" />
</form>
Someone, please help me, why I'm getting an error. I am trying to solve this problem for 1 week and still getting the error. Please help me.
You should use render and add else
Then do like
def register(request):
if request.method == 'POST':
form = RegistrationForm(request.POST, request.FILES)
if form.is_valid():
first_name = form.cleaned_data.get("firstname")
last_name = form.cleaned_data.get("lastname")
username = form.cleaned_data.get("username")
password = form.cleaned_data.get("password")
user = User.objects.create_user(username=username,password=password)
user.first_name = first_name
user.last_name = last_name
user.set_password(password)
user.is_active = True
user.save()
return HttpResponseRedirect('/home/')
else:
return render(request, 'registration/registerHome.html',dict(form=form)))
else:
form = RegistrationForm()
return render(request, 'registration/registerHome.html',dict(form=form)))
You don't need to use the #csrf_protect decorator as long as the csrf middleware is added.The Middleware gives you blanket protection on all views - adding the decorator is redundant. The Django docs recommend using the Middleware over the decorator as it provides better protection.
Try after removing the decorator.
Try something like this. I remember sometime ago I had the same problem and declaring the c dictionary and passing it to the render_to_response solved my problem.
#csrf_protect
def register(request):
if request.method == 'POST':
# do your post stuff here
pass
else:
c = {}
c['form'] = RegistrationForm()
c['context_instance'] = RequestContext(request)
return render_to_response('registration/registerHome.html',c )
Try using https://docs.djangoproject.com/en/1.11/topics/http/shortcuts/#render
from django.shortcuts import render
#csrf_protect
def register(request):
if request.method == 'POST':
form = RegistrationForm(request.POST, request.FILES)
if form.is_valid():
first_name = form.cleaned_data.get("firstname")
last_name = form.cleaned_data.get("lastname")
username = form.cleaned_data.get("username")
password = form.cleaned_data.get("password")
user = User.objects.create_user(username=username,password=password)
user.first_name = first_name
user.last_name = last_name
user.set_password(password)
user.is_active = True
user.save()
return HttpResponseRedirect('/home/')
else:
form = RegistrationForm()
return render(request, 'registration/registerHome.html',dict(form=form) ) )
I am creating user authentication form, on entering data and submitting, I get this error:
AttributeError at /register/
'RegistrationForm' object has no attribute 'username'
at ` username=form.username,
I have checked all the solutions with the same problem and applied them but no one is solving it(like that is_valid()). how do I get it right? here is the code:
from django.http import HttpResponse
def register_page(request):
if request.method == 'POST':
form = RegistrationForm(request.POST)
if form.is_valid():
user = User.objects.create_user(
username=form.clean_data['username'],
password=form.clean_data['password1'],
email=form.clean_data['email'])
return HttpResponseRedirect('/register/success/')
else:
form = RegistrationForm()
variables = RequestContext(request, {
'form': form})
return render_to_response(
'registration/register.html',
variables)
def logout_page(request):
logout(request)
return HttpResponseRedirect('/')
def main_page(request):
return render_to_response(
'main_page.html', RequestContext(request))
def user_page(request, username):
try:
user = User.objects.get(username=username)
except:
raise Http404('Requested user not found.')
bookmarks = user.bookmark_set.all()
template = get_template('user_page.html')
variables = RequestContext(request, {
'username': username,
'bookmarks': bookmarks
})
output = template.render(variables)
return HttpResponse(output)
forms.py
import re
class RegistrationForm(forms.Form):
username = forms.CharField(label='Username', max_length=30)
email = forms.EmailField(label='Email')
password1 = forms.CharField(
label='Password',
widget=forms.PasswordInput()
)
password2 = forms.CharField(
label='Password (Again)',
widget=forms.PasswordInput())
def clean_password2(self):
if 'password1' in self.clean_data:
password1 = self.clean_data['password1']
password2 = self.clean_data['password2']
if password1 == password2:
return password2
raise forms.ValidationError('Passwords do not match.')
def clean_username(self):
username = self.clean_data['username']
if not re.search(r'^\w+$', username):
raise forms.ValidationError('Username .')
try:
User.objects.get(username=username)
except ObjectDoesNotExist:
return username
raise forms.ValidationError('Username is already taken.')
Its cleaned_data, not clean_data:
username = form.cleaned_data['username']
Do this for other form data as well, like password1 and email.
Some background in the reason for this can be found in Django documentation. Basically, the methods are called clean_fieldname but after cleaning the data is in cleaned_fieldname. Note the distinction.
Ive been trying to create a django project that has users and those users can add titles of books they have created. Only the user will be able to view the titles of his books. I was wondering how can I create a class in models.py, forms.py, & views.py that will tie the user and the titles of their books together. Here is what I have so far.
models.py
from django.db import models
from django.contrib.auth.models import User
class Scripter(models.Model):
user = models.OneToOneField(User)
name = models.CharField(max_length=30)
def __unicode__(self):
return self.name
class Title(models.Model):
author = models.ForeignKey(Scripter)
def __unicode__(self):
return self.script_title
forms.py
from django import forms
from django.contrib.auth.models import User
from django.forms import ModelForm
from scripters.models import Scripter, Title
class RegistrationForm(ModelForm):
username = forms.CharField(label=(u'User Name'))
email = forms.EmailField(label=(u'Email Address'))
password = forms.CharField(label=(u'Password'), widget=forms.PasswordInput(render_value=False))
password1 = forms.CharField(label=(u'Verify Password'), widget=forms.PasswordInput(render_value=False))
class Meta:
model = Scripter
exclude = ('user',)
def clean_username(self):
username = self.cleaned_data['username']
try:
User.objects.get(username=username)
except User.DoesNotExist:
return username
raise forms.ValidationError("User Name has been taken!")
def clean(self):
if self.cleaned_data['password'] != self.cleaned_data['password1']:
raise forms.ValidationError("The passwords did not match")
else:
return self.cleaned_data
class LoginForm(forms.Form):
username = forms.CharField(label=(u'Username'))
password = forms.CharField(label=(u'Password'), widget=forms.PasswordInput(render_value=False))
class CreateScript(ModelForm):
title = forms.CharField(label=(u'Script Title'))
class Meta:
model = Title
def clean_title(self):
title = self.cleaned_data['title']
return title
views.py
from django.http import HttpResponseRedirect
from django.contrib.auth.models import User
from django.contrib.auth.decorators import login_required
from django.shortcuts import render_to_response
from django.template import RequestContext
from scripters.forms import RegistrationForm, LoginForm, CreateScript
from scripters.models import Scripter, Title
from django.contrib.auth import authenticate, login, logout
def ScripterRegistration(request):
if request.user.is_authenticated():
return HttpResponseRedirect('/profile/')
if request.method =='POST':
form = RegistrationForm(request.POST)
if form.is_valid():
user = User.objects.create_user(username=form.cleaned_data['username'],
email = form.cleaned_data['email'],
password = form.cleaned_data['password']
)
user.save()
scripter = Scripter(user=user, name=form.cleaned_data['name'])
scripter.save()
return HttpResponseRedirect('/profile/')
else:
return render_to_response('index.html', {'form': form}, context_instance=RequestContext(request))
else:
form = RegistrationForm()
context = {'form': form}
return render_to_response('index.html', context, context_instance=RequestContext(request))
#login_required
def Profile(request):
if not request.user.is_authenticated():
return HttpResponseRedirect('/login/')
Scripter = request.user.get_profile
context = {'Scripter': Scripter}
return render_to_response('profile.html', context, context_instance=RequestContext(request))
def LoginRequest(request):
if request.user.is_authenticated():
return HttpResponseRedirect('/profile/')
if request.method == 'POST':
submit = LoginForm(request.POST)
if submit.is_valid():
username = submit.cleaned_data['username']
password = submit.cleaned_data['password']
scripter = authenticate(username=username, password=password)
if scripter is not None:
login(request, scripter)
return HttpResponseRedirect('/profile/')
else:
return HttpResponseRedirect('/login/')
else:
submit = LoginForm()
context = {'submit': submit}
return render_to_response('login.html',context, context_instance=RequestContext(request))
def LogoutRequest(request):
logout(request)
return HttpResponseRedirect('/login/')
#login_required
def NewScript(request):
if not request.user.is_authenticated():
return HttpResponseRedirect('/login/')
if request.method =='POST':
title_form = CreateScript(request.POST)
if title_form.is_valid():
title = User.objects.get_or_create(
Title = title_form.cleaned_data['title'],
)
title.save()
script = Title(script_title=title_form.cleaned_data['title'])
script.save()
return HttpResponseRedirect('/edit/')
else:
return render_to_response('NewScript.html', {'title_form': title_form}, context_instance=RequestContext(request))
else:
title_form = CreateScript()
context = {'title_form': title_form}
return render_to_response('NewScript.html', context, context_instance=RequestContext(request))
I think what you're asking is how do I get the list of titles that are owned by a specific user.
This is rather easy using a reverse relationship:
scripter.title_set.all()
Will get you all the books owned by an instance of Scripter.