I am trying to create a single form for a user
that has fields of both forms, both the user
and the userprofile
that you create to extend the model.
models.py
from django.db import models
from django.forms import ModelForm
from django.contrib.auth.models import User
class UserProfile(models.Model):
user = models.OneToOneField(User, on_delete=models.CASCADE)
date_of_birthday = models.DateField()
address = models.TextField()
phone_number = models.CharField(max_length=11)
def __str__(self):
return self.user.first_name
class UserProfileForm(ModelForm):
class Meta:
model = UserProfile
fields = '__all__'
class UserForm(ModelForm):
class Meta:
model = User
fields = ['username', 'first_name', 'last_name', 'email', 'password']
views.py
from django.shortcuts import render
from django.views.generic import CreateView
from .models import UserProfile, UserProfileForm, UserForm
class UserProfileCreateView(CreateView):
model = UserProfile
template_name = 'userprofiles/user_create.html'
success_url = '/'
form_class = UserProfileForm
def form_valid(self, form):
form.save()
return super(UserCreate, self).form_valid(form)
class UserCreateView(CreateView):
model = UserProfile
template_name = 'userprofiles/user_create.html'
success_url = '/'
form_class = UserForm
def form_valid(self, form):
form.save()
return super(UserCreate, self).form_valid(form)
view, here using form
shows me in both the same form that is the model of User
that Django brings.
<form action="{% url 'users:user_create' %}" method="post">
{% csrf_token %}
{{ form.as_p }}
{{ form.as_p }}
<button type="submit">Crear Usuario</button>
</form>
I know that maybe it can be done with formset
or with prefix
of the view based on class, but I think the prefix
is not necessarily for that and I do not have it completely clear.
Greetings!