I am using UserProfile to save some fields that I created. Its working fine. But I would like to create a new view to let user change (update) theses fields values. But, theses values arent being showing in form. Anyone have any idea how to fix it?
view.py
#login_required
def atualizar_cadastro_usuario(request):
if request.method == 'POST':
form = cadastrousuarioForm(request.POST,instance=request.user.get_profile())
if form.is_valid():
new_user = form.save()
return render_to_response("registration/cadastro_concluido.html",{})
else:
form = cadastrousuarioForm(request.POST,instance=request.user.get_profile())
return render_to_response("registration/registration.html", {'form': form})
form.py
class cadastrousuarioForm(UserCreationForm):
username = forms.EmailField(label = "Email",widget=forms.TextInput(attrs={'size':'60','maxlength':'75'}))
email = forms.EmailField(label = "Digite o Email novamente",widget=forms.TextInput(attrs={'size':'60','maxlength':'75'}))
nome = forms.CharField(label = 'Nome',widget=forms.TextInput(attrs={'size':'30','maxlength':'100'}))
cpf = BRCPFField(label='CPF')
data_nascimento=forms.DateField(widget=forms.DateInput(format = '%d/%m/%Y'), input_formats=('%d/%m/%Y',))
endereco = forms.CharField(label = 'Endereço',widget=forms.TextInput(attrs={'size':'30','maxlength':'100'}))
cidade = forms.CharField(label = 'Cidade')
estado = forms.CharField(widget=BRStateSelect(), label='Estado', initial = 'SP')
telefone = forms.CharField(label = "Telefone",widget=forms.TextInput(attrs={'size':'12','maxlength':'12'}))
escolaridade = forms.ChoiceField(choices=UserProfile.ESCOLARIDADE_ESCOLHAS)
profissao = forms.CharField(label = 'Profissão')
empresa = forms.CharField(label = 'Empresa',required=False)
receber_emails = forms.ChoiceField(choices=UserProfile.QUESTIONARIO_ESCOLHAS)
#captcha = CaptchaField(label = 'Digite as letras a seguir')
class Meta:
model = User
fields = ("username","email")
def save(self, commit=True):
user = super(cadastrousuarioForm, self).save(commit=False)
...
In bash, it works fine:
>>> from django.contrib.auth.models import User
>>> from cadastro.models import UserProfile
>>> u = User.objects.get(username='user#gmail.com')
>>> u.get_profile().telefone
u'123123455'
You need to change your model in the form from User to UserProfile. The form also needs to subclass ModelForm rather than UserCreationForm. Also, it looks like you're only using a subset of fields in your ModelForm (username and email). Finally, since you're using a ModelForm you don't need to define all of the model's fields in your form. Try changing your cadastrousuarioForm to the following:
class cadastrousuarioForm(ModelForm):
class Meta:
model = UserProfile
fields = ('username','email')
def save(self, commit=True):
user = super(cadastrousuarioForm, self).save(commit=False)
Related
I am trying to extend the Django User model by creating a user Profile model. When users register for the site, I want them to be able to select what class period they are in. To do this, I've tried to create a form that alters the User model, and a form that alters the Profile model. The problem is that when I try to put both forms into 'users/register.html' I am getting an error that says 'Anonymous User has to data _meta'. Below is my original code that only has the form for altering the User model in 'users/register.html'. How can I configure the registration so that users are able to save to the User and Profile model when they are first signing up for the site?
models.py
class Profile(models.Model):
'''
periods = [
('-','-'),
('1','1'),
('2','2'),
('3','3'),
('4','4'),
('6','6'),
('7','7'),
]
'''
user = models.OneToOneField(User,on_delete=models.CASCADE)
period = models.IntegerField(default=1)
first_name = models.CharField(max_length=100,default='Home')
last_name = models.CharField(max_length=100,default='Simpson')
def __str__(self):
return f'{self.user.username}'
forms.py
class UserRegisterForm(UserCreationForm):
email = forms.EmailField()
class Meta:
model = User
fields = ['username','email','password1','password2']
class UserProfileForm(forms.ModelForm):
periods = [
(1,1),
(2,2),
(3,3),
(4,4),
(6,6),
(7,7),
]
period = forms.ChoiceField(choices=periods)
first_name = forms.CharField(max_length=100)
last_name = forms.CharField(max_length=100)
class Meta:
model = Profile
fields = ['first_name','last_name','period']
signals.py
#receiver(post_save,sender=User)
def create_profile(sender,instance,created,**kwargs):
if created:
Profile.objects.create(user=instance)
#receiver(post_save,sender=User)
def save_profile(sender,instance,**kwargs):
instance.profile.save()
views.py
def login(request):
context = {
'title':'Login',
}
return render(request,'users/login.html',context)
def register(request):
if request.method == "POST":
form = UserRegisterForm(request.POST)
if form.is_valid():
email = form.cleaned_data.get('email')
email_domain = re.search("#[\w.]+", email)
if email_domain.group() == EMAIL_DOMAIN:
form.save()
username = form.cleaned_data.get('username')
messages.success(request,f'Account created for {username}! You are now able to sign in.')
return redirect('users-login')
else:
messages.error(request,f'Sorry. You are not authorized to register.')
else:
form = UserRegisterForm()
context = {
'title':'Register',
'form':form
}
return render(request,'users/register.html',context)
This is happening because you are putting both the forms in the register page . When you have not created any user so how you can create a profile and how would you be able to add or retrieve data from it?
Now the solution for that is ,
1 . You create a page for registering the user say "users/register.html" , when they successfully register there, create a signal for creating the Profile for him , then successfully log the user in . Then redirect the just registered user to the profile change page.
Take both the forms in the user register page but do not validate the profile_change form .Create the user in the view and then reference it to the profile_change_form .
A simple code bit for that .
def registerUser(request) :
if request.method == "POST" :
user_form = UserRegisterForm(request.POST)
if user_form.is_valid():
username = request.POST.get("username")
# fields you require
user = User(username = username , password = password)
user.save()
profile_field_objects = request.POST.get("profile_field_data")
profile = Profile(user = user , profile_field_objects = profile_field_objects)
profile.save()
# rest you can code
I have a model called KeyFormModel which has 2 fields "secret_key" and "primary_key", I pointed this model towards a form and called this form to a view and template. each user has exactly one primary_key and one secret_key, when I send this to model they are mixing with other keysets
this is my model
class KeyFormModel(models.Model):
username = models.ForeignKey(settings.AUTH_USER_MODEL,on_delete=models.CASCADE)
primary_key = models.CharField(max_length=200)
secret_key = models.CharField(max_length=200)
def __str__(self):
return username+"_keys"
class Meta:
verbose_name_plural = 'Keys'
this is my form
from ..models import KeyFormModel
from django import forms
from django.conf import settings
class KeyForm(forms.ModelForm):
primary_key = forms.CharField(required=True)
secret_key = forms.CharField(required=True,widget = forms.PasswordInput)
class Meta:
model = KeyFormModel
fields = ("username","primary_key","secret_key")
this is my view
#cache_control(no_cache=True, must_revalidate=True)
#login_required(login_url='../login')
def AccountView(request):
if(request.method == 'POST'):
form =KeyForm(request.POST)
if(form.is_valid()):
form.save()
else:
for msg in form.error_messages:
messages.error(request,f"{msg}")
form = KeyForm
return(render(request, 'accountView.html',context={"form":form}))
as you can see I am trying to add username from AUTH_USER_MODEL after logging into that account but failing miserably. please hlp
What worked out for me:
import User to models:
from django.contrib.auth.models import User
and in the specific model add user field:
user = models.ForeignKey(
User,
on_delete=models.CASCADE,
)
i found the answer
#cache_control(no_cache=True, must_revalidate=True)
#login_required(login_url='../login')
def AccountView(request):
keyforce=KeyFormModel.objects.filter(user=request.user)
if(keyforce):
return(render(request,'keyView.html',{"keys":keyforce}))
else:
if(request.method == 'POST'):
form = KeyForm(request.POST)
if(form.is_valid()):
primary_key = request.POST['primary_key']
secret_key = request.POST['secret_key']
new = KeyFormModel(primary_key=primary_key,
secret_key=secret_key, user=request.user)
new.save()
return(redirect("main:Account"))
else:
for msg in form.error_messages:
messages.error(request, f'{msg}')
else:
form = KeyForm
return(render(request, 'accountView.html', context={"form": form}))
I learned that the values to the models can be added through views itself,
all I did was something like this
after adding User to your model
in view create
form = yourModel(user = request.user)
voila its done
I am looking for some help in my first django app and I am new to programming. I have the below scenario:
Models:
class save_table(models.Model):
name=models.CharField(max_length=100)
UniqueuserID = models.CharField(max_length=7)
UserLocation = models.CharField(max_length=100)
UserLead = models.CharField(max_length=50)
def __str__(Self):
return self.UniqueuserID
class data_table(models.Model):
UniqueuserID = models.CharField(max_length=7)
name=models.CharField(max_length=100)
UserLocation = models.CharField(max_length=100)
UserLead = models.CharField(max_length=50)
Form:
class save_table_form(forms.ModelForm):
class Meta:
model = save_table
fields = ('UniqueuserID')
def __init__(self,*args,**kwargs):
super(save_table_form,self).__init__(*args,**kwargs)
Every user ID that the user will add to the form will have a respective data entry int he second model and I want to save that additional data along with the form. However I did not use a foreign key because I do not want the saved model data in the save_table to change based on the changes in the data_table. Can I add the additional data to the form before saving the form.
if form.is_valid():
form.save()
Please help..
Yes you can add aditional data when saving the form!
overwrite the saving methoud in class save_table_form:
like this :
class save_table_form(forms.ModelForm):
def save(self, commit=True):
user_id = self.cleaned_data['id']
user_photo = self.cleaned_data['photo']
user_password = self.cleaned_data['password1']
user = SysUser.objects.get(pk=user_id)
user.username = self.cleaned_data['username']
if user_password:
user.set_password(self.cleaned_data['password1'])
user.first_name = self.cleaned_data['first_name']
user.mobile = self.cleaned_data['mobile']
user.office_id = self.cleaned_data['office_id']
if user_photo:
user.image = user_photo
user.save()
user.user_permissions.clear()
user.user_permissions.add(*self.cleaned_data['user_permissions'])
print('data is saving')
return user
models.py:
from django.db import models
from django.contrib.auth.models import User as BaseUser
CHOICE_GENDER = ((1, 'Male'), (2, 'Female'))
class Location(models.Model):
city = models.CharField(max_length=75)
country = models.CharField(max_length=25)
def __unicode__(self):
return ', '.join([self.city, self.state])
class Users(BaseUser):
user = models.OneToOneField(BaseUser, on_delete=models.CASCADE)
gender = models.IntegerField(choices=CHOICE_GENDER)
birth = models.DateField()
location = models.ForeignKey(Location)
class Meta:
ordering = ('user',)
forms.py:
from django.contrib.auth.forms import UserCreationForm
from django import forms
from .models import Users, Location, CHOICE_GENDER
class LocationForm(forms.ModelForm):
city = forms.CharField(max_length=75)
country = forms.CharField(max_length=25)
class Meta:
model = Location
fields = ('city', 'country',)
class RegistrationForm(UserCreationForm):
email = forms.CharField(max_length=75)
first_name = forms.CharField(max_length=30)
last_name = forms.CharField(max_length=30)
gender = forms.ChoiceField(choices=CHOICE_GENDER)
birth = forms.DateField()
location = LocationForm()
class Meta:
model = Users
fields = ('username', 'email', 'first_name', 'last_name', 'gender', 'birth')
def save(self, commit=True):
user = super(RegistrationForm, self).save(commit=False)
user.email = self.cleaned_data['email']
user.first_name = self.cleaned_data['first_name']
user.last_name = self.cleaned_data['last_name']
user.gender = self.cleaned_data['gender']
user.birth = self.cleaned_data['birth']
if commit:
user.save()
return user
This code in forms.py doesn't work. It doesn't save LocationForm due to these errors:
country - This field is required.
city - This field is required.
I've certainly did something wrong here, but I don't know exactly what. I admit that I've jumbled the code in forms.py, especially in the save method for RegistrationForm because I don't know how to properly invoke the creation of another form and how to make a connection between two of them. I searched the Internet but I couldn't find precise info about that, so I tried to improvise but I've failed, unfortunately.
Could someone help me with this? Thanks in advance!
UPDATE: views.py (currently):
def signup(request):
if request.method == "POST":
reg_form = RegistrationForm(request.POST)
loc_form = LocationForm(request.POST)
if reg_form.is_valid() and loc_form.is_valid():
location = loc_form.save()
reg_form.cleaned_data['location_id'] = location.id
registration = reg_form.save()
else:
pass
else:
reg_form = RegistrationForm()
loc_form = LocationForm()
return render(request, 'signup.html', {'loc_form': loc_form, 'reg_form':reg_form})
I've also modified forms.py but I still got the error from above.
Instead of using LocationForm inside RegistrationForm you can handle them seprately in your views.py it will result in a cleaner code and easy to handle.
if request.method == "POST":
reg_form = RegistrationForm(request.POST)
loc_form = LocationForm(request.POST)
if reg_form.is_valid() and loc_form.is_valid():
# since in your case they are dependent on each other
# save location form and get location object
location = loc_form.save()
# now you can use it in your reg_form
reg_form.cleaned_data['location_id'] = location.id
registration = reg_form.save()
else:
# no need to handle this case only for explanation
# use the forms, with valid post data initialized
# at the start of current if block
pass
else:
# create new forms for location and registration
reg_form = RegistrationForm()
loc_form = LocationForm()
return render(request, 'signup.html', {'loc_form': loc_form, 'reg_form':reg_form})
You can read here more on how to handle more than one nested forms in django docs.
I want to convert text to sha1 in django. But, i'm not find the way how to do it if field attribut wrapped by the form.
This is my views:
def ubah_password_email(request, pk):
#cek session
if 'username' in request.session and request.session['hak_akses'] == 'user':
user = get_object_or_404(User, pk=pk) #ambil id dengan get
profile = UserProfile.objects.filter(user=user).first()
email_form = EmailForm(data=request.POST, instance=profile) #gunakan instance untuk mengambil data yang sudah ada
users = User.objects.all()
if request.POST:
if email_form.is_valid():
email = email_form.save(commit=False)
email.save()
return redirect('home')
else:
email_form = EmailForm(instance=profile)
data = {
'email_form': email_form,
'object_list': users,
}
return render(request, 'ubah_password_email.html', data)
else:
return HttpResponseRedirect('/simofa/logout')
This is my model
class UserProfile(models.Model):
user = models.OneToOneField(User) #digunakan untuk relasi ke model User (default) alias UserProfile adalah sebagai extending model
CATEGORY_CHOICES = (
('admin','Admin'),
('user','User'),
)
hak_akses = models.CharField(max_length=100, choices = CATEGORY_CHOICES)
password_email = models.CharField(max_length=100, blank=True)
password_pckelas = models.CharField(max_length=100, blank=True)
# Override the __unicode__() method to return out something meaningful!
def __unicode__(self):
return self.user.username
This is my forms
class EmailForm(forms.ModelForm):
password_email = forms.CharField(widget=forms.PasswordInput())
class Meta:
model = UserProfile
fields = ('password_email',)
i'm trying using this and this reference. But, i still can't convert text to sha1?
I'm very grateful for your input. So, please help me :)
I'm not sure why you want or need a second password field. But make_password allows you to generate a hashed password:
from django.contrib.auth.hashers import make_password
Docs: https://docs.djangoproject.com/en/1.7/topics/auth/passwords/#django.contrib.auth.hashers.make_password
Source: https://github.com/django/django/blob/master/django/contrib/auth/hashers.py#L58