A Django beginner here having a lot of trouble getting forms working. Yes I\'ve worked through the tutorial and browsed the web a lot - what I have is mix of what I\'m finding h
I'm not sure exactly what the problem is here, but one issue certainly is that you are passing instance=request.user
when instantiating the form. That's definitely wrong: request.user
is an instance of User, whereas the form is based on UserProfile
.
Instead, you want to do something like this:
f = UserDetailsForm(request.POST)
if f.is_valid():
profile = f.save(commit=False)
profile.user = request.user
profile.save()
As regards ForeignKey vs OneToOne, you should absolutely be using OneToOne. The advice on using ForeignKeys was given for a while in the run-up to the release of Django 1 - almost five years ago now - because the original implementation of OneToOne was poor and it was due to be rewritten. You certainly won't find any up-to-date documentation advising the use of FK here.
Edit after comments The problem now is that you're instantiating the form with the first parameter, data, even when the request is not a POST and therefore request.POST
is an empty dictionary. But the data parameter, even if it's empty, takes precedence over whatever is passed as initial data.
You should go back to the original pattern of instantiating the form within the if
statement - but be sure not to pass request.POST
when doing it in the else
clause.