I followed a YouTube tutorial about creating a blog website, but I don’t like how the Profile creation form is set up. (I’m trying to create a website similar to the tutorial’s blog website, allowing users to create album reviews.)
The tutor in the YT video creates a UserRegisterForm
from the UserCreationForm
:
from django import forms
from django.contrib.auth.models import User
from django.contrib.auth.forms import UserCreationForm
from .models import Profile
class UserRegisterForm(UserCreationForm):
email = forms.EmailField()
class Meta:
model = User
fields = ['username', 'email', 'password1', 'password2']
Then a UserUpdateForm
and a ProfileUpdateForm
(which I tweaked for the information I would like from users):
class UserUpdateForm(forms.ModelForm):
email = forms.EmailField()
class Meta:
model = User
fields = ['username', 'email']
class ProfileUpdateForm(forms.ModelForm):
city = forms.CharField(label='City', max_length=100)
state = forms.CharField(label='State', required=False, max_length=50)
country = forms.CharField(label='Country (if outside U.S.)', required=False, max_length=100)
favorite_artists = forms.CharField(label='Your favorite artists (use commas)', required=False, max_length=200)
about_user = forms.CharField(widget=forms.Textarea(attrs={"rows": 7}), label='A small description of yourself', required=False)
class Meta:
model = Profile
fields = ['city', 'state', 'country', 'favorite_artists', 'about_user']
Then he adds a “profile” method in views.py
:
@login_required
def profile(request):
if request.method == 'POST':
u_form = UserUpdateForm(request.POST, instance=request.user)
p_form = ProfileUpdateForm(request.POST, instance=request.user.profile)
if u_form.is_valid() and p_form.is_valid():
u_form.save()
p_form.save()
messages.success(request, f'Your profile has been updated')
return redirect('profile')
else:
u_form = UserUpdateForm(instance=request.user)
p_form = ProfileUpdateForm(instance=request.user.profile)
context = {
'u_form': u_form,
'p_form': p_form
}
return render(request, 'users/profile.html', context)
Then this form (using the CrispyForms extension):
<form method="POST" enctype="multipart/form-data">
{% csrf_token %}
<fieldset class="form-group">
<legend class="border-bottom mb-4">Update Profile</legend>
{{ u_form|crispy }}
{{ p_form|crispy }}
</fieldset>
<div class="form-group pt-3">
<button class="btn btn-outline-info" type="submit">Update</button>
</div>
</form>
I don’t like the resulting page:
Is there a way to add the fields in the profile form into the register user form? Or are register form fields restricted to
'username'
, 'password'
, 'email'
, 'first_name'
, and 'last_name'
?