Skip to content Skip to sidebar Skip to footer

Modifying Sign Up Tab Created Using Django Framework

I have made a sign up tab that registers new users and log in page that allows the registered users to continue with the site. I want if any registered user (having a registered em

Solution 1:

Ok, so here is full solution. I have done some modifications to your existing solution, I hope this will help you.

Django comes with built in User model which already have authentication logic built in. Great thing is, it can be extended too. So I created UserDetails model which extends User using OneToOneField. Create and put following code in models.py .

models.py

from django.db import models
from django.contrib.auth.models import User

classUserDetails(models.Model):
    user = models.OneToOneField(User,on_delete=models.CASCADE)
    name = models.CharField(max_length=122)
    dob = models.DateField()

    def__str__(self):
        return self.name

After creating that, create migrations using following command python manage.py makemigrations and after that python manage.py migrate

Handling Sign Up logic:

We already have created our models, now to get data from user We need forms. Django have built in support for handling forms logic. I created two model forms as UserForm and UserDetailsForm. Here comes a tricky part, both forms are acting as a individual forms and each form is not aware of other. So I created a formset which is going to be used later to link our User with UserDetails inside view. Create and put following code in forms.py.

forms.py

from django import forms
from .models import UserDetails
from django.contrib.auth.models import User 
from django.contrib.auth.forms import UserCreationForm

classUserForm(UserCreationForm):
   classMeta:
      model = User
      fields = ('email','username','password1', 'password2',)

classUserDetailsForm(forms.ModelForm):
    classMeta:
        model = UserDetails
        fields = ('name', 'dob',)


from django.forms import inlineformset_factory
# Formset is combining UserForm and UserDetailsForm
UserDetailsFormSet = inlineformset_factory(User, UserDetails, form=UserDetailsForm, 
extra=1, can_delete = False)

To render both forms create a template signUpTemplate.html. (Note: You can style it later)

signUpTemplate.html

<formmethod="POST">
    {% csrf_token %}
    {{ user_form.as_p }}
    {{ user_details_form.as_p }}
    <buttontype="submit">Submit</button></form>

Now, I have created view as signUpView which will handle SignUp requests. Here I passed UserForm and UserDetailsFormSet in context and rendered the form using template. If you have seen carefully in signUpTemplate I am using single form tag <form>***code***</form> to render both the forms as it will force to send both the forms in single request.

Now this is how I am processing the forms data in view. First I check for UserForm. If UserForm is valid then I process UserDetailsFormSet and pass instance of UserForm in it (you may have seen commit=false parameter in save method. this parameter means that just save it in memory not in actual database). If UserDetailsFormSet is valid then I am calling the save() method on both forms. If forms are not valid then it will automatically render the error on template*(this is the power of built in forms)*. Here is the view code in views.py .

views.py

from django.shortcuts import render,redirect
from django.conf import settings
from .forms import UserForm, UserDetailsFormSet

defsignUpView(request):
    user_form = UserForm(request.POST orNone)
    user_details_form = UserDetailsFormSet(request.POST orNone)

    if request.method == 'POST':
        user_form = UserForm(request.POST)

        if user_form.is_valid():
            user = user_form.save(commit=False)
            user_details_form = UserDetailsFormSet(request.POST,instance=user)

            if user_details_form.is_valid():
                user.save()
                user_details_form.save()
                return redirect('login')

    context = {
        'user_form': user_form,
        'user_details_form': user_details_form,
    }

    return render(request, 'signUpTemplate.html',context=context)

Handling Login logic:

Login functionality is pretty straight forward. To handle login I have created loginView. Django provides built in AuthenticationForm for handling User authentication. To render AuthenticationForm create a template loginTemplate.html.

loginTemplate.html

<formmethod="POST">
    {% csrf_token %}
    {{ form.as_p }}
    <buttontype="submit">Submit</button></form>

The login() method is Django's built in functionality to handle User Login. Put following code in views.py (Note: do not forget to add URL after successful login in redirect() method).

views.py

from django.contrib.auth import login
from django.contrib.auth.forms import AuthenticationForm
from django.conf import settings

defloginView(request):
    form = AuthenticationForm(request.POST orNone)

    if request.method == 'POST':
        form = AuthenticationForm(data=request.POST)
        if form.is_valid():
            user = form.get_user()
            login(request, user)
            return redirect('URL_after_successful_login')

    return render(request, 'loginTemplate.html', context = {'form': form})

As we have done all the main part, now we can register both views in our apps urls.py file.

urls.py

from .viewsimport index,loginView,signUpView
from django.urlsimport path

urlpatterns = [
    path('', index, name='index'),
    path('login', loginView, name = 'login' ),
    path('signup', signUpView, name = 'signup')
]

also in your projects urls file do not forget to add referance to your apps url file by putting path('', include('your_app.urls')) in urlpatterns (Note: replace your_app with your appname)

Now you can run the server by using python manage.py runserver command. Go to your web browser and browse localhost:port/signup to get signup page, and localhost:port/login to get login page.

I hope you are familiar with admin site (i.e creation of super user and login into admin site), register your model with admin site as follows. And login with your super user credentials and check User and UserDetails tables at admin site.

admin.py

from django.contribimport admin
from .modelsimportUserDetails

admin.site.register(UserDetails)

I hope this will help you. :)

Post a Comment for "Modifying Sign Up Tab Created Using Django Framework"