django get_profile error - django

I want to get my userprofile id in the views i have already included below in settings.py
AUTH_PROFILE_MODULE = 'users.UserProfile'
views code:
def savecontent(request):
try:
logging.debug("=========================== in save content")
logging.debug(dir(request.user))
my_id = request.user.get_profile().id
logging.debug(my_id)
Error is:
2012-07-17 13:00:00,564 ERROR Error while saing content
Traceback (most recent call last):
File "/opt/labs/labs_site/content/views.py", line 21, in savecontent
my_id = request.user.get_profile().id
File "/opt/labs/django/django/utils/functional.py", line 185, in inner
return func(self._wrapped, *args)
AttributeError: 'AnonymousUser' object has no attribute 'get_profile'

AttributeError: 'AnonymousUser' object has no attribute 'get_profile'
You must have an authenticated user to retrieve a profile, that's your problem
#login_required
def foo(request):
profile_id = request.user.get_profile().id

Related

Django - Unit test an object has been deleted - how to use assertRaise / DoesNotExist exception

I would lioke some help to unit test a function that deletes an object in a Django app
The problem
I display a list of values, it includes a bin icon to delete one value, and my view seems to work fine (at least according to the test I made).
How can I unit test it? I'm not able to find out the right way to do yet.
I searched the web and found the DoesNotExist exception, but I'm afraid I'm not able to use it, as I got a matching query does not exist error.
Could you please advise me on how to proceed?
What I tried
Here is my current whole code for the test:
class TestAdmUsers(TestCase):
def setUp(self):
self.company = create_dummy_company("Société de test")
self.usr11 = create_dummy_user(self.company, "user11")
self.usr13 = create_dummy_user(self.company, "user13")
self.usr14 = create_dummy_user(self.company, "user14")
self.client.force_login(self.user_staff.user)
def test_delete_user(self):
test_usercomp_id = self.usr13.id
url = reverse("polls:adm_delete_user", args=[self.company.comp_slug, self.usr13.id])
response = self.client.get(url, follow=True)
self.assertRaises(UserComp.DoesNotExist, UserComp.objects.get(id=test_usercomp_id))
The test log is the following:
Creating test database for alias 'default'...
System check identified no issues (0 silenced).
E
======================================================================
ERROR: test_delete_user (polls.tests_admin.TestAdmUsers)
----------------------------------------------------------------------
Traceback (most recent call last):
File "D:\Mes documents\Informatique\Developpement\Votes AG\projet_votes\polls\tests_admin.py", line 136, in test_delete_user
self.assertRaises(UserComp.DoesNotExist, UserComp.objects.get(id=test_usercomp_id))
File "C:\Users\Christophe\.virtualenvs\projet_votes-onIieQ0I\lib\site-packages\django\db\models\manager.py", line 82, in manager_method
return getattr(self.get_queryset(), name)(*args, **kwargs)
File "C:\Users\Christophe\.virtualenvs\projet_votes-onIieQ0I\lib\site-packages\django\db\models\query.py", line 408, in get
self.model._meta.object_name
polls.models.UserComp.DoesNotExist: UserComp matching query does not exist.
----------------------------------------------------------------------
Ran 1 test in 1.763s
FAILED (errors=1)
Destroying test database for alias 'default'...
I made other tests like this one:
def test_delete_user(self):
url = reverse("polls:adm_delete_user", args=[self.company.comp_slug, self.usr13.id])
response = self.client.get(url)
self.assertContains(response, self.usr12.user.username)
self.assertNotContains(response, self.usr13.user.username)
that leads to this:
======================================================================
FAIL: test_delete_user (polls.tests_admin.TestAdmUsers)
----------------------------------------------------------------------
Traceback (most recent call last):
File "D:\Mes documents\Informatique\Developpement\Votes AG\projet_votes\polls\tests_admin.py", line 136, in test_delete_user
self.assertNotContains(response, self.usr13.user.username)
File "C:\Users\Christophe\.virtualenvs\projet_votes-onIieQ0I\lib\site-packages\django\test\testcases.py", line 465, in assertNotContains
self.assertEqual(real_count, 0, msg_prefix + "Response should not contain %s" % text_repr)
AssertionError: 1 != 0 : Response should not contain 'user13'
----------------------------------------------------------------------
Or this one:
def test_delete_user(self):
test_usercomp_id = self.usr13.id
url = reverse("polls:adm_delete_user", args=[self.company.comp_slug, self.usr13.id])
response = self.client.get(url, follow=True)
self.company.refresh_from_db()
self.usr13.refresh_from_db()
users = UserComp.get_users_in_comp(self.company.comp_slug)
self.assertContains(response, self.usr12.user.username)
self.assertNotContains(users, self.usr13)
with the following result:
======================================================================
ERROR: test_delete_user (polls.tests_admin.TestAdmUsers)
----------------------------------------------------------------------
Traceback (most recent call last):
File "D:\Mes documents\Informatique\Developpement\Votes AG\projet_votes\polls\tests_admin.py", line 137, in test_delete_user
self.usr13.refresh_from_db()
File "C:\Users\Christophe\.virtualenvs\projet_votes-onIieQ0I\lib\site-packages\django\db\models\base.py", line 628, in refresh_from_db
db_instance = db_instance_qs.get()
File "C:\Users\Christophe\.virtualenvs\projet_votes-onIieQ0I\lib\site-packages\django\db\models\query.py", line 408, in get
self.model._meta.object_name
polls.models.UserComp.DoesNotExist: UserComp matching query does not exist.
----------------------------------------------------------------------
And this latest one that uses a class method:
def test_delete_user(self):
current_username = self.usr13.user.username
url = reverse("polls:adm_delete_user", args=[self.company.comp_slug, self.usr13.id])
response = self.client.get(url, follow=True)
self.company.refresh_from_db()
self.usr13.refresh_from_db()
self.assertContains(response, self.usr12.user.username)
self.assertNotContains(UserComp.get_users_in_comp(self.company.comp_slug), self.usr13)
but the result is still an error:
`======================================================================
ERROR: test_delete_user (polls.tests_admin.TestAdmUsers)
----------------------------------------------------------------------
Traceback (most recent call last):
File "D:\Mes documents\Informatique\Developpement\Votes AG\projet_votes\polls\tests_admin.py", line 137, in test_delete_user
self.usr13.refresh_from_db()
File "C:\Users\Christophe\.virtualenvs\projet_votes-onIieQ0I\lib\site-packages\django\db\models\base.py", line 628, in refresh_from_db
db_instance = db_instance_qs.get()
File "C:\Users\Christophe\.virtualenvs\projet_votes-onIieQ0I\lib\site-packages\django\db\models\query.py", line 408, in get
self.model._meta.object_name
polls.models.UserComp.DoesNotExist: UserComp matching query does not exist.
----------------------------------------------------------------------
Related application code
Here is the code for the view:
def adm_delete_user(request, comp_slug, usr_id):
del_usr = User.objects.get(pk=usr_id)
msg = "Utilisateur {0} {1} supprimé.".format(del_usr.last_name, del_usr.first_name)
User.objects.get(pk=usr_id).delete()
messages.success(request, msg)
return redirect("polls:adm_users", comp_slug=comp_slug)
And the model:
class UserComp(models.Model):
user = models.OneToOneField(User, on_delete=models.CASCADE, verbose_name="Utilisateur")
company = models.ForeignKey(Company, on_delete=models.CASCADE, verbose_name="Société")
phone_regex = RegexValidator(regex=r'^0[0-9]([ .-]?[0-9]{2}){4}$', message=("Format de numéro de téléphone invalide"))
phone_num = models.CharField("numéro de téléphone", validators=[phone_regex], max_length=14, null=True, blank=True)
is_admin = models.BooleanField("administrateur", default=False)
def __str__(self):
return '%s %s' % (self.user.last_name, self.user.first_name)
class Meta:
verbose_name = "Liens Utilisateurs / Sociétés"
verbose_name_plural = "Liens Utilisateurs / Sociétés"
#classmethod
def create_usercomp(cls, user, company, phone_num='', is_admin=False):
""" Create a new UserComp """
usr_comp = UserComp(user=user, company=company, phone_num=phone_num, is_admin=is_admin)
usr_comp.save()
return usr_comp
#classmethod
def get_users_in_comp(cls, comp_slug):
user_list = cls.objects.filter(company__comp_slug=comp_slug)
return user_list
Complementary search results
Finally, I found some posts here that oriented my tests, but I wasn't able to find the solution:
The most important to me leads me to assertRaise() test
Unfortunately, the one that asked how to use this exception has been closed, and referred to the previous one, but actually there is no information on how to proceed
This other one asking about the exception, and this one related to the error message did not give me any additional information.
assertRaises takes a callable as its (optional) second argument.
Since .get(...) is not a callable, you should use the context manager form instead:
with self.assertRaises(UserComp.DoesNotExist):
UserComp.objects.get(id=test_usercomp_id)

Graphene Returning NoneType Error on Subscription

I'm trying to setup subscription on graphene-django and channels using channels_graphql_ws.
I'm getting the following error when trying to run my subscription query:
An error occurred while resolving field Subscription.onNewComment
Traceback (most recent call last):
File "/Users/noroozim/.pyenv/versions/nexus37/lib/python3.7/site-packages/graphql/execution/executor.py", line 450, in resolve_or_error
return executor.execute(resolve_fn, source, info, **args)
File "/Users/noroozim/.pyenv/versions/nexus37/lib/python3.7/site-packages/graphql/execution/executors/sync.py", line 16, in execute
return fn(*args, **kwargs)
File "/Users/noroozim/.pyenv/versions/nexus37/lib/python3.7/site-packages/channels_graphql_ws/subscription.py", line 371, in _subscribe
register_subscription = root.register_subscription
AttributeError: 'NoneType' object has no attribute 'register_subscription'
Here is what I have in my setup:
# /subscription.py/
class OnNewComment(channels_graphql_ws.Subscription):
comment = Field(types.UserCommentNode)
class Arguments:
content_type = String(required=False)
def subscribe(root, info, content_type):
return [content_type] if content_type is not None else None
def publish(self, info, content_type=None):
new_comment_content_type = self["content_type"]
new_comment = self["comment"]
return OnNewComment(
content_type=content_type, comment=new_comment
)
#classmethod
def new_comment(cls, content_type, comment):
cls.broadcast(
# group=content_type,
payload={"comment": comment},
)
I'm not sure if this is a bug or if I'm missing something.
I found out that graphne's graphiql template doesn't come with websocket support and I had to modify my graphene/graphiql.html file to incorporate websocket to get it to work.

AttributeError: 'tuple' object has no attribute 'get' in views.py

i want to create a registration form but i m getting an attribute error while running the application
from django.shortcuts import render
from basic_app.forms import UserForm,UserProfileInfoForm
def index(request):
return render(request,'basic_app/index.html')
def register(request):
registered=False
if request.method=="POST":
user_form=UserForm(data=request.POST)
profile_form=UserProfileInfoForm(data=request.POST)
if user_form.is_valid() and profile_from.is_valid():
user=user_form.save()
user.setpassword(user.password)
user.save()
profile=profile_form.save(commit=False)
profile.user=user
if 'profile_pic' in request.FILES:
profile.profile_pic=request.FILES['profile_pic']
profile.save()
registered=True
else:
print(user_form.errors,profile_form.errors)
else:
user_form=UserForm()
profile_form=UserProfileInfoForm()
return(request,'basic_app/registration.html',
{'user_form':user_form,
'profile_form':profile_form,
'registered':registered})
output
Internal Server Error: /basic_app/register/
Traceback (most recent call last):
File "C:\Users\Shoaib Khan\AppData\Local\conda\conda\envs\myenv\lib\site-packages\django\core\handlers\exception.py", line 34, in inner
response = get_response(request)
File "C:\Users\Shoaib Khan\AppData\Local\conda\conda\envs\myenv\lib\site-packages\django\utils\deprecation.py", line 93, in call
response = self.process_response(request, response)
File "C:\Users\Shoaib Khan\AppData\Local\conda\conda\envs\myenv\lib\site-packages\django\middleware\clickjacking.py", line 26, in process_response
if response.get('X-Frame-Options') is not None:
AttributeError: 'tuple' object has no attribute 'get'
[24/Dec/2018 15:34:51] "GET /basic_app/register/ HTTP/1.1" 500 61448
That is because of this line:
return(request,'basic_app/registration.html',
{'user_form':user_form,
'profile_form':profile_form,
'registered':registered})
You've actually created a tuple here. Notice the the parenthesis around the three things that you're returning?
This is how you render a template in django:
from django.shortcuts import render
render(request, 'polls/index.html', context)
So in your case this will work:
render(request,'basic_app/registration.html', {
'user_form':user_form,
'profile_form':profile_form,
'registered':registered
})
For more information on render check out its docs
Change this
return(request,'basic_app/registration.html',
{'user_form':user_form,
'profile_form':profile_form,
'registered':registered})
to
return render(request,'basic_app/registration.html',
{'user_form':user_form,
'profile_form':profile_form,
'registered':registered})

Error when loading the word2vec model

I am using the following function to load my word2vec model.
def __init__(self, filename):
print filename
try:
self.model = gensim.models.Word2Vec.load(filename)
except cPickle.UnpicklingError:
load = gensim.models.Word2Vec.load_word2vec_format
self.model = load(filename, binary=True)
However, I am getting the following error when I try to do it.
Traceback (most recent call last):
File "./explore", line 70, in <module>
api_controller.model = Model(sys.argv[1])
File "/home/volka/Documents/projects/word2vec-explorer/explorer.py", line 77, in __init__
self.model = gensim.models.Word2Vec.load(filename)
File "/usr/local/lib/python2.7/dist-packages/gensim/models/word2vec.py", line 1458, in load
model = super(Word2Vec, cls).load(*args, **kwargs)
File "/usr/local/lib/python2.7/dist-packages/gensim/utils.py", line 256, in load
obj = unpickle(fname)
File "/usr/local/lib/python2.7/dist-packages/gensim/utils.py", line 920, in unpickle
return _pickle.loads(f.read())
AttributeError: 'module' object has no attribute 'call_on_class_only'
The genism version I am using in both the versions are 0.12.3.
Please let me know where I am making it wrong?
This is how I tried to remove call_on_class_only.
model = word2vec.Word2Vec(text, sg=0, negative=5, hs=0)
model.save("test_project")
#load, delete and save
model_1 = word2vec.Word2Vec.load("test_project")
del model_1.call_on_class_only
model.save(model_name_2)
It gives me the following error: AttributeError: call_on_class_only
Please help me.

AttributeError: 'WSGIRequest' object has no attribute 'request' on OAuth2Decorator

I ran into an issue using Django on Google App Engine trying to access Google API.
I want to use the decorator, as described in the docs, but I get the same error over and over again:
AttributeError: 'WSGIRequest' object has no attribute 'request'
And the StackTrace:
Internal Server Error: /
Traceback (most recent call last):
File "/Applications/GoogleAppEngineLauncher.app/Contents/Resources/GoogleAppEngine-default.bundle/Contents/Resources/google_appengine/lib/django-1.5/django/core/handlers/base.py", line 115, in get_response
response = callback(request, *callback_args, **callback_kwargs)
File "/Users/johannes/GitHub/itzehoe/dependencies/oauth2client/appengine.py", line 703, in check_oauth
self._create_flow(request_handler)
File "/Users/johannes/GitHub/itzehoe/dependencies/oauth2client/appengine.py", line 734, in _create_flow
redirect_uri = request_handler.request.relative_url(
AttributeError: 'WSGIRequest' object has no attribute 'request'
And some code:
from google.appengine.api import users
from oauth2client.appengine import OAuth2DecoratorFromClientSecrets
from django.shortcuts import render
from django.conf import settings
decorator = OAuth2DecoratorFromClientSecrets(settings.GOOGLE_CLIENT_SECRETS,
'https://www.googleapis.com/auth/admin.directory.group')
#decorator.oauth_required
def index(request):
context = {}
return render(request, 'index.html', context)
The OAuth2Decorator functionality assumes you're wrapping methods in a webapp or webapp2 RequestHandler subclass, it's not designed to work with django views.