how to send verification email to specific users only in django-allauth - django

I'm using django-tenants for multi-tenancy,All things are good with allauth package.
But the problem is:
I've signup form for "subscribers" they must receive an email confirmation and a custom signup form for every "subscribers" to enable them to create users under their subdomains, But the "created users" must receive an email with an initial password not confirmation email.
Really I tried many things to perform this mission but with no solution and I searched in many threads here but unfortunately useless,
I tried to override
def send_mail(self, template_prefix, email, context):,
def send_confirmation_mail(self, request, emailconfirmation, signup): and
class CustomConfirmEmailView(ConfirmEmailView):.
I knew that I've missed something but I don't know what is it. If I send a confirmation email to "subscribers", "created users" affected , And if I change settings to prevent sending confirmation email the "subscribers" affected
Also I've a custom login form in adapter.py file to enable users to login with username.
class CustomLoginView(LoginView):
template_name = 'account/subdomain/login.html'
This is my settings
ACCOUNT_ADAPTER = 'apps.authentication.adapter.CustomAccountAdapter'
AUTH_USER_MODEL = 'authentication.CustomUser'
ACCOUNT_FORMS = {
'login': 'apps.authentication.forms.CustomLoginForm',
'signup': 'apps.authentication.forms.CustomUserCreationForm'
}
LOGIN_REDIRECT_URL = '/'
ACCOUNT_LOGOUT_REDIRECT_URL = 'account_login' # created users must redirect to their subdomain login page not public login page
ACCOUNT_LOGOUT_ON_GET = True # If True it will logout the user immediately
ACCOUNT_AUTHENTICATION_METHOD = 'username_email'
ACCOUNT_EMAIL_REQUIRED = True
ACCOUNT_UNIQUE_EMAIL = True #* It's not working for some reason but I don't know why, we have Handled from forms.py
ACCOUNT_USERNAME_REQUIRED = True
#* to solve subdomain users login for now
ACCOUNT_EMAIL_VERIFICATION = 'optional' # to send mail for subscribers not to created users but it doesn't fix the issue
ACCOUNT_LOGIN_ON_EMAIL_CONFIRMATION = None # To prevent login on verification for created users but the subscribers affected
# ACCOUNT_EMAIL_CONFIRMATION_ANONYMOUS_REDIRECT_URL = '/auth/email/success/'
# ACCOUNT_EMAIL_CONFIRMATION_AUTHENTICATED_REDIRECT_URL = '/'
ACCOUNT_CONFIRM_EMAIL_ON_GET = True # try to solve the issue
ACCOUNT_SESSION_REMEMBER = True
ACCOUNT_LOGIN_ATTEMPTS_LIMIT = 10
#* This setting to enable us to access sign up view when authenticated
ACCOUNT_AUTHENTICATED_LOGIN_REDIRECTS = False
ACCOUNT_SIGNUP_REDIRECT_URL = 'account_login'
Update: Some of my tries to solve the issue
I tried to solve this issue by making redirect to the
return redirect('account_email_verification_sent')
But I failed.
This is the custom signup view in adapter.py
class CustomSignupView(SignupView):
'''
We override this class to
Make Signup form for Customers == Subscribers users from dashboard
'''
print('working done .......')
def form_valid(self, form):
# print('Enter form valid')
self.user = form.save(self.request)
# mobile = self.user.mobile_number
self.user.first_login = False
client = Client.objects.create(
schema_name=self.user.company_name,
type=self.user.industry,
name=self.user.company_name,
description='any for now',
)
print('client is: ', client, self.user.industry)
domain = Domain.objects.create(
domain=self.user.company_name + '.localhost',
tenant=client,
is_primary=True,
)
print('domain: ', domain)
with schema_context(self.user.company_name):
CustomUser.objects.create(
password=self.user.password, username=self.user.username,
first_name=self.user.first_name, last_name=self.user.last_name,
company_name=self.user.company_name , mobile_number=self.user.mobile_number,
email=self.user.email, operating_countries=self.user.operating_countries,
hq_country=self.user.hq_country, operating_cities=self.user.operating_cities,
shipments_per_month=self.user.shipments_per_month, address=self.user.address,
industry=self.user.industry, first_login=False
)
# domain = Domain.objects.prefetch_related('tenant').get(tenant__name=self.user.company_name)
return redirect('account_email_verification_sent')
And this is the signup view for "created users"
def create_user(request):
with schema_context(request.tenant.schema_name):
url = request.get_host() #request.tenant.get_primary_domain()
user_url = url + '/accounts/login/'
# obj = Domain.objects.select_related('tenant').get(domain=url)
print('url= ', url, 'obj= ',request.tenant.type)
if request.method == 'POST':
form = SupplierCreationForm(request.POST or None)
if form.is_valid():
save_form = form.save(commit=False)
save_form.industry = request.tenant.type
save_form.operating_countries = ''
save_form.operating_cities = ''
save_form.hq_country = ''
save_form.first_login = True
save_form.save()
from django.core.mail import send_mail
send_mail(
subject='Action Required',
message='''
Congratulations, Your password is:''' + str(request.POST.get('password1')) + ''' ,
Go to this link (http://''' + url + '''%s''' %reverse('account_login') + ''') to login
''',
from_email=settings.EMAIL_HOST_USER,
recipient_list=[save_form.email]
)
print('sending mail done ... ')
return redirect('create_user')
else:
form = SupplierCreationForm()
context = {
'form': form
}
return render(request, 'account/create_user.html', context)
Any help. If I missed some code to elaborate the issue, please tell me to update my question,
Thanks

Related

Why is this Django view being executed twice on post?

I have a Django view that signs a user up to a free trial through Stripe. When the view makes a POST request, it does so twice.
I've tried idempotency keys, both after the if request.method == 'POST' line and in the initial rendering of the view. The customer in Stripe always ends up with two identical payment sources and two identical subscriptions to the plan.
def start_trial(request):
title = 'get started'
description = title
form = MembershipForm()
key = settings.STRIPE_PUBLISHABLE_KEY
trial_days = 30
coupon = None
custom_message = ''
subscription_idempotency = str(uuid.uuid4())
source_idempotency = str(uuid.uuid4())
try:
vendor = Vendor.objects.get(user=request.user)
custom_message = vendor.message
coupon = Coupon.objects.get(vendor.coupon)
coupon = coupon.stripe_coupon_id
trial_days = vendor.trial_days
except Vendor.DoesNotExist:
pass
try:
partner = Partner.objects.get(user=request.user)
custom_message = partner.message
coupon = Coupon.objects.get(partner.coupon)
coupon = coupon.stripe_coupon_id
trial_days = partner.trial_days
except Partner.DoesNotExist:
pass
if request.method == 'POST':
form = MembershipForm(request.POST)
if form.is_valid():
user = request.user
plan = Membership.objects.get(type_of=form.cleaned_data['plan'])
# stripe needs to attempt to create a customer
# TODO what if there's already a membership/subscription?
user_membership = UserMembership.objects.get(user=request.user)
stripe_subscription = stripe.Subscription.create(
customer=user_membership.stripe_customer_id,
items=[
{"plan": plan.stripe_plan_id}
],
trial_period_days=trial_days,
coupon=coupon,
idempotency_key=subscription_idempotency,
)
subscription = Subscription.objects.create(
user_membership=user_membership, stripe_subscription_id=stripe_subscription.id)
subscription.save()
stripe.Customer.create_source(user_membership.stripe_customer_id,
source=request.POST.get('stripeToken'),
idempotency_key=source_idempotency)
user_membership.membership = plan
user_membership.save()
user.is_subscriber = True
user.save()
# if subscription status is incomplete, display error.
# if passes, redirect to onboarding
message = 'yay'
messages.success(request, message=message)
return HttpResponseRedirect('/onboarding/')
return render(request, 'memberships/free_trial.html',
{'title': title, 'description': description, 'form': form,
'key': key, 'custom_message': custom_message})
Data always ends up in Stripe twice. Log shows:
[18/Jun/2019 11:05:21] "POST /memberships/free-trial/ HTTP/1.1" 302 0
[18/Jun/2019 11:05:22] "POST /memberships/free-trial/ HTTP/1.1" 302 0
Thanks to #duck for pointing me in the right direction. I had unseen (to me) JavaScript duplicating what was happening in the view. Removed the offending file and the problem is solved.

django email fails to send in production, works for errors, fails for a particular view

I'm trying to automatically send an email with a django contact us form.
The contact form view works in development properly via django.core.mail.backends.console.EmailBackend
Sending of emails to admins for errors in procution works properly.
However sending emails for the contact view/form doesn't work in production.
No errors are produced in production when submitting the contact form.
the post request appears in the logs, but there isn't any other useful information (that I can see) apart from that.
I'm not sure how best to pinpoint the error?
view:
#require_http_methods(['GET', 'HEAD', 'POST'])
def contact_view(request):
form = ContactForm()
if request.method == 'POST':
form = ContactForm(request.POST)
if form.is_valid():
contact_name = form.cleaned_data.get('contact_name', '')
contact_email = form.cleaned_data.get('contact_email', '')
email_content = form.cleaned_data.get('message', '')
email = EmailMessage(
subject="New contact form submission",
body=email_content,
to=('support#somedomain.com',),
from_email=f'{contact_name} <{contact_email}>',
reply_to=(contact_email,),
)
email.send()
messages.success(request,
"Your email has been sent. Thanks for contacting us, we'll get back to you shortly")
return redirect('contact')
context = {'form': form}
return render(request, 'pages/contact.html', context)
production email settings:
DEFAULT_FROM_EMAIL = env('DJANGO_DEFAULT_FROM_EMAIL',
default=' <noreply#some_domain.com>')
EMAIL_SUBJECT_PREFIX = env('DJANGO_EMAIL_SUBJECT_PREFIX', default='[some_domain]')
SERVER_EMAIL = env('DJANGO_SERVER_EMAIL', default=DEFAULT_FROM_EMAIL)
# Anymail with Mailgun
INSTALLED_APPS += ("anymail", )
ANYMAIL = {
"MAILGUN_API_KEY": env('DJANGO_MAILGUN_API_KEY'),
"MAILGUN_SENDER_DOMAIN": env('MAILGUN_SENDER_DOMAIN')
}
EMAIL_BACKEND = "anymail.backends.mailgun.EmailBackend"
Your admin emails work because they are using DEFAULT_FROM_EMAIL which is allowed.
Your email provider may not allow you to send emails from the address entered on the contact form.
You should use your email address for the from_email, and use the email address from the form as the reply_to email address.

Django Custom User Email Account Verification

I am looking to add email account verification in Django. I have attempted using the django-registration app to do so, but it doesn't appear that it has been updated to be fully compatible with custom user models which causes too many problems. Is there another reliable and well-documented app out there which will allow me to send a verification email on user registration in django?
How I handle the email registration personally:
First of all, my Profile extending Django Users (models.py):
class Profile(models.Model):
user = models.OneToOneField(User, related_name='profile') #1 to 1 link with Django User
activation_key = models.CharField(max_length=40)
key_expires = models.DateTimeField()
In forms.py, the Registration class :
class RegistrationForm(forms.Form):
username = forms.CharField(label="",widget=forms.TextInput(attrs={'placeholder': 'Nom d\'utilisateur','class':'form-control input-perso'}),max_length=30,min_length=3,validators=[isValidUsername, validators.validate_slug])
email = forms.EmailField(label="",widget=forms.EmailInput(attrs={'placeholder': 'Email','class':'form-control input-perso'}),max_length=100,error_messages={'invalid': ("Email invalide.")},validators=[isValidEmail])
password1 = forms.CharField(label="",max_length=50,min_length=6,
widget=forms.PasswordInput(attrs={'placeholder': 'Mot de passe','class':'form-control input-perso'}))
password2 = forms.CharField(label="",max_length=50,min_length=6,
widget=forms.PasswordInput(attrs={'placeholder': 'Confirmer mot de passe','class':'form-control input-perso'}))
#recaptcha = ReCaptchaField()
#Override clean method to check password match
def clean(self):
password1 = self.cleaned_data.get('password1')
password2 = self.cleaned_data.get('password2')
if password1 and password1 != password2:
self._errors['password2'] = ErrorList([u"Le mot de passe ne correspond pas."])
return self.cleaned_data
#Override of save method for saving both User and Profile objects
def save(self, datas):
u = User.objects.create_user(datas['username'],
datas['email'],
datas['password1'])
u.is_active = False
u.save()
profile=Profile()
profile.user=u
profile.activation_key=datas['activation_key']
profile.key_expires=datetime.datetime.strftime(datetime.datetime.now() + datetime.timedelta(days=2), "%Y-%m-%d %H:%M:%S")
profile.save()
return u
#Sending activation email ------>>>!! Warning : Domain name is hardcoded below !!<<<------
#The email is written in a text file (it contains templatetags which are populated by the method below)
def sendEmail(self, datas):
link="http://yourdomain.com/activate/"+datas['activation_key']
c=Context({'activation_link':link,'username':datas['username']})
f = open(MEDIA_ROOT+datas['email_path'], 'r')
t = Template(f.read())
f.close()
message=t.render(c)
#print unicode(message).encode('utf8')
send_mail(datas['email_subject'], message, 'yourdomain <no-reply#yourdomain.com>', [datas['email']], fail_silently=False)
Now, in views.py, we need to handle all that, let's go :
The register view:
def register(request):
if request.user.is_authenticated():
return redirect(home)
registration_form = RegistrationForm()
if request.method == 'POST':
form = RegistrationForm(request.POST)
if form.is_valid():
datas={}
datas['username']=form.cleaned_data['username']
datas['email']=form.cleaned_data['email']
datas['password1']=form.cleaned_data['password1']
#We generate a random activation key
salt = hashlib.sha1(str(random.random())).hexdigest()[:5]
usernamesalt = datas['username']
if isinstance(usernamesalt, unicode):
usernamesalt = usernamesalt.encode('utf8')
datas['activation_key']= hashlib.sha1(salt+usernamesalt).hexdigest()
datas['email_path']="/ActivationEmail.txt"
datas['email_subject']="Activation de votre compte yourdomain"
form.sendEmail(datas)
form.save(datas) #Save the user and his profile
request.session['registered']=True #For display purposes
return redirect(home)
else:
registration_form = form #Display form with error messages (incorrect fields, etc)
return render(request, 'siteApp/register.html', locals())
The activation views :
#View called from activation email. Activate user if link didn't expire (48h default), or offer to
#send a second link if the first expired.
def activation(request, key):
activation_expired = False
already_active = False
profile = get_object_or_404(Profile, activation_key=key)
if profile.user.is_active == False:
if timezone.now() > profile.key_expires:
activation_expired = True #Display: offer the user to send a new activation link
id_user = profile.user.id
else: #Activation successful
profile.user.is_active = True
profile.user.save()
#If user is already active, simply display error message
else:
already_active = True #Display : error message
return render(request, 'siteApp/activation.html', locals())
def new_activation_link(request, user_id):
form = RegistrationForm()
datas={}
user = User.objects.get(id=user_id)
if user is not None and not user.is_active:
datas['username']=user.username
datas['email']=user.email
datas['email_path']="/ResendEmail.txt"
datas['email_subject']="Nouveau lien d'activation yourdomain"
salt = hashlib.sha1(str(random.random())).hexdigest()[:5]
usernamesalt = datas['username']
if isinstance(usernamesalt, unicode):
usernamesalt = usernamesalt.encode('utf8')
datas['activation_key']= hashlib.sha1(salt+usernamesalt).hexdigest()
profile = Profile.objects.get(user=user)
profile.activation_key = datas['activation_key']
profile.key_expires = datetime.datetime.strftime(datetime.datetime.now() + datetime.timedelta(days=2), "%Y-%m-%d %H:%M:%S")
profile.save()
form.sendEmail(datas)
request.session['new_link']=True #Display: new link sent
return redirect(home)
Finally, in urls.py:
url(r'^register/$', 'register'),
url(r'^activate/(?P<key>.+)$', 'activation'),
url(r'^new-activation-link/(?P<user_id>\d+)/$', 'new_activation_link'),
With all that you should have something to start with, use the appropriate templatetags in the .txt emails and HTML and it should work.
NB: This code isn't perfect, there is duplication (for instance, the generation of the random key could be defined in a function), but it does the job. Also: the activation key is not generated using proper cryptographic functions. An alternative is to use a function like the following to generate the keys:
from django.utils.crypto import get_random_string
def generate_activation_key(username):
chars = 'abcdefghijklmnopqrstuvwxyz0123456789!##$%^&*(-_=+)'
secret_key = get_random_string(20, chars)
return hashlib.sha256((secret_key + username).encode('utf-8')).hexdigest()
NB2: Django send_mail doesn't provide any tools to authenticate your emails. If you want to authenticate your emails (DKIM, SPF), I advise you to look into this: https://djangosnippets.org/snippets/1995/
NB3: There is a security issue with the view new_activation_link: it should check if the user requesting the re-send is the right one and also if he isn't already authenticated. I let you correct that.
You may also be interested in the simple but powerful django-verified-email-field.
Simply use VerifiedEmailField in Your forms:
from django import forms
from verified_email_field.forms import VerifiedEmailField
class RegistrationForm(forms.ModelForm):
email = VerifiedEmailField(label='email', required=True)
Or in Your models:
from django.db import models
from verified_email_field.models import VerifiedEmailField
class User(models.Model):
email = VerifiedEmailField('e-mail')
It renders two input fields: e-mail and verification code. The verification code is sent to the e-mail address using AJAX or during field's clean if there is no valid code for given e-mail, so it works even without javascript.

Using twython-django to authenticate a user when they submit a form

I'm building a Django app and am trying to use twython-django to authenticate a Twitter user when they submit a form. I have tried to edit my views.py, urls.py and models.py files as suggested by this example https://github.com/ryanmcgrath/twython-django/tree/master/twython_django_oauth but I'm simply guessing at it so I'm sure that's why it isn't working.
Could you please help me out with how to get this working? I'm completely new to Twitter wrappers so any help would very much be appreciated.
The flow I'm trying to achieve:
User submits a message through the form
User is asked to authenticate their Twitter account on hitting "Submit" button
User's message, Twitter name, Twitter screen_name, profile_image_url and followers_count are saved in the database (I'm using Heroku Postgres)
User's profile image, name, screen_name and message are printed to index.html in a (Twitter-like) feed.
My views.py:
def logout(request, redirect_url=settings.LOGOUT_REDIRECT_URL):
django_logout(request)
return HttpResponseRedirect(request.build_absolute_uri(redirect_url))
def submit(request):
twitter = Twython(
twitter_token=settings.TWITTER_KEY,
twitter_secret=settings.TWITTER_SECRET,
callback_url=request.build_absolute_uri(reverse('alpha.views.submit'))
)
auth_props = twitter.get_authentication_tokens()
request.session['request_token'] = auth_props
return HttpResponseRedirect(auth_props['auth_url'])
form = MessageForm(request.session.get('message'))
if form.is_valid():
new_message = form.save()
return HttpResponseRedirect('/')
else:
request.session['message'] = request.POST
twitter = Twython(
twitter_token = settings.TWITTER_KEY,
twitter_secret = settings.TWITTER_SECRET,
oauth_token = request.session['request_token']['oauth_token'],
oauth_token_secret = request.session['request_token']['oauth_token_secret'],
)
authorized_tokens = twitter.get_authentication_tokens()
try:
user = User.objects.get(username = authorized_tokens['screen_name'])
except User.DoesNotExist:
user = User.objects.create_user(authorized_tokens['screen_name'], authorized_tokens['oauth_token_secret'])
profile = Message()
profile.user = user
profile.name = name
profile.profile_image_url = profile_image_url
profile.oauth_token = authorized_tokens['oauth_token']
profile.oauth_secret = authorized_tokens['oauth_token_secret']
profile.save()
user = authenticate(
username = authorized_tokens['screen_name'],
password = authorized_tokens['oauth_token_secret']
)
login(request, user)
return HttpResponseRedirect(redirect_url)
Disclaimer: I'm a newbie so the above code is probably a complete mess!
Yes, your use-case is different from that intended by twython-django, but that doesn't mean it's not going to work in your case, and you can use the library as it stands with your flow. After setting up everything as described on the main page, you'll need something like this for your views.py:
from django.shortcuts import redirect, reverse
def submit(request):
# initial form submission, first check if we're authenticated
# if we are, process as normal, otherwise redirect to the login
# page. If you've set up twython-django correctly, it'll redirect
# to twitter for the actual login.
if request.method == "POST":
if request.user.is_authenticated():
form = MessageForm(request.POST)
if form.is_valid():
form.save()
return redirect('/')
else:
# Modify this to display validation errors
pass
else:
request.session['message'] = request.POST
# the reverse(submit) resolves this view for redirection
# back from the twitter authentication
return redirect(settings.LOGIN_URL, next=reverse(submit))
# A Get request, where we should first check for the message stored
# We then process the form and remove it from session to prevent
# accidental re-use.
else:
if 'message' in request.session and request.user.is_authenticated():
form = MessageForm(request.session['message'])
del request.session['message']
if form.is_valid():
form.save()
return redirect('/')
else:
# Modify this to display validation errors
pass
else:
# handle the case where this is a get request and the variable
# isn't in session
pass
As for loading their profile image and follower count, those are not currently handled at all by twython django. You can either fork it on github and add them to the TwitterProfile model and add the appropriate code to the thanks view to load those too, or you can add a new model to your code which extends TwitterProfile.
from twython_django_oauth.models import TwitterProfile
from django import models
class ExtendedTwitterProfile(models.Model)
profile = models.OneToOne(TwitterProfile, related_name="extended")
avatar = models.CharField(max_length=255)
followers = models.IntegerField()
And add the code into the submit view to add/update the profile as needed.
extended_profile = ExtendedTwitterProfile.objects.get_or_create(profile=request.user.twitterprofile)
extended_profile.avatar = avatarurl
extended_profile.followers = followercount
extended_profile.save()
You should be able to access those details via
user.twitterprofile.extended.avatar
Although, I have in the past used a url to get the avatar, for example:
# avatar redirection urls
url(r'^avatar/(?P<userid>[0-9A-Za-z_]+)$', redirect_to,
{ 'url' : 'http://api.twitter.com/1/users/profile_image/%(userid)s.json' }, name='avatar' ),
url(r'^avatar/(?P<userid>[0-9A-Za-z_]+)/(?P<size>[a-z]+)$', redirect_to,
{ 'url' : 'http://api.twitter.com/1/users/profile_image?screen_name=%(userid)s&size=%(size)s' } ),
In a template where you want to display the avatar, you simply use and img tag using the url template tag to do the reverse url resolution, like so:
<img src="{% url avatar userid=request.user.username %}" />
As a further pointer, you can also request all of the users' basic details via Twitter's json API
https://twitter.com/users/zandeez.json
For example, will get you my public profile in a form you can use either in python using urllib or even javascript/ajax depending on what you want to do with the follower count.
Hopefully that should get you sorted, if you need any more help fell free to ask.

Problem with pymongo and django unique value

I am writing django app that as a beckend is using mongodb. I am curently writing register part. Here is how I connecto to database in settings.py
if socket.gethostname() == "Production server":
CON = Connection()
DB = CON.fish
else:
CON = Connection()
DB = CON.test
DB.user.ensure_index([("username", ASCENDING),("email",ASCENDING)],unique = True)#,drop_dups=True
Here is mye register view:
def register(request):
"""
handle user registration
code variable is for testing purposes
"""
if request.method== 'GET':
form = RegisterForm(auto_id=False)
code = 1
return render_to_response('register_home.html',locals(),context_instance=RequestContext(request))
elif request.method == 'POST':
form = RegisterForm(request.POST)
if form.is_valid():
password = form.cleaned_data['password']
password_confirmation = form.cleaned_data['password_confirmation']
if password == password_confirmation:
login = form.cleaned_data['login']
email = form.cleaned_data['email']
newsletter = form.cleaned_data['newsletter']
key = register_user(login,email,password,newsletter)
if key:
#send email
send_mail("Dziękujemy za rejestrację"," Klucz aktywacyjny to " + key,settings.EMAIL_HOST_USER,[email])
request.session['email'] = email
return redirect(register_success)
else:
code = 4
error = "Login/email taken"
return render_to_response('register_home.html',locals(),context_instance=RequestContext(request))
else:
code = 3
error = "invalid password"
return render_to_response('register_home.html',locals(),context_instance=RequestContext(request))
else:
code = 2
return render_to_response('register_home.html',locals(),context_instance=RequestContext(request))
Here is my function I use to register user:
def register_user(login,email,password,newsletter):
"""
This function will return activation key for this user if user was added successfully or none otherwise
"""
key = generate_activation_key()
user = {
"username":login,
"email":email,
"password":crypt_password(password),
"date_join": datetime.now(),
"key": key
}
if newsletter:
user['newsletter'] = True
try:
settings.DB.user.insert(user,safe = True)
except DuplicateKeyError, error:
logging.debug("error raise during saving user")
return None
except OperationFailure, error:
logging.critical("Cannot save to database")
logging.critical(error)
else:
#we have no errors users is registred
return key
And when I test it in the browser it seems to be working. But I write test for it and it isn't working anymore. Here is code for test:
def test_valid_credentials(self):
#now try to register valid user
data = {'login':'test','password':'zaq12wsx','password_confirmation':'zaq12wsx','terms':True,'newsletter':True,'email':'test#test.com'}
response = self.c.post(reverse('register'),data)
#our user should be registred
self.assertEquals(302, response.status_code,'We dont have benn redirected')
self.assertEqual(len(mail.outbox), 1,'No activation email was sent')
#clen email box
mail.outbox = []
#now try to add another user with the same data
response = self.c.post(reverse('register'),data)
#template should be rendered with error message about used login and email
self.assertEquals(200, response.status_code)#this fails
And here is error that i get.
self.assertEquals(200, response.status_code)
AssertionError: 200 != 302
So user was registred with the same username and email which shoudn't happen. Any sugestions? Thanks in advance
Why don't you use https://github.com/django-mongodb-engine/mongodb-engine it works almost perfect with Django ORM. Works like a charm for me.