
Welcome to the second part of the personal crypto portfolio app using Django. In the last part, we have successfully fetched the data of the top 100 cryptocurrencies according to market cap.
So, in this article, we will create an authentication(signup/login) system for the user so that users can register and save their personal portfolios.
Detail video for this tutorial is on youtube, do check it out.
Let’s Start
First, create a forms.py file inside your Django app and create a form for registering the user.
#forms.pyfrom django.contrib.auth import get_user_model
from django.contrib.auth.forms import UserCreationFormclass SignUpForm(UserCreationForm):class Meta:
model = get_user_model()
fields = ('username', 'email', 'password1', 'password2')def __init__(self, *args, **kwargs):
kwargs.setdefault('label_suffix', '')
super().__init__(*args, **kwargs)
self.fields['username'].label = "Username"
self.fields['email'].label = ""
self.fields['password1'].label = ""
self.fields['password2'].label = ""
Now create a function in your view.py to handle the request for registering the user.
User = get_user_model()# Create your views here.def register(request):
if request.method == 'POST':
form = SignUpForm(request.POST) if form.is_valid():
new_user = form.save()
new_user = authenticate(username=form.cleaned_data['username'],
password=form.cleaned_data['password1'],
)
login(request, new_user) return HttpResponseRedirect(reverse('home'))
else:
form = SignUpForm()return render(request, 'accounts/register.html', {'form':form})
Make necessary imports
The above function will check for “POST” requests and if the form is valid it saves the user in the database and the user will be logged in to the website.
HTML file for the register view
{% extends 'base.html' %}{% block content %}
<div class="container">
<form action="{% url 'accounts:register' %}" method="post">
{% csrf_token %}
{{form.as_p}}
<input type="submit" value="Register" class="btn btn-primary">
</form>
</div>
{% endblock %}
Now let’s continue with the login method. First, create a form for the login.
{%extends 'base.html'%}{% block title %}login{% endblock %}
{% block content %}<div class="section">
<div class="content">
<div class="heading mt-2">
<h2>Log in to Crypto</h2><br>
</div>
<div class="form-content">
<form action="{% url 'accounts:login' %}" method="post">
{% csrf_token %}
<input type="text" name="username" id="id-username" autocomplete="off"
placeholder="Please enter your username" required><br>
<input type="password" name="password" id="id_password" placeholder="Password" required><br>
<button class="login-btn" type="submit">Login</button><br>
</form>
</div>
</div>
</div>
</div>
{% endblock %}
Now create the view for handling the request.
def loginView(request):
if request.user.is_authenticated:
return HttpResponseRedirect(reverse('home'))if request.method == 'POST':
username = request.POST.get('username')
password = request.POST.get('password')user = authenticate(request, username=username, password=password)if user:
if user.is_active:
login(request,user)
return HttpResponseRedirect(reverse('home'))
else:
return HttpResponse("Account Not Active")
else:
context = {'notfound':True}
print(f"NO ACCOUNT FOUND WITH USERNAME {username} AND PASSWORD {password}")
print(context)
return render(request, 'accounts/login.html',context)else:
return render(request, 'accounts/login.html')
The above method will get the username and password that the user has entered in the form and it will authenticate the user and then user can log in.
We have successfully created the authentication system for the user.
That’s it for this article, in the next article we will create the portfolio model and get the price for the currency that we own.
Check out the youtube video for detailed instructions.
Follow for more such articles and for the next part of this list.
Thank you
Happy Coding!!!