I have a signup form that needs to be loaded for every page of my site if the user is a guest. I figured the easiest way to do this would be to create a “signup” app/module and have the form variable defined in the init.py so it was automatically initiated on every view, assuming I imported the module. However, I’m having a bit of trouble getting my view to find the form variable. “global name ‘form’ is not defined” Below is my setup:
I have a /signup/init.py and /signup/form.py files.
This is my init.py
from django import forms
from signup.form import SignUpForm
form = SignupForm()
This is my form.py
class SignupForm(forms.Form):
fullname = forms.CharField(min_length=3, max_length=25, initial='name', error_messages={'required': 'A unique username is required.', 'min_length': 'Your username must contain at least 3 characters.'})
username = forms.CharField(min_length=3, max_length=25, initial='choose a username', error_messages={'required': 'A unique username is required.', 'min_length': 'Your username must contain at least 3 characters.'})
password = forms.CharField(min_length=7, initial='choose a password', error_messages={'required': 'Please enter a password.','min_length': 'Your password must contain at least 7 characters.'})
email = forms.EmailField(initial='e-mail address', error_messages={'required': 'Please enter a valid email address.', 'invalid': 'Please enter a valid email address.'})
find_me = forms.BooleanField(initial=True, required=False)
tos = forms.BooleanField(error_messages={'required': 'You must accept our Terms of Service.'})
And I’m trying to load those from my /views/index.py file:
from django.http import HttpResponse
from pymongo import *
from user import *
import mongo
from django.shortcuts import render_to_response
from django.template import RequestContext, loader
import signup
#index view
def index(request):
return render_to_response('index.html',
{'form': signup.form},
context_instance=RequestContext(request),
)
I removed the irrelevant code in index.py… but basically.. (i’ll probably have an if else for the return statement to only return the ‘form’:form when the user is unregistered)
Am I approaching this completely wrong? Anyone mind showing me what I’m doing incorrectly?
::Edit::
Also, I noticed that I didn’t have signup.form in the return, but that still throws a
AttributeError at /
'module' object has no attribute 'form'
error. I changed the code above to accommodate that
I would just point out that the way you’re doing it is an extremely bad idea. You have one instance of the form across every request: that’s always going to be dangerous, allowing the possibility of information leakage across requests. Don’t do it.
Instead, use the built-in mechanism that Django has to do this for you: context processors. In your signup/form.py, define a simple function:
and add this to
TEMPLATE_CONTEXT_PROCESSORSin settings.py: