TypeError: expected string or bytes-like object User.id - django

I'm trying to register an new Transaction object on the DB using Django, but I'm having TypeError: expected string or bytes-like object when I try to do user_id = user.id I can't really understand why this is happening, since I do the same steps when registering a new Bank object (as shown on prints below). I've tried to debug and the local variables have the correct value, I've also tried to cast user.id with string or int, but none of them worked.
traceback console error create Transaction method create Bank method
models.py

Firstly, please don't post code or errors as images; they are text, they should be posted as text in the question.
However I don't see anything in any of those snippets that suggest the error is with the user - that line is probably highlighted because it's the last in that multi-line call.
Rather, the error looks to be in the reference to date.today - if that's the datetime.date class, then today is a method, which you would need to call:
Transaction.objects.create(date=date.today(), ... )
Or, since that field has a default anyway, you could leave out the date attribute from the create call altogether.

Related

django-selenium TypeError: 'str' object is not callable

Doing a simple test of a clicking dropdown and seeing if the menu is displayed.
dropdown_user = self.browser.find_element_by_id('dropdown-user')
dropdown_user.click()
expanded = dropdown_user.get_attribute("aria-expanded")
self.assertTrue= (expanded)
settings = self.browser.find_element_by_id('dropdown-user-settings')
self.assertTrue(settings.is_displayed())
Gives me this error when I run the test. I cant figure why settings is a str.
self.assertTrue(settings.is_displayed())
TypeError: 'str' object is not callable
I can't comment (not enough rep) or I would - could you post the whole stack trace? The line self.assertTrue= (expanded) looks like it could feasibly cause an issue.
Edit: I think you're assigning the value of the variable expanded to self.assertTrue, then when you try to call self.assertTrue you're trying to call a string, rather than a function. Remove the line self.assertTrue=(expanded) and replace it with self.assertEqual(expanded, 'true').
Edit 2 to explain in more depth as requested:
The value of expanded is a string - probably 'true', if your dropdown is expanded.
Writing self.assertTrue=(expanded) is the same (in this case) as writing self.assertTrue=expanded. You're assigning the value of the variable expanded (which is a string) to the variable self.assertEqual - it is no longer a function, it's a string!
self.assertTrue(True) # fine
self.assertTrue=('Woops!') # the value of self.assertTrue is now the
# string 'Whoops!'
print(self.assertTrue)
>'Woops!'
self.assertTrue(True) # you're trying to call a string here
> TypeError: 'str' object is not callable
In python, there's nothing to stop you from assigning any type to any variable, because it's dynamically typed.

Django Error On Delete Option in Admin Page

I have a model with information about products. I can delete objects by running the following code.
Items.objects.get(id=3).delete()
However, when I delete from the admin area, I run into a strange error for some products (but not all).
The exception I get is
Exception Type: TypeError
Exception Value: __str__ returned non-string (type MyUser)
Exception Location: /opt/python/run/venv/lib/python3.4/site- packages/django/utils/encoding.py in force_text, line 90
I've tried removing all of my overwritten str methods, and nothing has changed.
The (MyUser type) is my custom implementation of the User in django which I've basically taken directly from the docs.
The traceback shows the local variable "seen" with value "Error in formatting: TypeError: str returned non-string (type MyUser)" in the following function call
roots.extend(self._nested(root, seen, format_callback))
It looks like this is called while creating the tree like structure on the confirm delete page. I'm almost positive none of my str methods return a MyUser object...

Invalid keyword argument on new model entry

I have the following model:
class mark(models.Model):
title=models.CharField(max_length=35)
url=models.URLField(max_length=200)
user=models.ManyToManyField(User,blank=True)
and then I use a form to save some data to the db. My code inside the view that saves the data is:
new_mark= mark(url=request.POST['url'],
title=request.POST['title'],
user=request.user)
new_mark.save()
Of course I have all the data validation, login required validation, etc.
When I run this it throws me an unexpected
'user' is an invalid keyword argument for this function
on theuser=request.user) line. Any ideas what might be wrong?
Please provide the whole traceback and make sure your view has no function named "mark" etc (You probably also want to change mark to Mark to follow Python and Django style guides.) test via print type(mark) before the "new_mark = …" line.
Also I am not 100% sure if a ManyToMany field allows settings data like that, eg try:
new_mark= mark(url=request.POST['url'],
title=request.POST['title'])
new_mark.user.add(request.user)
new_mark.save()
And since it's an m2m field you probably want to rename the field to users.

Django KeyError when getting an object with a keyword for a field name

I wish to get an object in the following fashion:
Collection.objects.get(name='name', type='library', owner=owner, parent=parent)
Unfortunately type is a keyword as thus creates the following error:
KeyError at /forms/create_library
type
Is there a way to disambiguate the meaning of the word type to allow me to specify a field of that name?
Not tested:
Collection.objects.filter(
name__exact='name',
type__exact='library',
owner__exact=owner,
parent__exact=parent)
Query docs: http://docs.djangoproject.com/en/dev/topics/db/queries/
Also consider naming your field differently, mainly not with the same name as a builtin.
OK it turns out the problem was elsewhere. I was doing this in a form and thus using the self.cleaned_data dictionary of input values.
I was attempting to retrieve self.cleaned_data['type'] where in my previous simplification I stated the string 'library'. This was not in fact in the cleaned data of the form and thus threw a KeyError.

Django : Setting a generic (content_type) field with a real object sets it to None

Update 3 (Read This First) :
Yes, this was caused by the object "profile" not having been saved. For those getting the same symptoms, the moral is "If a ForeignKey field seems to be getting set to None when you assign a real object to it, it's probably because that other objects hasn't been saved."
Even if you are 100% sure that it was saved, check again ;-)
Hi,
I'm using content_type / generic foreign keys in a class in Django.
The line to create an instance of the class is roughly this :
tag = SecurityTag(name='name',agent=an_agent,resource=a_resource,interface=an_interface)
Where both agent and resource are content_type fields.
Most of the time, this works as I expect and creates the appropriate object. But I have one specific case where I call this line to create a SecurityTag but the value of the agent field seems to end up as None.
Now, in this particular case, I test, in the preceding line, that the value of an_agent does contain an existing, saved Django.model object of an agent type. And it does.
Nevertheless, the resulting SecurityTag record comes out with None for this field.
I'm quite baffled by this. I'm guessing that somewhere along the line, something is failing in the ORM's attempt to extract the id of the object in an_agent, but there's no error message nor exception being raised. I've checked that the an_agent object is saved and has a value in its id field.
Anyone seen something like this? Or have any ideas?
====
Update : 10 days later exactly the same bug has come to bite me again in a new context :
Here's some code which describes the "security tag" object, which is basically a mapping between
a) some kind of permission-role (known as "agent" in our system) which is a generic content_type,
b) a resource, which is also a generic content_type, (and in the current problem is being given a Pinax "Profile"),
and c) an "interface" (which is basically a type of access ... eg. "Viewable" or "Editable" that is just a string)
class SecurityTag(models.Model) :
name = models.CharField(max_length='50')
agent_content_type = models.ForeignKey(ContentType,related_name='security_tag_agent')
agent_object_id = models.PositiveIntegerField()
agent = generic.GenericForeignKey('agent_content_type', 'agent_object_id')
interface = models.CharField(max_length='50')
resource_content_type = models.ForeignKey(ContentType,related_name='security_tag_resource')
resource_object_id = models.PositiveIntegerField()
resource = generic.GenericForeignKey('resource_content_type', 'resource_object_id')
At a particular moment later, I do this :
print "before %s, %s" % (self.resource,self.agent)
t = SecurityTag(name=self.tag_name,agent=self.agent,resource=self.resource,interface=self.interface_id)
print "after %s, %s, %s, %s" % (t.resource,t.resource_content_type,type(t.resource),t.resource_object_id)
The result of which is that before, the "resource" variable does reference a Profile, but after ...
before phil, TgGroup object
after None, profile, <type 'NoneType'>, None
In other words, while the value of t.resource_content_type has been set to "profile", everything else is None. In my previous encounter with this problem, I "solved" it by reloading the thing I was trying to assign to the generic type. I'm starting to wonder if this is some kind of ORM cache issue ... is the variable "self.resource" holding some kind proxy object rather than the real thing?
One possibility is that the profile hasn't been saved. However, this code is being called as the result of an after_save signal for profile. (It's setting up default permissions), so could it be that the profile save hasn't been committed or something?
Update 2 : following Matthew's suggestion below, I added
print self.resource._get_pk_value() and self.resource.id
which has blown up saying Profile doesn't have _get_pk_value()
So here's what I noticed passing through the Django code: when you create a new instance of a model object via a constructor, a pre-init function called (via signals) for any generic object references.
Rather than directly storing the object you pass in, it stores the type and the primary key.
If your object is persisted and has an ID, this works fine, because when you get the field at a later date, it retrieves it from the database.
However -- if your object doesn't have an ID, the fetch code returns nothing, and the getter returns None!
You can see the code in django.contrib.contenttypes.generic.GenericForeignKey, in the instance_pre_init and __get__ functions.
This doesn't really answer my question or satisfy my curiosity but it does seem to work if I pull the an_agent object out of the database immediately before trying to use it in the SecurityTag constructor.
Previously I was passing a copy that had been made earlier with get_or_create. Did this old instance somehow go out of date or scope?