Skip to content Skip to sidebar Skip to footer

How To Create A Profile Registration Form In Django?

I am trying to create a custom registration form, but I don't really know how to do it since I am trying to connect the default django registration with a new model. here is what i

Solution 1:

Also in order to get the name in the template you have to access it like {{ user.profile.name }} since name is saved in the Profile Model

But if you want to create a form for your Profile model you can do it like this

class ProfileForm(forms.ModelForm):
    class Meta:
         model = Profile
         fields = ("name", "description")

Also if you plan to use both the UserCreationForm and the ProfileForm both in the same HTML Form you should add a prefix to them to know which data belongs to which form, look how to do it here https://docs.djangoproject.com/en/1.9/ref/forms/api/#prefixes-for-forms

Edit

def register_user(request):
    #...
    if request.method == "POST":
        user_form = UserCreationForm(request.POST, prefix="user")
        profile_form = ProfileForm(request.POST, prefix="profile")
        if user_form.is_valid() and profile_form.is_valid():
            user = user_form.save(commit=False)
            user.save()
            profile = profile_form.save(commit=False)
            profile.user = user
            profile.save()
            return redirect('/')
    else:
        user_form = UserCreationForm(prefix="user")
        profile_form = ProfileForm(prefix="profile")
    context = {
        "user_form": user_form,
        "profile_form": profile_form
    }
    return render(request, 'register.html', context)

Then in the template

<form action="/user/register/" method="post" id="register" autocomplete="off">
{% csrf_token %}
<div class="fieldWrapper">
    {{ user_form }}
    {{ profile_form }}
</div>
<input type="submit" value="Register"/>


Post a Comment for "How To Create A Profile Registration Form In Django?"