skip to Main Content

I am getting error when i tried to signup in my django project,
error is given below,
enter image description here

urls.py
views.py
templates
and all the related files and code are provided below,
may you please check it and tell me why i am getting this error?


urls.py
from django.urls import path
from . import views


app_name = "users"
urlpatterns = [
    
    path('', views.AccountView.as_view(), name="account"),
    path('profile/', views.profile_view, name="profile"),
    path('sign-up', views.SignUpView.as_view(), name="sign-up"),
    path('sign-in', views.SignInView.as_view(), name="sign-in"),
    path('sign-out', views.sign_out, name="sign-out"),
    ]
views.py
from django.shortcuts import render, redirect, reverse
from django.contrib.auth.decorators import login_required
from django.contrib.auth.models import User
from django.contrib.auth import login, logout, authenticate
from django.conf import settings
from django.http import JsonResponse
from django.views.generic.edit import FormView
from django.views.generic.base import TemplateView
from django.utils.decorators import method_decorator


from django_google_api.mixins import(
    AjaxFormMixin, 
    reCAPTCHAValidation,
    FormErrors,
    RedirectParams,
    )


from .forms import (
    UserForm,
    UserProfileForm,
    AuthForm,
    )

result = "Error"
message = "There was an error, please try again"


class AccountView(TemplateView):
    '''
    Generic FormView with our mixin to display user account page
    '''
    template_name = "users/account.html"

    @method_decorator(login_required)
    def dispatch(self, *args, **kwargs):
        return super().dispatch(*args, **kwargs)



def profile_view(request):
    '''
    function view to allow users to update their profile
    '''
    user = request.user
    up = user.userprofile

    form = UserProfileForm(instance = up) 

    if request.is_ajax():
        form = UserProfileForm(data = request.POST, instance = up)
        if form.is_valid():
            obj = form.save()
            obj.has_profile = True
            obj.save()
            result = "Success"
            message = "Your profile has been updated"
        else:
            message = FormErrors(form)
        data = {'result': result, 'message': message}
        return JsonResponse(data)

    else:

        context = {'form': form}
        context['google_api_key'] = settings.GOOGLE_API_KEY
        context['base_country'] = settings.BASE_COUNTRY

        return render(request, 'users/profile.html', context)



class SignUpView(AjaxFormMixin, FormView):
    '''
    Generic FormView with our mixin for user sign-up with reCAPTURE security
    '''

    template_name = "users/sign_up.html"
    form_class = UserForm
    success_url = "/"

    #reCAPTURE key required in context
    def get_context_data(self, **kwargs):
        context = super().get_context_data(**kwargs)
        context["recaptcha_site_key"] = settings.RECAPTCHA_PUBLIC_KEY
        return context

    #over write the mixin logic to get, check and save reCAPTURE score
    def form_valid(self, form):
        response = super(AjaxFormMixin, self).form_valid(form)  
        if self.request.is_ajax():
            token = form.cleaned_data.get('token')
            captcha = reCAPTCHAValidation(token)
            if captcha["success"]:
                obj = form.save()
                obj.email = obj.username
                obj.save()
                up = obj.userprofile
                up.captcha_score = float(captcha["score"])
                up.save()
                
                login(self.request, obj, backend='django.contrib.auth.backends.ModelBackend')

                #change result & message on success
                result = "Success"
                message = "Thank you for signing up"

                
            data = {'result': result, 'message': message}
            return JsonResponse(data)

        return response




class SignInView(AjaxFormMixin, FormView):
    '''
    Generic FormView with our mixin for user sign-in
    '''

    template_name = "users/sign_in.html"
    form_class = AuthForm
    success_url = "/"

    def form_valid(self, form):
        response = super(AjaxFormMixin, self).form_valid(form)  
        if self.request.is_ajax():
            username = form.cleaned_data.get('username')
            password = form.cleaned_data.get('password')
            #attempt to authenticate user
            user = authenticate(self.request, username=username, password=password)
            if user is not None:
                login(self.request, user, backend='django.contrib.auth.backends.ModelBackend')
                result = "Success"
                message = 'You are now logged in'
            else:
                message = FormErrors(form)
            data = {'result': result, 'message': message}
            return JsonResponse(data)
        return response




def sign_out(request):
    '''
    Basic view for user sign out
    '''
    logout(request)
    return redirect(reverse('users:sign-in'))

mixin.py
from django.conf import settings
from django.shortcuts import redirect
from urllib.parse import urlencode
import requests
import json
import datetime
from humanfriendly import format_timespan
from django.http import JsonResponse


def is_ajax(request):
    return request.META.get('HTTP_X_REQUESTED_WITH') == 'XMLHttpRequest'

def FormErrors(*args):
    '''
    Handles form error that are passed back to AJAX calls
    '''
    message = ""
    for f in args:
        if f.errors:
            message = f.errors.as_text()
    return message
    

def reCAPTCHAValidation(token):

    ''' reCAPTCHA validation '''
    result = requests.post(
        'https://www.google.com/recaptcha/api/siteverify',
         data={
            'secret': settings.RECAPTCHA_PRIVATE_KEY,
            'response': token
         })

    return result.json()



def RedirectParams(**kwargs):
    '''
    Used to append url parameters when redirecting users
    '''
    url = kwargs.get("url")
    params = kwargs.get("params")
    response = redirect(url)
    if params:
        query_string = urlencode(params)
        response['Location'] += '?' + query_string
    return response


class AjaxFormMixin(object):

    '''
    Mixin to ajaxify django form - can be over written in view by calling form_valid method
    '''

    def form_invalid(self, form):
        response = super(AjaxFormMixin, self).form_invalid(form)
        if is_ajax(self.request):
            message = FormErrors(form)
            return JsonResponse({'result':'Error', 'message': message})
        return response

    def form_valid(self, form):
        response = super(AjaxFormMixin, self).form_valid(form)
        if is_ajax(self.request):
            form.save()
            return JsonResponse({'result':'Success', 'message': ""})
        return response





def Directions(*args, **kwargs):
    

    lat_a = kwargs.get("lat_a")
    long_a = kwargs.get("long_a")
    lat_b = kwargs.get("lat_b")
    long_b = kwargs.get("long_b")
    lat_c = kwargs.get("lat_c")
    long_c = kwargs.get("long_c")
    lat_d = kwargs.get("lat_d")
    long_d = kwargs.get("long_d")

    origin = f'{lat_a},{long_a}'
    destination = f'{lat_b},{long_b}'
    waypoints = f'{lat_c},{long_c}|{lat_d},{long_d}'

    result = requests.get(
        'https://maps.googleapis.com/maps/api/directions/json?',
         params={
         'origin': origin,
         'destination': destination,
         'waypoints': waypoints,
         "key": settings.GOOGLE_API_KEY
         })

    directions = result.json()

    if directions["status"] == "OK":

        routes = directions["routes"][0]["legs"]

        distance = 0
        duration = 0
        route_list = []

        for route in range(len(routes)):

            distance += int(routes[route]["distance"]["value"])
            duration += int(routes[route]["duration"]["value"])

            route_step = {
                'origin': routes[route]["start_address"],
                'destination': routes[route]["end_address"],
                'distance': routes[route]["distance"]["text"],
                'duration': routes[route]["duration"]["text"],

                'steps': [
                    [
                        s["distance"]["text"],
                        s["duration"]["text"],
                        s["html_instructions"],

                    ]
                    for s in routes[route]["steps"]]
                }

            
            route_list.append(route_step)
            

    return {
        "origin": origin,
        "destination": destination,
        "distance": f"{round(distance/1000, 2)} Km",
        "duration": format_timespan(duration),
        "route": route_list
        }


sign_up.html
{% extends 'base.html' %}
{% load static %}


{% block extend_head %}

<script src='https://www.google.com/recaptcha/api.js?render={{recaptcha_site_key}}'></script>

{% endblock %}

{% block content %}

<h3>Django Google API Course - Sign Up</h3>

<div class="container">


  <form id="signupform" method="POST" action="/sign-up">
    {% csrf_token %}

    
    <label for="first_name">First Name</label>
    {{form.first_name}}

    <label for="last_name">Last Name</label>
    {{form.last_name}}

    <label for="username">Username</label>
    {{form.username}}

    <label for="password1">Password</label>
    {{form.password1}}

    <label for="password2">Confirm Password</label>
    {{form.password2}}

    {{form.token}}

    <label class="check-container">Show Passwords
     <input type="checkbox" onclick="showPword()">
     <span class="checkmark"></span>
    </label>

    <button type="submit">Sign up</button>

  </form>
</div>


</div>

{% endblock %}

{% block extend_footer %}

<script type="text/javascript">
  // Create a variable that can be used in main.js
  var recaptcha_site_key = '{{recaptcha_site_key|safe}}'
</script>


{% endblock %}


0

Traceback: Internal Server Error: /sign-up Traceback (most recent call last): File "C:UserslaxmaOneDriveDesktopdsa and practicelearningdjangoPython Django and Google APIs – Project TutorialvenvLibsite-packagesdjangocorehandlersexception.py", line 47, in inner response = get_response(request) ^^^^^^^^^^^^^^^^^^^^^ File "C:UserslaxmaOneDriveDesktopdsa and practicelearningdjangoPython Django and Google APIs – Project TutorialvenvLibsite-packagesdjangocorehandlersbase.py", line 181, in _get_response response = wrapped_callback(request, *callback_args, **callback_kwargs) ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ File "C:UserslaxmaOneDriveDesktopdsa and practicelearningdjangoPython Django and Google APIs – Project TutorialvenvLibsite-packagesdjangoviewsgenericbase.py", line 70, in view return self.dispatch(request, *args, **kwargs) ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ File "C:UserslaxmaOneDriveDesktopdsa and practicelearningdjangoPython Django and Google APIs – Project TutorialvenvLibsite-packagesdjangoviewsgenericbase.py", line 98, in dispatch return handler(request, *args, **kwargs) ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ File "C:UserslaxmaOneDriveDesktopdsa and practicelearningdjangoPython Django and Google APIs – Project TutorialvenvLibsite-packagesdjangoviewsgenericedit.py", line 142, in post return self.form_valid(form) ^^^^^^^^^^^^^^^^^^^^^ File "C:UserslaxmaOneDriveDesktopdsa and practicelearningdjangoPython Django and Google APIs – Project Tutorialdjango_google_apiusersviews.py", line 110, in form_valid data = {‘result’: result, ‘message’: message} ^^^^^^ UnboundLocalError: cannot access local variable ‘result’ where it is not associated with a value [15/Nov/2023 17:17:05] "POST /sign-up HTTP/1.1" 500 86818

i have tried stack overflow solution but they didnt work

2

Answers


  1. Chosen as BEST ANSWER

    Traceback: Internal Server Error: /sign-up Traceback (most recent call last): File "C:UserslaxmaOneDriveDesktopdsa and practicelearningdjangoPython Django and Google APIs - Project TutorialvenvLibsite-packagesdjangocorehandlersexception.py", line 47, in inner response = get_response(request) ^^^^^^^^^^^^^^^^^^^^^ File "C:UserslaxmaOneDriveDesktopdsa and practicelearningdjangoPython Django and Google APIs - Project TutorialvenvLibsite-packagesdjangocorehandlersbase.py", line 181, in _get_response response = wrapped_callback(request, *callback_args, **callback_kwargs) ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ File "C:UserslaxmaOneDriveDesktopdsa and practicelearningdjangoPython Django and Google APIs - Project TutorialvenvLibsite-packagesdjangoviewsgenericbase.py", line 70, in view return self.dispatch(request, *args, **kwargs) ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ File "C:UserslaxmaOneDriveDesktopdsa and practicelearningdjangoPython Django and Google APIs - Project TutorialvenvLibsite-packagesdjangoviewsgenericbase.py", line 98, in dispatch return handler(request, *args, **kwargs) ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ File "C:UserslaxmaOneDriveDesktopdsa and practicelearningdjangoPython Django and Google APIs - Project TutorialvenvLibsite-packagesdjangoviewsgenericedit.py", line 142, in post return self.form_valid(form) ^^^^^^^^^^^^^^^^^^^^^ File "C:UserslaxmaOneDriveDesktopdsa and practicelearningdjangoPython Django and Google APIs - Project Tutorialdjango_google_apiusersviews.py", line 110, in form_valid data = {'result': result, 'message': message} ^^^^^^ UnboundLocalError: cannot access local variable 'result' where it is not associated with a value [15/Nov/2023 17:17:05] "POST /sign-up HTTP/1.1" 500 86818


  2. The image hints at UnboundLocalError at /sign-up/. Please, if you have an error: always include the traceback if you have it. It makes finding the problem so much easier.

    Looking at the SignUpView, it seems that result and message are not set if captcha["success"] is False. Add a result and message if the captcha fails:

       def form_valid(self, form):
            response = super(AjaxFormMixin, self).form_valid(form)  
            if self.request.is_ajax():
                token = form.cleaned_data.get('token')
                captcha = reCAPTCHAValidation(token)
                if captcha["success"]:
                    obj = form.save()
                    obj.email = obj.username
                    obj.save()
                    up = obj.userprofile
                    up.captcha_score = float(captcha["score"])
                    up.save()
                    
                    login(self.request, obj, backend='django.contrib.auth.backends.ModelBackend')
    
                    #change result & message on success
                    result = "Success"
                    message = "Thank you for signing up"
                else:
                    result = "Nope!"
                    message = "Try again!"
                data = {'result': result, 'message': message}
            return JsonResponse(data)
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search