Getting "AttributeError: 'str' object has no attribute 'regex'" in Django urls.reverse - regex

As in the title, I'm getting
AttributeError: 'str' object has no attribute 'regex'
I've seen many valid answers to this, but none of them applied to my code as they identified issues in the urls.py file. My issue is in the views.py file.
I get the exception when using reverse to generate a redirect URL:
HttpResponseRedirect(reverse('changetracker:detail', args))
When I use 'changetracker:detail' in other functions, I don't get the exception.

I'm answering this to share knowledge as I didn't see this particular root cause identified already.
The problem turned out to be that I should be using a keyword argument 'args=args' to pass in URL arguments, not a positional argument:
HttpResponseRedirect(reverse('changetracker:detail', args=args))
Using the positional argument (position 2) caused reverse to use that argument as the URL list and thus raise the AttributeError.

Related

How to use Django's APIRequestFactory with an array of objects?

I have the following test
def test_bulk_post(my_faker,factory):
snippets = [{'code':'print(True)'},{'code':'print(True)'},{'code':'print(True)'}]
assert factory.post('/snippets/',snippets) == True
I am trying to extend the snippets app in the tutorial to accept multiple code objects in a single post request.
Right now this gives me:
/venv/lib/python3.8/site-packages/django/test/client.py(244)encode_multipart()
*** AttributeError: 'list' object has no attribute 'items'
so its not expecting a list.. But I want to give it one. How do I do that?
factory.post by default expects a key, value pairs that goes with multipart/form-data and not list hence error
You should probably set content_type='application/json' to pass data as JSON body
factory.post('/snippets/',snippets, content_type='application/json )

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

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.

django template throws NoReverseMatch error

I had two methods create and update in the views, in which update takes one argument whereas create does not take any. I have decided to turn them into only one function update_create because they were not that different.
This is how the new method in views looks:
def update_create(request, id=None):
This is my urls.py:
url(r'^(\d+)/update/$|create/$', update_create, name='update_create'),
This is how my template looks in templates/list.html
Create a new event
I got this error when using the above code:
NoReverseMatch at /agenda/list/
Reverse for 'update_create' with arguments '()' and keyword arguments '{}' not found.
But, if I use this in my templates instead (I have added an argument), it works without any errors:
Create a new event
Can someone explain what's happening? Why previous code didn't work, and Why the new code is working?
URL pattern (\d+) expects number to be provided as argument. To resolve the issue simply provide urls like this:
url(r'^(\d+)/update/$', update_create, name='update_create'),
url(r'^update/$', update_create, name='update_create'),
As mariodev pointed out, your url pattern was expecting a digit in front of the url. As such, your first url:
Create a new event
would generate a url like /update, which wasn't a valid url. However, the latter url:
Create a new event
would generate a url like /1/update, which was a valid url.
From the django docs: https://docs.djangoproject.com/en/dev/topics/http/urls/
Basically subsequent arguments get parsed on first come first serve, and passed to your view. Another thing to consider when developing is using explicitly named parameters, as the django docs elaborate on.

Django error: 'QueryDict' object has no attribute '_meta'

I am very new to django so this is probably a noob question.
I am trying to reuse django admin's change list view. I've created a admin model and want to provide the changelist template a list of these objects. In my view I have:
def placements(request):
partner_id = request.session.get('partner_id', 0)
self = PlacementAdmin(request.GET, Placement.objects.filter(partner=partner_id))
return render_to_response('publisher/placement/change_list.html', {'cl': self})
I get this error when I try to hit this function from a browser:
'QueryDict' object has no attribute '_meta'
Could anyone tell me what the error is or provide an easier way to accomplish this in case I am on the wrong track completely.
Heres the complete trace:
Request Method: GET
Request URL: http://localhost:8080/publisher/
Django Version: 1.3 beta 1
Exception Type: AttributeError
Exception Value:
'QueryDict' object has no attribute '_meta'
Exception Location: /Users/imran/django_env/lib/python2.6/site-packages/django/contrib/admin/options.py in __init__, line 278
Python Executable: /Users/imran/django_env/bin/python
Python Version: 2.6.1
Python Path:
['.',
'.',
'/Users/imran/Workspaces/publisher/django/pub_admin',
'/Users/imran/django_env/lib/python2.6/site-packages/setuptools-0.6c11-py2.6.egg',
'/Users/imran/django_env/lib/python2.6/site-packages/pip-0.8.1-py2.6.egg',
'/Users/imran/django_env/lib/python26.zip',
'/Users/imran/django_env/lib/python2.6',
'/Users/imran/django_env/lib/python2.6/plat-darwin',
'/Users/imran/django_env/lib/python2.6/plat-mac',
'/Users/imran/django_env/lib/python2.6/plat-mac/lib-scriptpackages',
'/Users/imran/django_env/Extras/lib/python',
'/Users/imran/django_env/lib/python2.6/lib-tk',
'/Users/imran/django_env/lib/python2.6/lib-old',
'/Users/imran/django_env/lib/python2.6/lib-dynload',
'/System/Library/Frameworks/Python.framework/Versions/2.6/lib/python2.6',
'/System/Library/Frameworks/Python.framework/Versions/2.6/lib/python2.6/plat-darwin',
'/System/Library/Frameworks/Python.framework/Versions/2.6/lib/python2.6/lib-tk',
'/System/Library/Frameworks/Python.framework/Versions/2.6/lib/python2.6/plat-mac',
'/System/Library/Frameworks/Python.framework/Versions/2.6/lib/python2.6/plat-mac/lib-scriptpackages',
'/Users/imran/django_env/lib/python2.6/site-packages']
It's best to post the traceback error when posting a question!
That said, the error comes from you passing request.GET to a ModelAdmin admin object which isn't expecting it.
You have a long road of troubles ahead of you though, as you're trying to use the magical change_list view template which is operated on by a collection of even more magical, undocumented template tags, which just doesn't normally appear in the same sentence as new to django.
I think you're on the wrong track simply because django's admin is not easy to hack into.
At a minimum, you'd have to pass in your template a ChangeList object for the cl variable.
If you really want to do this, the only advice I can give is to take a look at django.contrib.admin.options.ModelAdmin.changelist_view() since that's what you're trying to replicate.
Seriously though I'd like to talk you out of this. Django's actually really fun to work with!

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.