i need to create group seekers and user register he has to automatically add to seekers
models.py
class Seeker(models.Model):
user = models.OneToOneField(User)
birthday = models.DateField()
name = models.CharField(max_length=100)
def __unicode__(self):
return self.name
forms.py
this is the default user for storing the userid & password for my application
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 = Seeker
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.")
def clean(self):
if self.cleaned_data['password'] != self.cleaned_data['password1']:
raise forms.ValidationError("The Password did not match please try again.")
return self.cleaned_data
views.py
i am using default user for creating the user
def SeekersRegistration(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()
seekers = Seeker(user =user, name = form.cleaned_data['name'],birthday = form.cleaned_data['birthday'])
seekers.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))
Use signals
from django.contrib.auth.models import User
from django.db.models.signals import post_save
from django.dispatch import receiver
#receiver(post_save, sender=User)
def add_user_to_specific_group(instance, created, **kwargs):
if created:
# assign user to group
Related
I am trying to create an address book website where logged in user is able to fill in a form and store contact information. I was able to implement the login and logout functionality. But the problem is that I am not able to set the username to current logged in user. Here is what I have implemented so far:
Models.py
class UserProfileInfo(models.Model):
user = models.OneToOneField(User,on_delete=models.CASCADE,primary_key=True)
#additional
def __str__(self):
return self.user.usernname
class UserContacts(models.Model):
current_user = models.ForeignKey(User,on_delete=models.CASCADE)
first_name = models.CharField(max_length = 150)
last_name = models.CharField(max_length = 150)
phone_number = models.CharField(max_length = 150)
email_address = models.CharField(max_length = 150)
street_address = models.CharField(max_length = 350)
def __str__(self):
return '{}'.format(self.first_name)
Forms.py
class UserForm(forms.ModelForm):
password = forms.CharField(widget = forms.PasswordInput())
class Meta():
model = User
fields = ('username','email','password')
class UserContactForm(forms.ModelForm):
class Meta():
model = UserContacts
fields = "__all__"
views.py:
#login_required
def new_contact(request):
form = UserContactForm()
current_user = request.user.get_username()
user = User.objects.filter(username=current_user).first()
output = UserContacts.objects.filter(current_user_id=user.id).first()
if request.method == "POST":
form = UserContactForm(request.POST)
if form.is_valid():
form.save(commit=True)
return index(request)
else:
print('Error Form Invalid')
return render(request,'basic_app/contact.html',{'form':form})
Here is how the output looks like when the logged in user tries to enter contact information details:
Updating contact screenshot. As you can see the current user has to select his username to fill out the contact information.
How to overcome this and by default set the username in the form to the current logged in user
Change your UserContactForm to include an extra perameter in __init__, and set the initial value on the user field:
class UserContactForm(forms.ModelForm):
class Meta():
model = UserContacts
fields = "__all__"
def __init__(self, *args, **kws):
# To get request.user. Do not use kwargs.pop('user', None) due to potential security hole
self.user = kws.pop('user')
super().__init__(*args, **kws)
self.fields['user'].initial = self.user
Then change you view to add in the request.user to the form construction:
#login_required
def new_contact(request):
form = UserContactForm(user=request.user)
current_user = request.user.get_username()
user = User.objects.filter(username=current_user).first()
output = UserContacts.objects.filter(current_user_id=user.id).first()
if request.method == "POST":
form = UserContactForm(request.POST, user=request.user)
if form.is_valid():
form.save(commit=True)
return index(request)
else:
print('Error Form Invalid')
return render(request,'basic_app/contact.html',{'form':form})
You could probably remove the:
current_user = request.user.get_username()
user = User.objects.filter(username=current_user).first()
output = UserContacts.objects.filter(current_user_id=user.id).first()
Basically i am sending email to user with password and username. I can get the username using self.cleaned_data.get('email'). But the problem is that i dont know how to get password from view which i am setting random password in views. So please help me to get that random password from views.py to forms.py in def send_email
Forms.py
class UserRegisterForm(forms.ModelForm):
email = forms.EmailField()
first_name = forms.CharField()
last_name = forms.CharField()
class Meta:
model = User
fields = ['first_name','last_name', 'email']
def send_email(self):
name = self.cleaned_data.get('first_name')
username = self.cleaned_data.get('email')
to_email = self.cleaned_data.get('email')
password1 = # Get Password from view
Views.py
def register(request):
if request.method == 'POST':
ur_form = UserRegisterForm(request.POST)
pr_form = UserProfileForm(request.POST, request.FILES)
user_role = 0
if ur_form.is_valid() and pr_form.is_valid():
new_user = ur_form.save(commit=False)
new_user.username = new_user.email
password = User.objects.make_random_password() # Pass This to Form send_email
new_user.set_password(password)
new_user.save()
Pass the random password to the form at the time of form initialization and handle that in your UserRegisterForm form by overriding the __init__() method
Try this
# form.py
class UserRegisterForm(forms.ModelForm):
def __init__(self, *args, **kwargs):
self._pwd = kwargs.pop('pwd', None)
super().__init__(*args, **kwargs)
email = forms.EmailField()
first_name = forms.CharField()
last_name = forms.CharField()
class Meta:
model = User
fields = ['first_name', 'last_name', 'email']
def send_email(self):
name = self.cleaned_data.get('first_name')
username = self.cleaned_data.get('email')
to_email = self.cleaned_data.get('email')
password1 = self._pwd # access your password from view
# views.py
def register(request):
if request.method == 'POST':
random_password = generate_your_random_password() # generate password here
ur_form = UserRegisterForm(request.POST, pwd=random_password)
pr_form = UserProfileForm(request.POST, request.FILES)
user_role = 0
if ur_form.is_valid() and pr_form.is_valid():
new_user = ur_form.save(commit=False)
new_user.username = new_user.email
new_user.set_password(random_password) # set the random password here
new_user.save()
# your code ....
I use a custom form inherited from django's UserCreationForm to add user. How ever i have to set different initial value for username field.It works perfectly but after hitting save button the user get saved with a different username than the initial value shown in the form.You can find the code below
from django.contrib.auth.forms import UserCreationForm
class AdminUserCreationForm(UserCreationForm):
"""
AdminForm for creating an instance of custom USER_MODEL.
"""
email = forms.EmailField(required=True)
class Meta:
model = User
fields = ("username", "email")
field_classes = {'username': UsernameField}
def __init__(self, *args, **kwargs):
super().__init__(*args, **kwargs)
self.initial['username'] = random_username_generator()
self.fields['username'].disabled = True
self.fields['password1'].required = False
self.fields['password2'].required = False
def clean_username(self):
username = self.cleaned_data['username'].lower()
try:
User.objects.get(username=username)
except User.DoesNotExist:
return username
raise forms.ValidationError('A user with username {} already exists'.format(username))
def clean_email(self):
email = self.cleaned_data['email'].lower()
try:
User.objects.get(email=email)
except User.DoesNotExist:
return email
raise forms.ValidationError('A user with email {} already exists'.format(email))
def save(self, commit=True):
import ipdb; ipdb.set_trace();
user = super(AdminUserCreationForm, self).save(commit=False)
# user = self.instance
qb = QuickBlox()
qb_password = reset_password_generator()
user.qb_password = qb_password + 'vx'
user.save()
attempt = LoginAttempts()
attempt.user = user
attempt.save()
send_invite_mail(user)
return user
I am using Django 1.5. I am a custom User model like this:
class User(AbstractBaseUser):
#id = models.IntegerField(primary_key=True)
#identifier = models.CharField(max_length=40, unique=True, db_index=True)
username = models.CharField(max_length=90, unique=True, db_index=True)
create_time = models.DateTimeField(null=True, blank=True)
update_time = models.DateTimeField(null=True, blank=True)
email = models.CharField(max_length=225)
#password = models.CharField(max_length=120)
external = models.IntegerField(null=True, blank=True)
deleted = models.IntegerField(null=True, blank=True)
purged = models.IntegerField(null=True, blank=True)
form_values_id = models.IntegerField(null=True, blank=True)
disk_usage = models.DecimalField(null=True, max_digits=16, decimal_places=0, blank=True)
objects = UserManager()
USERNAME_FIELD = 'email'
class Meta:
db_table = u'galaxy_user'
I have a custom authentication:
class AuthBackend:
def authenticate(self, username=None, password=None):
if '#' in username:
kwargs = {'email': username}
else:
kwargs = {'username': username}
try:
user = User.objects.get(**kwargs)
if user.check_password(password):
return user
except User.DoesNotExist:
return None
def get_user(self, user_id):
try:
return User.objects.get(pk=user_id)
except User.DoesNotExist:
return None
Even after entering the correct username and password check_password() always returning false so that I can't login. I tried that in terminal too:
user.check_password(password)
is always returning False.
#views.py:
def login_backend(request):
if request.method == 'POST':
username = request.POST['username']
password = request.POST['password']
user = authenticate(username=username, password=password)
state = "Username or Password Incorrect!"
if user is not None:
login(request, user)
return HttpResponseRedirect('/overview/')
else:
return render_to_response('login_backend.html', {'state':state}, context_instance=RequestContext(request))
else:
return render_to_response('login_backend.html', context_instance=RequestContext(request))
The problem is that when you create your CustomUser, you save the password in open-way(without hashing). Can you give me your RegistrationForm code?
In my case:
# forms/register.py
class RegistrationForm(forms.ModelForm):
"""
Form for registering a new account.
"""
class Meta:
model = CustomUser
fields = ['username', 'password', 'email']
Register-handler:
# views.py
def register(request):
"""
User registration view.
"""
if request.method == 'POST':
form = RegistrationForm(data=request.POST)
if form.is_valid():
user = form.save() # Save your password as a simple String
return redirect('/')
else:
form = RegistrationForm()
return render(request, 'news/register.html', {'form': form})
So when you try to login:
if user.check_password(password):
return user
check_password always returns False.
Solution:
To set password properly, you should redefine save() method in RegistrationForm:
# forms/register.py
class RegistrationForm(forms.ModelForm):
"""
Form for registering a new account.
"""
class Meta:
model = CustomUser
fields = ['username', 'password', 'email']
def save(self, commit=True):
user = super(RegistrationForm, self).save(commit=False)
user.set_password(user.password) # set password properly before commit
if commit:
user.save()
return user
Or simply change handler:
def register(request):
"""
User registration view.
"""
if request.method == 'POST':
form = RegistrationForm(data=request.POST)
if form.is_valid():
user = form.save(commit=False)
user.set_password(request.POST["password"])
user.save()
return redirect('/')
else:
form = RegistrationForm()
return render(request, 'news/register.html', {'form': form})
I have created a user registration view and this is it:
def register(request):
if request.method == 'POST':
data = request.POST.copy() # so we can manipulate data
# random username
data['username'] = hashlib.md5( data['email'] ).hexdigest()
data['username'] = data['username'][0:30]
#data['username'] = ''.join([choice(letters) for i in xrange(30)])
form = RegisterForm(data)
if form.is_valid():
new_user = form.save()
#UserProfile.objects.create(user=new_user)
return HttpResponse("Thanks for Registering")
else:
form = RegisterForm()
return render_to_response("CTUser/register.html", { 'form': form, })
When I uncommented the UserProfile line:
#UserProfile.objects.create(user=new_user)
the email and password are saved correctly, but when It is there, all the info is erased. Am I doing something wrong here?
here is the UserProfile classs:
class UserProfile(User):
user = models.OneToOneField(User)
#user = models.ForeignKey(User, unique=True)
#profile sub URL
pagelink = models.CharField(max_length=40)
#one or many albums
albums = models.ManyToManyField(Album)
UPDATE(10/19/11):
Here is the registration form function:
class RegisterForm(UserCreationForm):
email = forms.EmailField(label = "Email Address", max_length=75)
class Meta:
model = User
#exclude = ['username',]
fields = ("username", "email")
def clean_email(self):
email = self.cleaned_data["email"]
try:
user = User.objects.get(email=email)
raise forms.ValidationError("This email address already exists. Did you forget your password?")
except User.DoesNotExist:
return email
def save(self, commit=True):
user = super(UserCreationForm, self).save(commit=False)
user.set_password(self.cleaned_data["password1"])
user.email = self.cleaned_data["email"]
user.is_active = True # change to false if using email activation
if commit:
user.save()
return user
Check if new_user contains all data you want to save. Paste RegisterForm code.
EDIT
try to change:
user = super(UserCreationForm, self).save(commit=False)
into
user = super(RegisterForm, self).save(commit=False)