Django url unit test comparison of expected view function fails - django

class TestsUrls(SimpleTestCase):
def test_index_url_is_resolved(self):
url = reverse('index')
self.assertEquals(resolve(url).func, index)
I am trying to unit test url to see if it returns the expected view. This assertion fails even though it looks like the functions are the same. I am using function based views, not class based views. Does that have something to do with it?
AssertionError: <function index at 0x11db7cb70> != <function index at 0x11d860ae8>

It's not clear how you get index, but resolve(url).func returns an instance of the python object that is the function. Everything in python are objects, also functions, so you get an instance in memory. When you compare the two objects, you are comparing different instances of the same function. As you can see their addresses in memory are different.
So instead of directly comparing them, compare their name and module:
f = resolve(url).func
self.assertEqual(f.__name__, index.__name__)
self.assertEqual(f.__module__, index.__module__)

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 )

Possible to use mixins in function based views?

Like the title states, I'm wondering if it's possible to use mixins in a function based view. If so, how would I import it? The following code doesn't work:
def payment_method_view(request, MyMixin):
Thanks!
No.
First of all, it makes no sense. A mixin is something to mix into a class. You "patch" certain functions in a mixin. But how would you do that on a function? A function can have attributes, but the idea is that typically a function does not do much with its attributes. It typically has no workflow where it calls attached functions. If you would be able to apply a mixin, that would mean that all of a sudden your function for example has a payment_method_view.get_queryset function. Although that could perhaps be useful, this is not really how functions are designed to be used.
A function typically encodes a form of computation, it is typically not used as some sort of collection that stores named attributes that interact with each other. A class is typically used for that: it contains elements (class attributes and methods), and they can interact with each other.
But furthermore it would result in a lot of problems. A function has no builtin inheritance mechanisms. So it means that if you applied to mixins that patched a function, then there would not be some method resolution order (MRO) that will "guide" super() calls, etc. As a result, very easily this would break.
Syntactically it makes no sense either. You simply defined a function that takes two parameters: request, and MyMixin. The fact that MyMixin happens to be the name of a class, is - according to Python - a coincidence. Function parameters define a scope, so it means that if you would use MyMixin in the function, you would refer to the value that corresponds to the given parameter.
What you typically do to change a function, is writing a decorator. A decorator is a function that takes as input the function, and alters the function, or creates a new one. In that case the decorated function is used. For example we can make a decorator #login_required:
from functools import wraps
def login_required(f):
#wraps(f)
def g(request, *args, **kwargs):
if request.user.user.is_authenticated():
return f(request, *args, **kwargs)
else:
return HttpResponse('Unauthorized', status=401)
return g
Here we thus have defined a function login_required that takes as input a function f, and we construct a new function g. This function takes as parameters request, *args and **kwargs. First g checks if the user that is attached to the request is autheticated (has logged in), if that is the case, we call the given function f with the request, *args, and **kwargs. If not, we return a 401 exception (not autheticated).
Now we can apply our decorator to a function:
#login_required
def payment_method_view(request):
# ...
pass
So now Python will call our login_required function with payment_method_view as parameter, and the result (the g function) will take the place of the payment_method_view. We thus now require the user to be logged in before the original payment_method_view is called.

In Django, how do I deal with an "or" in the url regex once I get to the view?

I'm just learning Django, and am getting stuck with some url logic. I'm trying to allow either a category name or id in the url:
...
url(r'^(?P<booze_q>\w+|\d+)/$','glasses.views.booze'),
...
And then in thew view, only deal with that result once. However, if the url is a string - in this case, Whiskey, I get an error for trying to pass a string where an int is expected. This is the closest I've gotten so far:
def booze(request, booze_q):
booze = get_object_or_404(Booze,Q(pk=booze_q)|Q(name=booze_q))
return render_to_response('booze/detail.html', {'booze': booze})
But this returns an error: invalid literal for int() with base 10: 'Whiskey'
I'm sure it's a pretty easy thing, but this is my first Django app, so any help would be appreciated.
tl;dr: End result, I'd like mysite.com/1/ or mysite.com/Whiskey/ to both call the glasses.views.booze view, and get the object with id=1 or name=Whiskey
This is a common scenario you'll encounter quite often, which is typically handled by resorting to multiple arguments and having views behave differently based on which of the view arguments are then present or not.
What you do is first define a URL pattern that uniquely matches each specific case and then let Django's URL resolver set the arguments accordingly based on which of the patterns was matched.
Here's an example with a class based view, that performs two different queries based on which of the two keyword arguments, booze_id or booze_name, is set:
url(r'^(?P<booze_id>\d+)/$', BoozeDetailView.as_view()),
url(r'^(?P<booze_name>\w+)/$', BoozeDetailView.as_view()),
class BoozeDetailView(DetailView):
model = Booze
def get_object(self):
booze_id = self.kwargs.get('booze_id', None)
booze_name = self.kwargs.get('booze_name', None)
if booze_id:
return self.model.objects.get(id=booze_id)
else:
return self.model.objects.get(name=booze_name)
You will always get a string, even if the string contains a number.
1) You should not have a parameter that could be either an id or something else. One day you will enter an item whose name is a number and your app will fail.
2) When querying for pk with a string django automatically tries to convert it into an integer. You'll have to handle the non-pk case before constructing that query.

Django: grabbing parameters

I'm having the hardest time with what should be super simple. I can't grab the passed parameters in django.
In the browser I type:
http://localhost:8000/mysite/getst/?term=hello
My url pattern is:
(r'^mysite/getst/$', 'tube.views.getsearchterms')
My View is
def getsearchterms(request):
my_term = some_way_to_get_term
return HttpResponse(my_term)
In this case it should return "hello". I am calling the view, but a blank value is returned to me. I've tried various forms of GET....
What should some_way_to_get_term be?
The get parameters can be accesses like any dictionary:
my_term = request.GET['term']
my_term = request.GET.get('term', 'my default term')
By using arbitrary arguments after ? and then catching them with request.GET['term'], you're missing the best features of Django urls module : a consistent URL scheme
If "term" is always present in this URL call it must be meaningful to your application,
so your url rule could look like :
(r'^mysite/getst/(?P<term>[a-z-.]+)/', 'tube.views.getsearchterms')
That means :
That you've got a more SEO-FRIENDLY AND stable URL scheme (no ?term=this&q=that inside)
That you can catch your argument easily in your view :
Like this
def getsearchterms(request,term):
#do wahtever you want with var term
print term

Django get() query not working

this_category = Category.objects.get(name=cat_name)
gives error: get() takes exactly 2 non-keyword arguments (1 given)
I am using the appengine helper, so maybe that is causing problems. Category is my model. Category.objects.all() works fine. Filter is also similarily not working.
Thanks,
Do you have any functions named name or cat_name? If so, try changing them or the variable names you are using and trying again.
The helper maps the Django model manager (Category.objects in this case) back to the class instance of the model via the appengine_django.models.ModelManager. Through the inheritance chain you eventually come to appengine.ext.db.Model.get(cls, keys, **kwargs) so that is why you are seeing this error. The helper does not support the same interface for get that Django does. If you do not want to get by primary key, you must use a filter
To do your query, you need to use the GAE filter function like this:
this_category = Category.objects.all().filter('name =', cat_name).get()