I have a User Model (pre-defined by Django) and a UserProfile model connected via a ForeignKey.
I'm creating two separate ModelForms to use in a single template as a registration form of sorts.
models.py
class UserProfile(models.Model):
# This field is required.
user = models.ForeignKey(User, unique=True, related_name="connector")
location = models.CharField(max_length=20, blank=True, null=True)
forms.py
class UserForm(ModelForm):
class Meta:
model = User
class UserProfileForm(ModelForm):
class Meta:
model = UserProfile
However, when I load the page and fill in the form information, the UserProfileForm requires me to select / fill in the user field in order to validate.
This "user", however, is the one that is being created right now so I can't choose a "user" as it has not been created yet / is still being created.
I know this user is field has the attribute unique=true but there a way to make this field "optional"?
My view (below) should handle it such that once the user object is created, i will set the foreign key of UserProfile to this newly created user object (unless I am doing something wrong my views.py as well).
views.py
@csrf_protect
def register(request):
if request.method == 'POST':
form1 = UserForm(request.POST)
form2 = UserProfileForm(request.POST)
if form1.is_valid() and form2.is_valid():
#create initial entry for user
username = form1.cleaned_data["username"]
password = form1.cleaned_data["password"]
new_user = User.objects.create_user(username, password)
new_user.save()
#create entry for UserProfile (extension of new_user object)
profile = form2.save(commit = False)
profile.user = new_user
profile.save()
return HttpResponseRedirect("/books/")
else:
form1 = UserForm()
form2 = UserProfileForm()
c = {
'form1':form1,
'form2':form2,
}
c.update(csrf(request))
return render_to_response("registration/register.html", c)
Well you could set:
user = models.ForeignKey(User, unique=True, blank=True, null=True, related_name="connector")
which would make the user relationship optional, but I don't think this is what you need. Instead, why not just remove the user
field from the UserProfile
form and manually assign it, instead of letting the user see the dropdown at all. Then there would be no validation error.
class UserProfileForm(ModelForm):
class Meta:
model = UserProfile
exclude = ("user", )