How to create a view that saves User and UserProfile objects in Django

I have two models in Django: User (predefined by Django) and UserProfile. The two are connected through a foreign key.

models.py:

class UserProfile(models.Model):
  user = models.ForeignKey(User, unique=True, related_name="connect")
  location = models.CharField(max_length=20, blank=True, null=True)

I use UserCreationForm (predefined by Django) for the user model and created another form for UserProfile in forms.py

#UserCreationForm for User Model

class UserProfileForm(ModelForm):
  class Meta:
    model = UserProfile
    exclude = ("user", )

I load both of these forms into the registration.html template, so the site client can enter data about the fields contained in both models (for example: "first_name", "last_name" in the user model, "location" in the UserProfile model).

, . , , User, , ​​ UserProfile. - ? , :

def register(request):
  if request.method == 'POST':
    form1 = UserCreationForm(request.POST)
    form2 = UserProfileForm(request.POST)
    if form1.is_valid():
      #create initial entry for User object
      username = form1.cleaned_data["username"]
      password = form1.cleaned_data["password"]
      new_user = User.objects.create_user(username, password)

      # What to do here to save "location" field in a UserProfile 
      # object that corresponds with the new_user User object that 
      # we just created in the previous lines

  else:
    form1 = UserCreationForm()
    form2 = UserProfileForm()
  c = {
    'form1':UserCreationForm,
    'form2':form2,
  }
  c.update(csrf(request))
  return render_to_response("registration/register.html", c)
+5
1

:)

def register(request):
    if request.method == 'POST':
        form1 = UserCreationForm(request.POST)
        form2 = UserProfileForm(request.POST)
        if form1.is_valid() and form2.is_valid():
            user = form1.save()  # save user to db
            userprofile = form2.save(commit=False)  # create profile but don't save to db
            userprofile.user = user
            userprofile.location = get_the_location_somehow()
            userprofile.save()  # save profile to db

    else:
        form1 = UserCreationForm()
         form2 = UserProfileForm()
    c = {
      'form1':form1,
      'form2':form2,
    }
    c.update(csrf(request))
    return render_to_response("registration/register.html", c)

, form.save() db. form.save(commit=False) , db.

+3

All Articles