'module' object is not callable Django - django

views.py
for user in users:
#for profile in RegistrationProfile.objects.filter(user=user):
#if profile.activation_key_expired():
salt = sha_constructor(str(random())).hexdigest()[:5]
profile.activation_key = sha_constructor(salt+user.username).hexdigest()
user.date_joined = datetime.now()
user.save()
profile.save()
#if Site._meta.installed:
site = Site.objects.get_current()
# else:
site = RequestSite(request)
profile.send_activation_email(site)
context.update({"form" : form})
return render_to_response("registration/registration_complete.html", context)
imports of my views:
import django.contrib.sessions
from django.core.mail import send_mail
from django.core.mail import EmailMessage
from mail_templated import EmailMessage
from django.db.models import Sum
from tinymce.widgets import TinyMCE
from django.utils.encoding import smart_unicode
import datetime
from django.db.models import Q
from django.utils.hashcompat import sha_constructor
from registration.models import RegistrationProfile
import random
from django.contrib.sites.models import Site, RequestSite
this is giving me error ' module' object is not callable..can anyone tell me why? plz tell me what i am missing

I think you should check your imports. random is both a module name and a function inside a module. If you have
import random
Then you need to call random.random instead of just random.

Related

Django - How to get a custom user model with get_object_or_404

I'd like to retrieve an instance of my User class, which extends AbstractBaseUser . I'd also like to filter my users by a primary key using the django get_object_or_404 shortcut, but this won't work:
from django.shortcuts import get_object_or_404
from django.conf import settings
user = get_object_or_404(settings.AUTH_USER_MODEL, pk=pk)
The following exception is raised:
"ValueError at /v1/users/24c47b4a-920e-47c7-902c-80c64c0dd657/
First argument to get_object_or_404() must be a Model, Manager, or QuerySet, not 'str'.
In my settings.py, this is what my AUTH_USER_MODEL looks like:
AUTH_USER_MODEL = 'users.User'
Is there a way to achieve this?
You can try this get_user_model;
from django.contrib.auth import get_user_model
from django.shortcuts import get_object_or_404
from django.conf import settings
user = get_object_or_404(get_user_model(), pk=pk)
Maybe you can use this solution:
from django.shortcuts import get_object_or_404
from django.conf import settings
user = get_object_or_404(get_user_model(), pk=pk)

Emails won't send after upgrading from Django 1.6.x to Django > 1.7.x

I am currently using Django Allauth and a modified version of Django Invitations (https://github.com/bee-keeper/django-invitations). The only thing added is a field for which group to add the user to, and the application works perfectly when Django 1.6.x is being used. I would like to upgrade to Django 1.7.x or 1.8 but this somehow breaks the emailing feature.
The specific piece of code is here:
'import datetime
from django.db import models
from django.utils.translation import ugettext_lazy as _
from django.utils import timezone
from django.utils.crypto import get_random_string
from django.utils.encoding import python_2_unicode_compatible
from django.contrib.sites.models import Site
from django.core.urlresolvers import reverse
from allauth.account.adapter import DefaultAccountAdapter
from allauth.account.adapter import get_adapter
from .managers import InvitationManager
from . import app_settings
from . import signals
...(other code)
def send_invitation(self, request, **kwargs):
current_site = (kwargs['site'] if 'site' in kwargs
else Site.objects.get_current())
invite_url = reverse('invitations:accept-invite',
args=[self.key])
invite_url = request.build_absolute_uri(invite_url)
ctx = {
'invite_url': invite_url,
'current_site': current_site,
'email': self.email,
'key': self.key,
}
email_template = 'invitations/email/email_invite'
get_adapter().send_mail(email_template,
self.email,
ctx)
self.sent = timezone.now()
self.save()
signals.invite_url_sent.send(
sender=self.__class__,
instance=self,
invite_url_sent=invite_url)'
found here (https://github.com/bee-keeper/django-invitations/blob/master/invitations/models.py)
This also references the code from allauth here:
from __future__ import unicode_literals import re
import warnings
import json
from django.conf import settings
from django.http import HttpResponse
from django.template.loader import render_to_string
from django.template import TemplateDoesNotExist
from django.contrib.sites.models import Site
from django.core.mail import EmailMultiAlternatives, EmailMessage
from django.utils.translation import ugettext_lazy as _
from django import forms
from django.contrib import messages
try:
from django.utils.encoding import force_text
except ImportError:
from django.utils.encoding import force_unicode as force_text
from ..utils import (import_attribute, get_user_model,
generate_unique_username,
resolve_url)
from . import app_settings
USERNAME_REGEX = re.compile(r'^[\w.#+-]+$', re.UNICODE)
........ (other code)
def render_mail(self, template_prefix, email, context):
"""
Renders an e-mail to `email`. `template_prefix` identifies the
e-mail that is to be sent, e.g. "account/email/email_confirmation"
"""
subject = render_to_string('{0}_subject.txt'.format(template_prefix),
context)
# remove superfluous line breaks
subject = " ".join(subject.splitlines()).strip()
subject = self.format_email_subject(subject)
bodies = {}
for ext in ['html', 'txt']:
try:
template_name = '{0}_message.{1}'.format(template_prefix, ext)
bodies[ext] = render_to_string(template_name,
context).strip()
except TemplateDoesNotExist:
if ext == 'txt' and not bodies:
# We need at least one body
raise
if 'txt' in bodies:
msg = EmailMultiAlternatives(subject,
bodies['txt'],
settings.DEFAULT_FROM_EMAIL,
[email])
if 'html' in bodies:
msg.attach_alternative(bodies['html'], 'text/html')
else:
msg = EmailMessage(subject,
bodies['html'],
settings.DEFAULT_FROM_EMAIL,
[email])
msg.content_subtype = 'html' # Main content is now text/html
return msg
def send_mail(self, template_prefix, email, context):
msg = self.render_mail(template_prefix, email, context)
msg.send()'
found at (allauth/account/adapter.py)
The form always saves an invitation element into the database but breaks at the sending email line. (all infor stored is correct, so that isn't breaking it). If the email is removed, all code afterwards runs fine. I have even tried to just send a basic email like such in place:
from django.core.mail import EmailMessage
msg = EmailMessage("TEST", "HELLO", my_email, [some_email])
msg.send()
but this, too does not send emails.
I am hoping this is super simple, but any help would be appreciated.
I had the same problem, the execution just hung when running this code in a django shell (Django 1.7):
from django.core.mail import send_mail
send_mail('Subject here', 'Here is the message.', 'from#example.com',
['to#example.com'], fail_silently=False)
Following the Django docs on email settings, I used in settings.py:
EMAIL_USE_TLS = False
EMAIL_USE_SSL = True
EMAIL_PORT = 465
This worked.

How to create a django-allauth regular and social account for testing purposes?

I managed to create a regular user as happens when signing in with Django-allauth.
I've been trying to do the same for a social account (Github) but I am really struggling. I assume there must be people out here that had to make a social account for testing purposes. Could anyone show how they did that?
Also, if you know a better way to create a regular user this is highly appreciated.
The following snippet from the django-allauth tests shows how to do this:
from allauth.account import app_settings as account_settings
from allauth.account.models import EmailAddress
from allauth.account.utils import user_email
from allauth.socialaccount.helpers import complete_social_login
from allauth.socialaccount.models import SocialApp, SocialAccount, SocialLogin
from allauth.utils import get_user_model
from django.contrib.auth.models import AnonymousUser
from django.contrib.auth.models import User
from django.contrib.messages.middleware import MessageMiddleware
from django.contrib.sessions.middleware import SessionMiddleware
from django.test import TestCase
from django.test.client import Client
from django.test.client import RequestFactory
from django.test.utils import override_settings
class SocialAccountTests(TestCase):
#override_settings(
SOCIALACCOUNT_AUTO_SIGNUP=True,
ACCOUNT_SIGNUP_FORM_CLASS=None,
ACCOUNT_EMAIL_VERIFICATION=account_settings.EmailVerificationMethod.NONE # noqa
)
def test_email_address_created(self):
factory = RequestFactory()
request = factory.get('/accounts/login/callback/')
request.user = AnonymousUser()
SessionMiddleware().process_request(request)
MessageMiddleware().process_request(request)
User = get_user_model()
user = User()
setattr(user, account_settings.USER_MODEL_USERNAME_FIELD, 'test')
setattr(user, account_settings.USER_MODEL_EMAIL_FIELD, 'test#test.com')
account = SocialAccount(user=user, provider='openid', uid='123')
sociallogin = SocialLogin(account)
complete_social_login(request, sociallogin)
user = User.objects.get(
**{account_settings.USER_MODEL_USERNAME_FIELD: 'test'}
)
self.assertTrue(
SocialAccount.objects.filter(user=user, uid=account.uid).exists()
)
self.assertTrue(
EmailAddress.objects.filter(user=user,
email=user_email(user)).exists()
)

Custom template in django form wizard - NameError

I am trying to create custom templates for a simple contact form as per the django docs but I am getting a NameError. Looks like a simple issue but I can't figure it out. Any help will be greatly appreciated. The error message is:
"NameError at /contact/
name 'wizardcustomtemplate' is not defined"
where 'wizardcustomtemplate' is the app. Here is my code:
urls.py
from django.conf.urls import patterns, include, url
from django.contrib import admin
admin.autodiscover()
from wizardcustomtemplate.forms import SubjectForm, SenderForm, MessageForm
from wizardcustomtemplate.views import ContactWizard
urlpatterns = patterns('',
url(r'^admin/', include(admin.site.urls)),
url(r'^contact/$', ContactWizard.as_view(FORMS)),
)
views.py
import os
from django.shortcuts import render
from django.shortcuts import render_to_response
from django.http import HttpResponse
from django.http import HttpResponseRedirect
from django.core.mail import send_mail
from django.core.context_processors import csrf
from django.contrib.formtools.wizard.views import SessionWizardView
from django.contrib.formtools.wizard.views import WizardView
from django.core.files.storage import FileSystemStorage
from django.core.files import File
FORMS = [("0", wizardcustomtemplate.forms.SubjectForm),
("1", wizardcustomtemplate.forms.SenderForm),
("2", wizardcustomtemplate.forms.MessageForm)
]
TEMPLATES = {"0": "wizardcustomtemplate/subject.html",
"1": "wizardcustomtemplate/sender.html",
"2": "wizardcustomtemplate/message.html"
}
class ContactWizard(SessionWizardView):
def get_template_names(self):
return [TEMPLATES[self.steps.current]]
def done(self, form_list, **kwargs):
form_data = process_form_data(form_list)
return render_to_response('wizardcustomtemplate/thanks.html', {'form_data': form_data})
def process_form_data(form_list):
form_data = [form.cleaned_data for form in form_list]
return form_data
forms.py
from django import forms
class SubjectForm(forms.Form):
subject = forms.CharField(max_length = 100,initial='Wizard')
class SenderForm(forms.Form):
sender = forms.EmailField(initial='abcd#efgh.org')
class MessageForm(forms.Form):
message = forms.CharField(initial='How r u?')
The form wizard works fine if I don't use the custom templates (FORMS, TEMPLATES etc.) Please let me know if you need additional information.
Solved it by adding import wizardcustomtemplate in views.py as suggested by #Rohan.

Can't accessing Django profile with query from db while it get profile of logged in user

I am developing a site in Django and having two types of profiles. One of them named Person. So I am trying to access a Person object, using following code:
from django.contrib.auth.forms import UserCreationForm
from django.template import RequestContext
from django.shortcuts import render_to_response,get_object_or_404
from django.core import urlresolvers
from django.http import HttpResponseRedirect
from django.contrib.auth.decorators import login_required
from accounts.forms import UserRegistrationForm, UserProfileForm
from pprint import pprint
from django.http import HttpResponse
from models import User
from models import UserProfile
def profile(request, url,template_name='person/profile.html'):
user=User(username=url).get_profile().person;
return HttpResponse(user)
And it gives error:
DoesNotExist at /p/Haafiz/
UserProfile matching query does not exist.
At another place, I am trying to do so with following code:
from django.contrib.auth.forms import UserCreationForm
from django.template import RequestContext
from django.shortcuts import render_to_response,get_object_or_404
from django.core import urlresolvers
from django.http import HttpResponseRedirect
from django.contrib.auth.decorators import login_required
from accounts.forms import UserRegistrationForm, UserProfileForm
from pprint import pprint
from django.http import HttpResponse
from accounts.forms import UserProfile
#login_required
def dashboard(request,template_name="account/dashboard.html"):
return HttpResponse(request.user.get_profile().person)
And in this case, it is working fine. What can be problem at first place where I am trying to access profile from object getting from db? Both these cases seems same to me but it is having problem in the above one.
User(name=url) just generate an instance of User,not query the database for certain user.
Change
user=User(username=url).get_profile().person
to
user = User.objects.get(username=url).get_profile().person