i had a task to do: Tasks at hand o Brief description of the tasks to be performed ▪ The objective is to create a Django app that enables a user to register, log in, and sign a pre-defined contract. The contract will have 2 signing parties: one of them is the user that logs in initially and signs the contract, the other signing party is to be invited to sign by email. o User Stories ▪ As a user, I want to register, so that I could get logged in to use the signing features of the app • Acceptance Criteria o Basic django authentication is enough (session auth) o Username and password is enough for registration o No extra validation required for password or username o Upon logging in, I should be directed to the contract instantiation page ▪ As a user, I want to log in, so that I could use the signing features of the app • Acceptance Criteria o Log in with username and password o No extra validation required for password or username o Upon logging in, I should be directed to the contract instantiation page ▪ As a user, I want to instantiate a new contract, so that I could define its signing parties (signatories) and have it signed • Acceptance Criteria o The contract instantiation is done on a page view (the contract instantiation page) that takes in the necessary information as necessary, as dictated in the following bullet points: o The contract is to be made up of placeholder text (‘lorem impsum...’) o The contract should have three empty spots to fill for the recipients: full name, date, and signature o One of the signatories is the user itself (me, who’s logged in as a user) o The other signatory is to be invited via collecting an email address from the user (me, who’s logged in as a user). This information will be collected on this contract instantiation page ▪ As a user, I want to sign the agreement after it’s instantiated, so that I could have it filled out, digitally signed, and sent out to the other recipient for signing • Acceptance Crtieria o After instantiating the contract on the contract instantiation page, I should be directed to a page that shows me the Docusign agreement o I should be able to see an agreement with the placeholder text and the empty spots to input my full name, the date, and my signature o After completing the agreement, I should be redirected to another page showing me a success message o The other signatory should also receive an email with a link for signing the agreement I have been asked to use docusign API for that but for some reasons i just have access to SignNow API instead. i haven't ever work with REST-APIs honestly my setting.py: """ Django's settings for eSignApp project. Generated by 'django-admin startproject' using Django 5.1.1. For more information on this file, see https://docs.djangoproject.com/en/5.1/topics/settings/ For the full list of settings and their values, see https://docs.djangoproject.com/en/5.1/ref/settings/ """ import os from dotenv import load_dotenv from pathlib import Path # Load environment variables from .env file load_dotenv() # SIGNNOW_CLIENT_ID = os.getenv('SIGNNOW_CLIENT_ID') # SIGNNOW_CLIENT_SECRET = os.getenv('SIGNNOW_CLIENT_SECRET') EMAIL_BACKEND = 'django.core.mail.backends.smtp.EmailBackend' EMAIL_HOST = 'smtp.example.com' # Replace with your email provider's SMTP server EMAIL_PORT = 587 EMAIL_USE_TLS = True EMAIL_HOST_USER = 'your_email@example.com' # Replace with your email EMAIL_HOST_PASSWORD = 'your_password' # Replace with your email password # Build paths inside the project like this: BASE_DIR / 'subdir'. BASE_DIR = Path(__file__).resolve().parent.parent # Quick-start development settings - unsuitable for production # See https://docs.djangoproject.com/en/5.1/howto/deployment/checklist/ # SECURITY WARNING: keep the secret key used in production secret! SECRET_KEY = 'django-insecure--0a-g*dpo******c74s($mi3tzoe5_02(*******bko*!r_)2a' # SECURITY WARNING: don't run with debug turned on in production! DEBUG = True ALLOWED_HOSTS = [] # Application definition INSTALLED_APPS = [ 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'rest_framework', 'contracts', ] SIGNNOW_CLIENT_ID="38c34e58c691************336638c0" SIGNNOW_CLIENT_SECRET="93064f118f************d2a36d598a" SIGNNOW_API_URL="https://api-eval.signnow.com" MIDDLEWARE = [ 'django.middleware.security.SecurityMiddleware', 'django.contrib.sessions.middleware.SessionMiddleware', 'django.middleware.common.CommonMiddleware', 'django.middleware.csrf.CsrfViewMiddleware', 'django.contrib.auth.middleware.AuthenticationMiddleware', 'django.contrib.messages.middleware.MessageMiddleware', 'django.middleware.clickjacking.XFrameOptionsMiddleware', ] ROOT_URLCONF = 'eSignApp.urls' TEMPLATES = [ { 'BACKEND': 'django.template.backends.django.DjangoTemplates', 'DIRS': [], 'APP_DIRS': True, 'OPTIONS': { 'context_processors': [ 'django.template.context_processors.debug', 'django.template.context_processors.request', 'django.contrib.auth.context_processors.auth', 'django.contrib.messages.context_processors.messages', ], }, }, ] WSGI_APPLICATION = 'eSignApp.wsgi.application' # Database # https://docs.djangoproject.com/en/5.1/ref/settings/#databases DATABASES = { 'default': { 'ENGINE': 'django.db.backends.sqlite3', 'NAME': BASE_DIR / 'db.sqlite3', } } # Password validation # https://docs.djangoproject.com/en/5.1/ref/settings/#auth-password-validators AUTH_PASSWORD_VALIDATORS = [ { 'NAME': 'django.contrib.auth.password_validation.UserAttributeSimilarityValidator', }, { 'NAME': 'django.contrib.auth.password_validation.MinimumLengthValidator', }, { 'NAME': 'django.contrib.auth.password_validation.CommonPasswordValidator', }, { 'NAME': 'django.contrib.auth.password_validation.NumericPasswordValidator', }, ] # Internationalization # https://docs.djangoproject.com/en/5.1/topics/i18n/ LANGUAGE_CODE = 'en-us' TIME_ZONE = 'UTC' USE_I18N = True USE_TZ = True # Static files (CSS, JavaScript, Images) # https://docs.djangoproject.com/en/5.1/howto/static-files/ STATIC_URL = 'static/' # Default primary key field type # https://docs.djangoproject.com/en/5.1/ref/settings/#default-auto-field DEFAULT_AUTO_FIELD = 'django.db.models.BigAutoField' my views.py: from django.http import JsonResponse from .utils import create_pdf import requests import os from django.shortcuts import render, redirect from django.contrib.auth import login, authenticate from .forms import UserRegistrationForm, ContractForm from django.core.mail import send_mail def register(request): if request.method == 'POST': form = UserRegistrationForm(request.POST) if form.is_valid(): user = form.save(commit=False) user.set_password(form.cleaned_data['password']) user.save() login(request, user) return redirect('create_contract') else: form = UserRegistrationForm() return render(request, 'contracts/register.html', {'form': form}) # def login_view(request): if request.method == 'POST': username = request.POST['username'] password = request.POST['password'] user = authenticate(request, username=username, password=password) if user: login(request, user) return redirect('/contracts/') return JsonResponse({'message': 'Invalid credentials'}, status=401) return JsonResponse({'message': 'Invalid request method'}, status=400) SIGNNOW_CLIENT_ID = os.getenv('SIGNNOW_CLIENT_ID') SIGNNOW_CLIENT_SECRET = os.getenv('SIGNNOW_CLIENT_SECRET') def get_access_token(): url = "https://api.signnow.com/oauth2/token" payload = { 'client_id': SIGNNOW_CLIENT_ID, 'client_secret': SIGNNOW_CLIENT_SECRET, 'grant_type': 'client_credentials' } response = requests.post(url, data=payload) return response.json().get('access_token') # contracts/views.py def send_email_for_signature(request,email, document_id, title): subject = f'Signature Request: {title}' message = f'Please sign the contract document. Document ID: {document_id}' from_email = request.user.email # Replace with your email recipient_list = send_mail(subject, message, from_email, recipient_list, fail_silently=False) def create_contract(request): if request.method == 'POST': form = ContractForm(request.POST) if form.is_valid(): title = form.cleaned_data['title'] recipients = form.cleaned_data['recipients'].split(',') content = form.cleaned_data['content'] # Create a PDF file from the content pdf_file_path = create_pdf(content, title) # Create a document in signNow access_token = get_access_token() document_response = create_document_in_signnow(access_token, pdf_file_path) # Send email to recipients for email in recipients: send_email_for_signature(request,email, document_response, title) return redirect('success') # Redirect after sending else: form = ContractForm() return render(request, 'contracts/create_contract.html', {'form': form}) def create_document_in_signnow(access_token, pdf_file_path): url = "https://api.signnow.com/v2/documents" headers = { 'Authorization': f'Bearer {access_token}', 'Content-Type': 'application/json' } # Open the PDF file to upload with open(pdf_file_path, 'rb') as pdf_file: response = requests.post(url, headers=headers, files={'file': pdf_file}) return response.json() my forms.py: from django import forms from django.contrib.auth.models import User # class ContractForm(forms.Form): # user_name = forms.CharField(max_length=100) # recipient_email = forms.EmailField() class UserRegistrationForm(forms.ModelForm): password = forms.CharField(widget=forms.PasswordInput) class Meta: model = User fields = ['username', 'email', 'password'] class ContractForm(forms.Form): title = forms.CharField(max_length=100) recipients = forms.CharField(widget=forms.Textarea, help_text="Enter recipient emails separated by commas.") content = forms.CharField(widget=forms.Textarea, help_text="Enter contract content with placeholders.") my contracts(app name)/urls.py: from django.views.generic import TemplateView from . import views from django.contrib.auth import views as auth_views from django.urls import path from .views import register, create_contract urlpatterns = [ path('register/', register, name='register'), path('login/', auth_views.LoginView.as_view(template_name='contracts/login.html'), name='login'), path('create-contract/', create_contract, name='create_contract'), path('success/', TemplateView.as_view(template_name='contracts/success.html'), name='success'), ] templates/contracts/create_contract.html: <!DOCTYPE html> <html> <head> <title>Create Contract</title> </head> <body> <h2>Create Contract</h2> <form method="post"> {% csrf_token %} {{ form.as_p }} <button type="submit">Send Contract</button> </form> </body> </html> templates/contracts/login.html: <!DOCTYPE html> <html> <head> <title>Login</title> </head> <body> <h2>Login</h2> <form method="post"> {% csrf_token %} {{ form.as_p }} <button type="submit">Login</button> </form> <p>Don't have an account? <a href="{% url 'register' %}">Register here</a></p> </body> </html> templates/contracts/register.html: <!DOCTYPE html> <html> <head> <title>Register</title> </head> <body> <h2>Register</h2> <form method="post"> {% csrf_token %} {{ form.as_p }} <button type="submit">Register</button> </form> <p>Already have an account? <a href="{% url 'login' %}">Login here</a></p> </body> </html> templates/contracts/success.html: <!DOCTYPE html> <html> <head> <title>Success</title> </head> <body> <h2>Contract Sent Successfully!</h2> <p>Your contract has been sent to the recipients.</p> <a href="{% url 'create_contract' %}">Create another contract</a> </body> </html> [url="https://stackoverflow.com/questions/79263383/signnow-api-django-app-send-email-e-signing-contract"]Continue reading...[/url]