[Fixed]-How do I link these two models such that one will update that same instance?


So basically, you want to know how to save an instance of something which is related to the logged-in user. That’s easy.

To explain why you are getting a NOT NULL error: Your TournyRegForm class has not been told to display an input field for ‘user’, so it isn’t. So when you go to save the form, None is being filled in for the user field. The database is complaining because a ‘NOT NULL’ field has a NULL value, which is a problem.. so this error is legitimate.

But it’s ok that this field is not on the form.. because you don’t want the user telling us who they are via the form, you want to get the information about who they are by the fact that they are logged in. The Django auth module puts this information in the Request object where you can easily get at it. All you need to do is to fill in the correct user before the model is saved, like this:

if tourny_form.is_valid():
    # commit= False tells the modelform to just create the model instance
    # but don't save it yet.
    user_profile = tourny_form.save(commit=False)
    # associate this user_profile with the logged in user.. it is always
    # present in the request object if you are using django's         auth module.
    user_profile.user = request.user
    # now save it

So that takes care of saving a model that is related to the currently logged in user. But you have other problems. For example, do you want to save a new UserProfile each time? I don’t think you do.. So on your GET you need to do something like this:

user_profile = UserProfile.objects.filter(user=request.user).first()
tourny_form = TournyRegForm(instance=user_profile)

This will fetch the UserProfile of the currently logged=in user from the database, then initialize the form with that instance, so when the user comes back they will be able to edit their profile.

Now, if you actually want the user to be able to register for multiple games.. you will need a Game model for storing the game information, with one-to-many relationship with your UserProfile. This works by having a ForeignKey field in the Game model which relates it to UserProfile.. so each user will have only one UserProfile but could have multiple Games.

Leave a comment