ModelForm isnt working

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()
                account = Account.objects.update_or_create(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)

With this code I get this error:
TypeError: ‘AnonymousUser’ object is not iterable

I know this is wrong, how should I get the user from the form if the form just includes the prename, or doesnt that matter is there an user in every form? Because then I would use this code:


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(commit=False)
                formuser = form.user
                account = Account.objects.update_or_create(user=formuser)
                account.save()
                form.save()

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

                return redirect('home:login')

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

With this error: ‘CreateUserForm’ object has no attribute ‘user’
because obviously the user isnt existing in the form for creating it.

form.save()
becomes
new_user = form.save()

account = Account.objects.update_or_create(user=request.user)
The update_or_create method doesn’t just return the object. It returns a tuple as documented.
So, the proper version becomes
account, is_new_account = Account.objects.update_or_create(user=new_user)

account.save()
is correct.
(Since you’re not changing the Account object here, you could wrap this in an if block to not perform the save if that Account object already exists.)

For future reference, just posting an error without the complete context of the stack trace is not very useful. Anytime you’re reporting a runtime error, you should post the complete stackdump.

so it works now, but how can i check if the object is already existing and why should I do that I mean the user is just registering himself once so why would I check if he already exists.

And another thing is the form for the Prename, if I submit it there is this error:

Traceback (most recent call last):
  File "C:\Users\Finn\AppData\Local\Programs\Python\Python39\lib\site-packages\django\core\handlers\exception.py", line 47, in inner
    response = get_response(request)
  File "C:\Users\Finn\AppData\Local\Programs\Python\Python39\lib\site-packages\django\core\handlers\base.py", line 181, in _get_response
    response = wrapped_callback(request, *callback_args, **callback_kwargs)
  File "C:\Users\Finn\AppData\Local\Programs\Python\Python39\lib\site-packages\django\contrib\auth\decorators.py", line 21, in _wrapped_view
    return view_func(request, *args, **kwargs)
  File "D:\Developement\Projekte\DivusX\DivusX\StartSite\views.py", line 69, in AccountInfoPrename
    form.save()
  File "C:\Users\Finn\AppData\Local\Programs\Python\Python39\lib\site-packages\django\forms\models.py", line 468, in save
    self.instance.save()
  File "C:\Users\Finn\AppData\Local\Programs\Python\Python39\lib\site-packages\django\db\models\base.py", line 726, in save
    self.save_base(using=using, force_insert=force_insert,
  File "C:\Users\Finn\AppData\Local\Programs\Python\Python39\lib\site-packages\django\db\models\base.py", line 763, in save_base
    updated = self._save_table(
  File "C:\Users\Finn\AppData\Local\Programs\Python\Python39\lib\site-packages\django\db\models\base.py", line 868, in _save_table
    results = self._do_insert(cls._base_manager, using, fields, returning_fields, raw)
  File "C:\Users\Finn\AppData\Local\Programs\Python\Python39\lib\site-packages\django\db\models\base.py", line 906, in _do_insert
    return manager._insert(
  File "C:\Users\Finn\AppData\Local\Programs\Python\Python39\lib\site-packages\django\db\models\manager.py", line 85, in manager_method
    return getattr(self.get_queryset(), name)(*args, **kwargs)
  File "C:\Users\Finn\AppData\Local\Programs\Python\Python39\lib\site-packages\django\db\models\query.py", line 1270, in _insert
    return query.get_compiler(using=using).execute_sql(returning_fields)
  File "C:\Users\Finn\AppData\Local\Programs\Python\Python39\lib\site-packages\django\db\models\sql\compiler.py", line 1416, in execute_sql
    cursor.execute(sql, params)
  File "C:\Users\Finn\AppData\Local\Programs\Python\Python39\lib\site-packages\django\db\backends\utils.py", line 98, in execute
    return super().execute(sql, params)
  File "C:\Users\Finn\AppData\Local\Programs\Python\Python39\lib\site-packages\django\db\backends\utils.py", line 66, in execute
    return self._execute_with_wrappers(sql, params, many=False, executor=self._execute)
  File "C:\Users\Finn\AppData\Local\Programs\Python\Python39\lib\site-packages\django\db\backends\utils.py", line 75, in _execute_with_wrappers
    return executor(sql, params, many, context)
  File "C:\Users\Finn\AppData\Local\Programs\Python\Python39\lib\site-packages\django\db\backends\utils.py", line 84, in _execute
    return self.cursor.execute(sql, params)
  File "C:\Users\Finn\AppData\Local\Programs\Python\Python39\lib\site-packages\django\db\utils.py", line 90, in __exit__
    raise dj_exc_value.with_traceback(traceback) from exc_value
  File "C:\Users\Finn\AppData\Local\Programs\Python\Python39\lib\site-packages\django\db\backends\utils.py", line 84, in _execute
    return self.cursor.execute(sql, params)
  File "C:\Users\Finn\AppData\Local\Programs\Python\Python39\lib\site-packages\django\db\backends\sqlite3\base.py", line 423, in execute
    return Database.Cursor.execute(self, query, params)
django.db.utils.IntegrityError: NOT NULL constraint failed: StartSite_account.user_id

If you don’t need to check for it already existing, don’t worry about it. It was a parenthetical note to highlight the fact that update_or_create returns a value telling you whether an existing object is used or if a new one was created.

The Working with forms page covers form error handling. The Form fields page also has some useful information.

I searched in different web pages now but I still dont know what this error means or why it appears. In the default Django docs I cant find it either.

You’re trying to save an instance of the Account model, but you haven’t put a valid entry into the user field. This is caused either by trying to create a new instance, or you have retrieved an existing instance and have cleared out that field.

We would need to see the view and form involved to provide more specific information.

@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}

                  )

I think about using the update or create method again to prevent making more than one entry, is that a good idea or the wrong way?

You didn’t post the form, but I can get to the core of the question:

Does the form include a field for user? (If not, then you’d need to assign a value to the user field before saving it.)

nope the form doesnt include a user field

That doesn’t really address the question.

Thinking about the flow of events - does the instance exist by the time you get to this point?

but if i add one how can I disable showing it in the form but still using it in my views

the first time using the form not but if I use it after then it exists

Not talking about that form. Talking about whatever instance of the Account object you’re trying to edit (or create).

Or, to phrase this differently, how do you know which instance of the Account object do you want to work with?

okay so I have to find out which AccountModel object instance belongs to the user using the form, and Im doing that in the views right?

Yes, that’s correct.

As an example, see the first example on Creating forms from models. Also see the second part of the first example in the save method docs.

I tried something, I know the code how I used it is completely wrong but is the idea I had behind that code right?

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

                

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

                  )

I know our replies crossed-paths. See my previous reply for the appropriate examples.

yeah but as I see the examples from the docs are all using forms where the user is in a field, but in my case I dont have a user field. I think in theory the way I’ve posted is not that wrong, just the code is wrong you know what I mean. So I cant figure out how to do it pwease help.

Where in either example referenced do you see the user in a field?

Yes, it is. Your goal should be to understand why your proposed approach doesn’t match the patterns pointed out to you, and to understand what each line of the example code is doing, and why.