last day (15 days later) » 

3:16 PM
0
Q: How create a user and a profile with a single form in Django?

João de SousaI have created a Clients model in models.py that is intended to be a Client (user) Profile. class Clients(models.Model): user = models.OneToOneField(User, on_delete=models.CASCADE) first_name = models.CharField(max_length=30, verbose_name="Primeiro Nome") last_name = models.CharField...

 
If you google your question, you'll find this tutorial which shows exactly what you need: Subclass the UserCreationForm (from django.contrib.auth.forms) so that all the functionality to create a user is already there.
 
@dirkgroten I have followed that tutorial, but the data doesn't get saved.
 
But that's not the code you're showing here. Subclassing the UserCreationForm is the correct approach, so go back to that, write the code as shown in the tutorial and edit your question with that code. The tutorial actually says that the form won't save the extra fields automatically. You need to do that in the view (I would actually do it in the form's save() method)
 
@dirkgroten I followed the tutorial again. I can now save the user, but all other fields get passed empty. I update the question.
 
show us your view
 
3:16 PM
@dirkgroten just added it
 
it saves the email, first_name and last_name, right?
on the User model
User model already has fields first_name, last_name, email, so you don't need them on the Clients model
 
So, I only need to keep it in my forms.py?
 
address, nif and mobile must be saved on the Clients model: user.clients.nif = form.cleaned_data['nif']
when you save the user the first time, the Clients is created because of your signal handlers, so you can just use it.
you need them in fields = ('email', 'first_name', 'last_name', ...) on your form, I think that should be enough to save them when you save the form. But remember, they are saved on the User so you can remove these fields from Clients model.
 
This seems like a simple thing, but I'm new to Django and coding, so sorry my ignorance.

I can delete email, first_name and last_name from my Clients model because User already has them.
Then, in my forms.py, I don't need to change anything.
 
wait let me check something
Yes, you can remove them from Clients model. And you can remove them from your form (only keep them in the fields = (...) list).
If you want to change the way they render, then you can override the labels for example in Meta. This UserCreationForm is a ModelForm for the User object, so it knows everything about User. To override the fields, look at this. It shows you how to override the label for example.
Then look at my answer. You were doing user.nib = form.cleaned_data['nib'] but that doesn't do much because user doesn't have a field nib to save.
The tutorial does: user.profile.date_of_birth = ... see the profile? That's your clients.
Note: I don't like the fact that your model is called Clients. It should be Client. That way the user attribute is client.
Always use singular for your models.
 
3:38 PM
About the model name, I know, I have to change it
I tried your code, but now it's not saving anything.
My views look like this right

def signup(request):
if request.method == 'POST':
form = SignUpForm(request.POST)
if form.is_valid():
user = form.save()
user.refresh_from_db()
user.clients.address = form.cleaned_data.get('address')
user.clients.nif = form.cleaned_data.get('nif')
user.clients.mobile = form.cleaned_data.get('mobile')
user.save()
raw_password = form.cleaned_data.get('password1')
user = authenticate(username=user.username, password=raw_password)
login(request, user)
return redirect('clientes')
 
It redirects to 'clientes'?
 
No, reloads the form page
So, I think it runs the else statement
 
or the form is not valid
are you showing the form errors in your template?
Do you see a POST request in your console? is your form submitted using POST?
 
So, I had accidently deleted POST method on the form
But now, it creates the user, but not the data in the Clients model. As it also returns "UNIQUE constraint failed: backend_clients.nif" when I submit the form.
 
You need to add def clean_nif(self) method in your form to validate it's unique.
Because you set it as primary_key
I wouldn't do that by the way (don't set it as primary_key, set it as unique on the model)
Because your form isn't a ModelForm for Clients, it doesn't know that nif should be unique
 
3:53 PM
I am using it as a primary key because I have a details page for each client, where it grabs the NIF, clientes/<int:nif>, and shows that client info
 
that's not a reason. You can use any unique field for that. So setting it to unique=True would serve the same purpose. You can still fetch an object using the nif.
 
Oh ok, if I change it to unique=True, do I still need to add the def clean_nif(self)=
?
 
yes, because your form isn't related to the model
 
Ok, now for some reason I am back at staying in the form without anything being added
I checked and it is sending the POST request
 
so this means the form is not valid
are you displaying the form errors in your template?
start by adding {{ form.errors }} somewhere (this won't be user-friendly, you should display the errors for each field at the right place, but it helps debug for now)
 
4:05 PM
Ok, that's brilliant. I was using passwords too similar to the user.
Now, I'm back to the "UNIQUE constraint failed: backend_clients.nif", which as you said I need to fix in the forms.py. I am just trying to understand how I integrate it.
 
if you add def clean_nif(self): nif = self.cleaned_data['nif']; <check another Clients with same nif doesn't exist in the database>; return nif that should cover that.
Look at here for an example, which shows how to raise the validation error.
 
I think I am just being dumb now, I added this before class Meta

def clean_nif(self):
nif = self.cleaned_data['nif'];

return nif
 
4:20 PM
where do you check that nif isn't a duplicate?
something like if Clients.objects.filter(nif=nif).exists(): raise ValidationError(...)
 
Ok, now it's creating both the user and the Client. But I get a "'User' object has no attribute 'profile'" page and none of the date is passed to the Client, only associates the user.
I think that it might have something to do with " instance.profile.save()" on my models.py
 
yeah that's wrong, it should be instance.clients.save()
But that's not going to work anyway because you don't set 'nif' is 'nif' is the primary key
that's why you should make this field unique=True and null=True
 
I already made it unique=True
 
also null=True
otherwise django can't create an empty clients
if I were you I wouldn't do this at all. Remove the signal. If the only way to create a user is via the signup form anyway, you know for sure the clients is created with a nif.
create it in your view instead of creating it in the post_save signal
The only reason why you see so many tutorials that create an empty profile is because that way the profile is optional, the user can edit it on their profile page. But in your case you don't want it optional, since a user must have a nif.
 
4:37 PM
Everythink is working now, no errors. But when I go to the admin page, the Client created has no address, mobile, or nif
It's empty
 
updated my answer. Either do profile = user.clients and then assign all the values and save the profile, or add the post_save signal which saves the profile (instance.clients.save()) each time the user is saved and do user.save() instead of user.clients.save().
actually using profile doesn't really matter. You were just saving the user but not the user.clients.
 
It works! If don't want to login in the account that was just created, can I just remove "login(request, user)"?
 
yep
also remove the two line to authenticate, that doesn't make sense to me.
why authenticate the user if he just created the password
it produces an unnecessary extra query to the db
 
5:01 PM
Ok, just one question and I promise not to bother you anymore. I have a page that lists all clients. I do I pass the variables now that the name and email are on User and mobile and nif on Clients?
I tried this but I can't pass two variables:
def clients(request):
u = User.objects.all()
cs= Clients.objects.all()
context= {'u': u, 'cs' : cs}
 
5:14 PM
you're passing a list of clients, if you loop over them, let's say you call each particular client c, then c.user.email and c.user.first_name are the ways to access those values.
or vice versa, if you have a user object then user.clients.nif is the nif of the user. you always have to access via the model.
you could define a @property on Clients that returns self.user.email if you don't want to remember all the time to go via the user.
 
You are amazing. Thank you so much for spending two hours helping me!
 
you're welcome
 

last day (15 days later) »