What would be the steps to create a user profile other than the administrator user please, I am a newbie. I leave the model class of which I want to be a user profile
from django.contrib.auth.models import User
user = models.OneToOneField(User, ondelete=models.CASCADE)
Add this field to the model.
If you are using Django's auth user registration form then, while registering new user in views.py:
form = UserRegistrationForm(request.POST)
if form.is_valid():
instance = form.save()
apoderado = Apoderado()
apoderado.user = instance
apoderado.other_fields = form.cleaned_data['other_fields']
apoderado.save()
This will create new user with extra fields. This is a simple trick but, if any error occurs then only half of data will be stored. If you want to go for extra, use Django signals.
Related
I was looking for solution for my problem here, but it didnt solve my problem.
I want to create user's profile while their signing up.
To signup I use CreateView
class UserRegisterView(generic.CreateView):
form_class = SignUpForm
template_name = 'registration/register.html'
success_url = reverse_lazy('login')
#this method doesn't work and I get
# `Profile.user" must be a "User" instance`
def form_valid(self,form):
Profile.objects.create(user=self.request.user)
My Profile model looks like:
class Profile(models.Model):
user = models.OneToOneField(User, on_delete=models.CASCADE)
#rest of fields like bio, social urls etc
My main point is to automatically create user's profile when their create their account.
What is the best way to solve this?
I will suggest to avoid using signals, since you have a form.
self.request.user will return an user object only when an user is logged in using any form of authentication (Session, token etc.)
def form_valid(self,form):
user = form.save()
Profile.objects.create(user=user)
return super(UserRegisterView, self).form_valid(form)
I am trying to make a signup interface in Django. at first, I have created a form using Django user creation form along with two extra fields. but whenever I submit the form I can not find the data of extra field.
here is the code for form creation:
from django import forms
from django.contrib.auth.models import User
from django.contrib.auth.forms import UserCreationForm
class UserSignUp(UserCreationForm):
email=forms.EmailField()
age=forms.CharField()
adress=forms.CharField()
class meta:
model=User
fields=['username','password1','password2','email','age','adress']
and here is the view for signup validation
def signupuser(request):
if request.method=="POST":
form=UserSignUp(request.POST)
if form.is_valid():
form.save()
return render(request,'diabetes/home.html')
else:
form=UserSignUp()
return render(request,"diabetes/signupuser.html",{'form':form})
now, what should I do?
You are trying to save fields which aren't on the model.
The defautl django.contrib.auth.models.User has only the fields:
username
password
email
first_name
last_name
The UserCreationForm has the "additional"/changed fields:
password1
password2
But the fields age, address aren't on the User model and therefore nowhere saved.
You can either extend the existing User model or use a custom user model
I search Django-way to do some non tipical feature (I think). My env is Django 2.0.2, PostgreSQL 9.6 and Python 3.6.4. So, I have model and form like:
# ./app/models.py
from users.models import User # custom user model
class SubscribeModel(models.Model):
user = models.ForeignKey(User, on_delete=models.CASCADE)
phone = models.CharField(max_length=80)
# ./app/forms.py
class SubscribeForm(forms.Form):
phone = forms.EmailField(label='Phone Number', max_length=100)
Also, my view for this model like:
# ./app/views.py
from django.contrib.auth.mixins import LoginRequiredMixin
from users.models import User
class SubscribeView(LoginRequiredMixin, View):
login_url = '/login/'
redirect_field_name = 'redirect_to'
template_name = 'app/subscribe.html'
form_class = SubscribeForm
def post(self, request):
user = get_object_or_404(User, id=request.user.id)
form = self.form_class(request.POST, instance=user)
if form.is_valid():
form.save()
return redirect('/')
return render(request, self.template_name, {'client': user, 'form': form})
Would be great to understand what to do that logic after save form:
Anonymous user fill the form and click Save;
He is redirecting to login page (because LoginRequiredMixin);
After enter to the site, all data which he filled — saved to his account (automatically).
This feature we can see when online shopping: we choose goods, add to
our cart and only later, site ask us for login to site, if we are not (for save our order).
I think, my question solve saving data to request.session and re-save to DB after logged in, but I have no idea how to do that on my code and is this correctly? I am newbie in Django... yet!
Actually using request.session to store the data without saving it to the database is one approach, you can eighter save it to the localStorage or sessionStorage if you are developing mainly javascript AJAX frontent. But if you render every view with django then is using request.session better for you. Consider storing ids of the objects in the request.session in array and then use it as you want, remember to seralize it to JSON (json.dumps(list of ids)) before assigning it to the request.session.
I need two extra fields for the user data so I followed the official django docs Extending the existing User model, the admin form for users works fine but I have a UserCreationForm and I want to add the two extra fields in that form too, already tried to use two forms, the UserCreationForm and the form for my extended user model but I can't get the id of the UserCreationForm to fill the user_id of my extended user model so I search how to use a signal to do that like the django docs recommend and find this Django Signals: create a Profile instance when a new user is created but that only fill the user_id of my extended user model that is the OneToOneField but not the two extra fields.
sorry for my bad english.
I need to run but here's a quick implementation. It needs some tweaks apparently but should get you started:
# this is your model form for extended OneOnOne with user
class ExtendedForm(forms.ModelForm):
model = ExtendedModel
# temporary exclude user field to pass the validation
exclude = ('user')
def create_user(request):
user_form = UserForm(request.POST or None)
extra_form = ExtendedForm(request.POST or None)
if user_form.is_valid() and extra_form.is_valid():
# create a new user first
new_user = user_form.save()
# create an object in memory but not save it
new_extended_obj = extra_form.save(commit=False)
# assign the user to the extended obj
new_extended_obj.user = new_user
# write to database
new_extended_obj.save()
Let's say you have a django model with a OneToOne / Unique ForeignKey relationship with a User, as show on the Django documentation on how to create a UserProfile.:
Now let's say you have a view method that takes a request you can get a user from. What is the best way to query for the profile associated with that user?
from django.contrib.auth.models import User
# sample user profile model associated with user
class UserProfile(models.Model):
likes_spam = models.BooleanField()
user = models.OneToOneField(User)
#view method
def forward_to_practice_home(request):
user = request.user
profile_for_user = #insert code here that would get the profile for that user
related_names are very helpful. If you change your user profile definition to:
class UserProfile(models.Model):
likes_spam = models.BooleanField()
user = models.OneToOneField(User, related_name='profile')
then you can use profile as follows:
def forward_to_practice_home(request):
user = request.user
profile_for_user = user.profile
UserProfile.objects.get(user=user)
You may use a special method called get_profile()
profile_for_user = user.get_profile()
Be reminded that you have to set the AUTH_PROFILE_MODULE in the settings.py
However, this is deprecated in Django 1.5 because it adds the support of user model customization