Note that there are some explanatory texts on larger screens.

plurals
  1. POHow to save data in backend/database for UserProfile in Django
    text
    copied!<p>My intention is to create a user profile using Django's User model and a UserProfile model (which basically adds details / fields about the user). I then want to create a registration form that asks to fill fields that are contained in both the User Model and the UserProfile Model (i.e. a single form for fields from both models).</p> <p>What's happening right now is after entering the necessary data into my form, the view passes and the server does create a User object and even links it to a UserProfile object (as far as I understand, this linkage occurs because of the signal created in the models.py class). However, no information about the UserProfile (in this case, the "location" field) is added and for the life of me, I can't figure out why.</p> <p>I have the following models.py</p> <pre><code>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) def create_user_profile(sender, instance, created, **kwargs): if created: UserProfile.objects.create(user=instance) post_save.connect(create_user_profile, sender=User) </code></pre> <p>I have the following forms.py (where UserForm is based on the User Model defined by Django)</p> <pre><code>class UserForm(ModelForm): class Meta: model = User class UserProfileForm(ModelForm): class Meta: model = UserProfile </code></pre> <p>I have the following views.py</p> <pre><code>@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) </code></pre> <p>I have the following register.html</p> <pre><code>&lt;form action="/accounts/register/" method="post"&gt;{% csrf_token %} &lt;p style="color:red"&gt; {{form.username.errors}}&lt;/p&gt; {{ form1.as_p }} {{ form2.as_p }} &lt;input type="submit" value="Create the account"&gt; &lt;/form&gt; </code></pre> <p>Can anyone see what I'm doing wrong? Is there a better way to do this? Thanks in advance!</p>
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload