I’ve prepared a model with a relationship.
I’d like to get a form which will make it possible to create User for that form.
Could someone explain me how it can be resolved?
class UserProfile(models.Model):
user = models.OneToOneField(User, unique=True, primary_key=True)
website = models.URLField(null=True, blank=True)
accepted_rules = models.BooleanField(default=False)
accepted_rules_date = models.DateTimeField(auto_now_add=True)
class UserProfile(ModelForm):
class Meta:
model = UserProfile
@csrf_protect
def register(request):
if request.method == "POST":
form = UserProfile(request.POST or None)
if form.is_valid():
website = form.cleaned_data['website']
accepted_rules = form.cleaned_data['accepted_rules']
username = form.cleaned_data['username']
email = form.cleaned_data['email']
password = form.cleaned_data['password']
form.save()
print "All Correct"
return TemplateResponse(request, 'base.html', {
'form':form,
}
)
Here is one way I would consider. First of all, I would name the form UserProfileForm so that it’s name doesn’t conflict with the model. Add extra fields to your UserProfile form for the fields required to create a new user. Create the new User instance. Use form.save(commit=False) so that you can add the newly created User instance to the UserProfile instance and save it. There may be a more elegant way.