ModelForm isnt working

What does the view look like now?


def register_view(request):
    if request.user.is_authenticated:
        return redirect('home:profile')
    else:
        form = CreateUserForm

        if request.method == 'POST':
            form = CreateUserForm(request.POST)
            if form.is_valid():
                account = form.save(commit=False)
                account.user = request.user
                account.save()

                messages.success(request, 'Account wurde erstellt')

                return redirect('home:login')

        context = {'form': form}
        return render(request, 'home/register.html', context)

Missing the parens here - but that’s only going to affect a GET on this view, which doesn’t necessarily create a problem if your form is being submitted to this view from a different page.

Other than that, this should be working. What isn’t working, and how are you verifying that?

in my sqlite interface thing I can see the prenames as entered in the form but the user_id (on the right side) are NULL but in the register view I’ve set the user. And thanks for the parens thing, fixed it.

Ahh… sqlite, ok.

So, what you’re going to want to do here is initialize your form on your GET to the existing instance if one exists. You’ll want to ensure that this does an update rather than an insert in that case.

(You could also try using account.user = request.user.id, but that’s not necessarily going to solve the root issue here of trying to save a second row with the same user_id.)

Also, it might make the errors more apparent if you remove the null=False constraint on the user column.

tried the thing with the id’s, doesn’t change anything. And the Null=False isnt there anymore I removed it like 4 versions ago

Ok, how did we get from working with the AccountInfoPrenameForm to CreateUserForm? CreateUserForm is the wrong form for creating an account object.

yeah the Account Model is my customized User Model which has a OneToOneField

from django.db import models
from django.contrib.auth.models import User

class Account(models.Model):
    user = models.OneToOneField(User, on_delete=models.CASCADE)
    prename = models.CharField(max_length=20, null=True)
    surname = models.CharField(max_length=40, null=True)
    company = models.CharField(max_length=40, null=True)
    profile_pic = models.CharField(max_length=40, null=True)
    country = models.CharField(max_length=40, null=True)
    packet_premium = models.BooleanField(null=True)
    packet_business = models.BooleanField(null=True)


    def __str__(self):
        return self.user.username


and for using it I need a normal User for that is the CreateUserForm

But this view isn’t creating a User object, it’s creating an Account object.

No.

Your Account Model is a “profile” model associated with a User model. It is not your User model.

the register view is for creating both isnt it, for the AccountPrename thing I have a different view,

@login_required(login_url='home:login')
def AccountInfoPrename(request):
        if request.method == 'POST':
            form = AccountInfoPrenameForm(request.POST)
            if form.is_valid():
                form.save()



            return redirect('home:profile')
        else:
            form = AccountInfoPrenameForm()
        return render(request,
                  'home/profile.html',
                  {'form': form}

                  )


It’s for whatever you want it to be, provided you write the code to handle it.

However, right now I’m not sure you’re clear on the difference between objects and object instances, and between the user model and a profile model - I’d hesitate trying to make things more complicated than necessary until you get a more solid grasp on some fundamentals.

I think Im clear about that now, but still am I setting the users id into the model field and it doesnt appear in the database.

I also would like to say that I’m from germany and maybe I have like difficulties using the correct vocabular for the correct meaning.

So based on the last “register_view” you posted, you’re trying to create an Account object named account, but you’re using the wrong form.

Have you changed that view to use the right form?

But I dont have an extra form for the account object. Also isn’t it correct using the default user creation form for creating users. I mean my Account model just uses the default user, it shouldn’t replace him. At my opinion the UserCreationForm is correct there.

But I have an idea now, I try to (as you said) make an extra form for the Account Model which I also use for register and that stuff not just for profile stuff. Im writing again if I’m done.

Good Night

Your User objects and Account objects are two different but related objects.

That’s fine, then it should be a User object that you are creating from that submission, not an Account object. Saving the object created from UserCreationForm is a User. That submission isn’t going to do anything with Account.

No. Your Account model doesn’t use a User. It contains a reference to a User. There is no functionality or attributes in User that is available to Account.

so I tried to build an own user Model with own register system and stuff like that but I have come to the decission to use the OneToOneField (again) because its way easier.

Im completely clear about that, I have just difficulties with explaining it in english.

Same thing here

So the point is how can I make a Model with a reference to a user which displays the user id in the database and allows only one entry per user, like if I edit the form the entry should just be editet and not be newly created.

I want to create the account model database entry in the register view.

def register_view(request):
    if request.user.is_authenticated:
        return redirect('home:profile')
    else:
        form = CreateUserForm()

        if request.method == 'POST':
            form = CreateUserForm(request.POST)
            if form.is_valid():
                form.save()
                #here should be the code where I put the id from the request user into the Account Model User Field
                messages.success(request, 'Account wurde erstellt')

                return redirect('home:login')

        context = {'form': form}
        return render(request, 'home/register.html', context)

Again working on terminology - which is important when you’re trying to make sense of the documentation:

You are not making a Model. You are looking to create an instance of a Model.

You are correct - it is at that location that you want to create an instance of Account, setting any fields that should be set at that time - including the reference to the user object you created in the line directly above this.

See the doc page on Models for a full description on this. For a simple example of creating an instance from a model, modifying that instance, and saving it, see both the “person” and “fruit” examples in the Field options section on that page.

Don’t forget that the save method on a form returns the instance of the object being saved from that form.

yeah another difficulty with english and that stuff yk, im clear about that thank you

so I did this:

@login_required(login_url='home:login')
def AccountInfoPrename(request):
        if request.method == 'POST':
            form = AccountInfoPrenameForm(request.POST)
            if form.is_valid():
                form.save()
                account = Account.objects.update_or_create(user=request.user)
                account.save()

            return redirect('home:profile')
        else:
            form = AccountInfoPrenameForm()
        return render(request,
                  'home/profile.html',
                  {'form': form}

                  )


I changed the view to the AccountInfoPrename view because at the register view ther was a error thrown “‘AnonymousUser’ object is not iterable” which is because he isnt registered there.

So with this code it should update the user if it exits or create it if it doesnt exist.

But after submitting the form another erros appears

NOT NULL constraint failed: StartSite_account.user_id

Please go back to the previous version of the view.

You’re still primarily creating a User object. Changing to a form that is associated with the Account object is not correct.

And, my understanding is that you want to create the Account object associated with the user you just created, not the Account object associated with the person currently logged on.

So, revert back to the previous version. Capture the user object being created from the form.save statement. Create the Account object for that user. Save that new account instance.