Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Which server Django is using?
After we installed the Django, we use the command: python manage.py runserver we can run a server, but I don't know the server is which server, and I searched the django directory, find the server is not in the directory: aircraftdeMacBook-Pro:Django-1.11.2-py2.7.egg ldl$ cd django/ aircraftdeMacBook-Pro:django ldl$ ls __init__.py bin dispatch shortcuts.pyc utils __init__.pyc conf forms template views __main__.py contrib http templatetags __main__.pyc core middleware test apps db shortcuts.py urls So, I have two questions: The server is which web-server, and how can I find its location? If we finish the application, if we use the web-server as the python-web's web-server(means why not apache or nginx)? The port default is 8000, how to change to the 80? -
Facebook permission for posting to Facebook Group from code (from one user only, who is the Group Admin)
I have a facebook user U, who is the admin/creator of a facebook group G. I also have a facebook app APP where U is an administrator. I also have a Python/Django application, where each time a new database record is created (D), a new message is posted automatically on facebook group G by user U saying "message" : "new data D is created" I see here https://developers.facebook.com/docs/graph-api/reference/group/feed#publish that to create a new feed in the group, the facebook app APP needs these two permissions publish_actions and user_managed_groups Is it really necessary that I submit a request to get these two permissions for ALL users who ever Connect with Facebook APP? In all cases it is only the single admin user U who will post to facebook group G, and need to give these permissions - surely there is a more tighter/securer way of achieving this without asking these permissions for every user who uses this app -
How to allow multiple connections to a slow Django view
I have a simple, fairly slow view function in django that looks like this: def example_view(request): context = external_api_call_that_takes_a_long_time_to_return() return render(request, 'template.html', context) When I access the view from two tabs, however, it only runs one of these view functions at a time. The first one takes 10 seconds to load, the second one 10 seconds after that. How do I let my server generate those views concurrently? -
Django: Adding default values to ModelForms
I am working on a small project in django and I am trying to take a form that is filled out by the user and store it in the database. For the form, I am using the ModelForm instead of the standard Form. The user submits the form with the name and description of the group that the form creates. I want to add default values to the form values in the model before I have the new object into the daatabase. Here is the Form.py from django import forms from django.forms import ModelForm from tab.models import Group member_count_choices = (('bronze', '1-4',), ('silver', '5-7',), ('gold', '8-10',), ('platnium', '11+',)) class CreateGroupForm(forms.ModelForm): class Meta: model = Group fields = ['name', 'description'] Here is the views.py from django.shortcuts import render, get_object_or_404, redirect from django.db import transaction from .models import Group, User from .forms import CreateGroupForm, AddMembersFour, AddMembersSeven from .forms import AddMembersTen, AddMembersEleven # the following def is going to be what grabs all of the different groups that # are in the database # filters can be added later def groups(request): # following is all of th actions that are taken after the form is submitted if request.method == 'POST': createGroup = CreateGroupForm(request.POST) … -
How to pass a variable from View to Template
Maybe it's a trivial question, but how can I define a String variable in a Django View, and display it in a template? I tried something like this: views.py: class HomeView(TemplateView): template_name = 'home/home.html' def get(self, request): text = "Hello World" args = {'text': text} return render(request, self.template_name, args) home.html: <p>{{ text }}</p> But it doesn't work, "text" is "undefined". -
AttributeError: <bound method Manager.get of <django.db.models.manager.Manager
I am not very experimented in unittesting, I am getting the error below and I wasn't able to fix, I would appreciate some help please. Thanks This is the returned error: ====================================================================== ERROR: test_authenticate_credentials_for_inactive_user (apps.authentication.tests.test_authentication.AuthenticateCredentialsTest) ---------------------------------------------------------------------- Traceback (most recent call last): File "/usr/local/site-packages/mock/mock.py", line 1297, in patched arg = patching.__enter__() File "/usr/local/site-packages/mock/mock.py", line 1369, in __enter__ original, local = self.get_original() File "/usr/local/site-packages/mock/mock.py", line 1343, in get_original "%s does not have the attribute %r" % (target, name) AttributeError: <bound method Manager.get of <django.db.models.manager.Manager object at 0x00000000015bd168>> does not have the attribute 'has_expired' This is the code: class ExpiringTokenAuthentication(TokenAuthentication): """ Extends token auth with inactivity expiration mechanism. """ model = ExpiringToken def authenticate_credentials(self, key): try: token = self.model.objects.get(key=key) except self.model.DoesNotExist: raise exceptions.AuthenticationFailed('Invalid token') if not token.user.is_active: raise exceptions.AuthenticationFailed('Invalid user') if token.has_expired(): raise exceptions.AuthenticationFailed('Token has expired') unittest: class AuthenticateCredentialsTest(TestCase): def setUp(self): self.ExpiringTokenAuth = ExpiringTokenAuthentication() @patch('apps.authentication.authentication.ExpiringTokenAuthentication.model.objects.get') @patch('apps.authentication.authentication.ExpiringTokenAuthentication.model.objects.get.user.is_active') @patch('apps.authentication.authentication.ExpiringTokenAuthentication.model.objects.get.has_expired') def test_authenticate_credentials_for_inactive_user(self, mock_token, active_user, expired_token): active_user.return_value = True expired_token.return_value = False with self.assertRaises(exceptions.AuthenticationFailed) as ea: self.ExpiringTokenAuth.authenticate_credentials('valid key') -
Imp load source cant load through import django model
File main.py has: imp.load_source('views.py', '/home/user/project/project/statistics/graphs/views.py') File views.py has at start: from django.shortcuts import render from django.views.generic import View from statistics.map.models import TestModel I get during main.py is running: module = imp.load_source(file_name, file_path) File "/home/user/project/project/statistics/graphs/views.py", line 4 in <module> from statistics.map.models import TestModel ImportError: No module named statistics.map.models So, question, why django.shortcuts and django.views.generic paths have passed with imp.load_source, but from statistics.map.models import TestModel no and I can't load_source next part of main.py? Thanks. -
Django Ajax request issues with data returned in my template
In my django project i make an ajax call for dynamically display and populate fields. First of all, in my template i create the element: Template html <select class="form-control" onChange="AddOptions(this);"> {% for entry in all_test %} <option id="mainID" value="{{ entry.id }}">{{ entry.descr }}</option> {% endfor %} </select> <div id = "div_val" class="input-group" style="display: none;"> <div class="input-group-btn"> <button id = "btn_val" type="button" class="btn btn-danger">Test</button> </div><!-- /btn-group --> <input type="text" class="form-control"> </div> then in my js: start.js function AddOptions(VarID) { $.ajax({ type: "POST", url: "ajax", data: {mainID: VarID.value}, success: function (data) { $.each(data, function (index) { $("#div_val").show(); console.log("Key: " + data[index].OptionKey+" Val: "+ data[index].OptionVal) }); } }); } urls.py url(r'^ajax$', mainoptions), and finally my python function called from urls.py: from frontend.models import temp_main, temp_case, temp_variables def mainoptions(request): if request.is_ajax(): mainOptions = temp_variables.objects.filter(main_id=int(request.POST['mainID'])) response = [] for i in mainOptions: vallabel = {} vallabel['OptionID'] = i.id vallabel['OptionKey'] = i.v_key vallabel['OptionVal'] = i.v_val response.append(vallabel) json = simplejson.dumps(response) return HttpResponse( json, content_type='application/json' ) else: pass All done, my hidden div "div_val" in template was show, but now i can't understand how can i use the returned data in my template, for, for example, populate the value of the element inside the div (without using jquery … -
python error asd sdasdasdasdasdasdasdasdasdasdsadasdasdasdasdasdas
adssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssgag asdasdasdasddddddddddddddddddddasddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddd **asdasdasdasdaasdasdasdasdasdasdasdsadasdasdasdasdasd***asdasdasdasdasdasdasd*asdsads****asdasdassssssssssssssssasdddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddadsssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddas**** -
Filedownload Issue Django - File becomes practically empty
I am having the following issue with filedownload from product views in Django product site: The issue: Filesize of downloaded file is practically 1kb whilst it should be a normal image filesize (20kb in my example). So the to-download file is present in static folder of the product instance.id (static_cdn/protected/instance.id/image.jpg -- context: product site where user can upload a file to the corresponding product view). However, whenever I try to download it from the product view, it downloads the file with the right filename (including the added instance.id number before the filename), but the filesize is almost null. I think it has to do the with the class ProductDownloadView. Please find the relevant codes below: views.py: class ProductDownloadView(MultiSlugMixin, DetailView): model = Product def get(self, request, *args, **kwargs): obj = self.get_object() filepath = os.path.join(settings.PROTECTED_ROOT, obj.media.path) response = HttpResponse(file(filepath), content_type="application/force-download") response["Content-Disposition"] = "attachment;filename=%s" % (obj.media.name) response["X-SendFile"] = str(obj.media.name) return response models.py class Product(models.Model): user = models.ForeignKey(settings.AUTH_USER_MODEL, null=True, blank=True) managers = models.ManyToManyField(settings.AUTH_USER_MODEL, related_name="managers_product") media = models.FileField(blank=True, null=True, upload_to=download_media_location, storage=FileSystemStorage(location=settings.PROTECTED_ROOT)) def __unicode__(self): return self.title def get_absolute_url(self): view_name = "products:detail_slug" return reverse(view_name, kwargs={"slug": self.slug}) def get_download(self): view_name = "products:download_slug" url = reverse(view_name, kwargs={"slug": self.slug}) return url -
Can I use both Django and Rest Framework views in a single project?
I want to add some REST API views to an existing Django project, which uses vanilla Django views. For that I'd like to use the REST Framework. I wonder if I can I mix Django and RF views in a single project and what pitfalls this might have (e.g. with authentication). -
Web app spawn worker, thread - redis queue vs spawn thread directly
My co-worker wrote this class Worker(object): WORKER_LIMIT = 2 queue = Queue() @classmethod def enqueue(cls, _type, args): cls.queue.put((_type, args)) @classmethod def handle_event(cls, event): pass @classmethod def worker(cls): while True: event = cls.queue.get(True) cls.handle_event(event) cls.queue.task_done() @classmethod def start(cls): for i in range(cls.WORKER_LIMIT): w = Thread(target=cls.worker) w.daemon = True w.start() worker = Worker() worker.start() He use that to spawn a background process to run heavy task (which is great). But I have a bad felling about this. Is this make a lot of zombie? Our app server run with nginx and gunicorn. I myself will use some redis task queue to send job to out side worker. I don't like the idea of spawn thread directly from web app. Do you guys have any idea? -
Algolia model integration within Django - possible ways to handle various field types
I have a model with various different field types that I want the Algolia search engine to index correctly, so far I have been able to handle models.char_fields pretty straightforwardly - I'm now thinking, how best to index various other field types (e.g., Foreign Keys "Objects", ImageFields, DateTime fields etc etc). One thing I have noticed is that Algolio will fetch and store a DateTimeField as Unix standard time...so, originally I thought I could render something human readable on the template using {% humanize %}, but to no luck. I was wondering if anyone knew of ways of dragging out useful information from the model - one idea I have had is to grab the object within the view and then bring out a unique identify for each returned object, then work some conidtional flow to marry up that unique ident to the model, then I can work with that model as normal...? Such as: def instant_search(request): posts = Post.published.all() context = { 'appID': settings.ALGOLIA['APPLICATION_ID'], 'searchKey': settings.ALGOLIA['SEARCH_API_KEY'], 'indexName': get_adapter(Post).index_name, 'posts': posts, } return render(request, 'blog/frame/instant_search.html', context) The within the template I can use {% for posts in post %} {% if post.id = _highlightResult.id.value %} ...do somestuff {% endif %} … -
phonebook application, how to add for user an unlimited amount of phone numbers?
I'm new in django. Trying to create a simple phone book web application. When I'm creating a contact I need to add to that user an unlimited amount of phone numbers with different types (cell phone, home phone, work phone, etc.) For example: for user1 I need to add 5 numbers, for user2 add 10 numbers. How should I do this? -
social auth django authentication Google
when authentication with google is completed the user is created in django.auth.user with all the correct fields but not logged in. It basically redirects to the redirect URL but doesn't log in the user. I've tried several other projects including this one: https://simpleisbetterthancomplex.com/tutorial/2016/10/24/how-to-add-social-login-to-django.html But same issue. Authentication and everything is all good. redirects back to url, creates django.auth.user but doesn't log the user in after redirecting. I can go into django admin and login there but I would like it to automatically log the user in after the redirect from google. Any help would be appreciated :) -
Django AttributeError: 'RegexURLResolver' object has no attribute '_urlconf_module'
When deploying my djangocms project I keep getting this AttributeError. On my local machine everything runs smoothly in the pycharm testserver. On my VPS i have also setup a virtualenv and installed all the requirements I use python 3.6 and os is ubunto 16.04. Please advice which possible checks I can take to resolve this issue. [wsgi:error] [pid 1224:tid 140015438874368] mod_wsgi (pid=1224): Exception occurred processing WSGI script '/var/www/html/geocms/geocms/wsgi.py'. [wsgi:error] [pid 1224:tid 140015438874368] [Traceback (most recent call last): [wsgi:error] [pid 1224:tid 140015438874368] File "/var/www/html/geocms/geocms_env/lib/python3.6/site-packages/django/core/urlresolvers.py", line 393, in urlconf_module [wsgi:error] [pid 1224:tid 140015438874368] return self._urlconf_module [wsgi:error] [pid 1224:tid 140015438874368] AttributeError: 'RegexURLResolver' object has no attribute '_urlconf_module' -
Confusion with Queryset.annotate()
I have two models: class Property(models.Model): # code here... class AccommodationType(models.Model): property = models.ForeignKey(Property, related_name='accommodation_types') # rest of code here... What I'm trying to to is to annotate Property's queryset with count of related AccommodationType's and filter it by the value of this count. So here is my code: qs = Property.objects.all() qs.annotate(acc_types_count=Count('accommodation_types')) filtered = qs.filter(acc_types_count=1) and here I got the error: django.core.exceptions.FieldError: Cannot resolve keyword 'acc_types_count' into field. Choices are: # ...rest of the fields Where I am wrong? -
Trying to install django-haystack
Hello Im trying to install django-haystack on a debian 7 x86 but it is impossible to install, this debian is fresh installation, I compiled python 3.6, I am little disappointed, this the error i get 100% |ââââââââââââââââââââââââââââââââ| 389kB 9.0kB/s Complete output from command python setup.py egg_info: Download error on https://pypi.python.org/simple/setuptools_scm/: [Errno -2] Name or service not known -- Some packages may not be found! Download error on https://pypi.python.org/simple/setuptools-scm/: [Errno -2] Name or service not known -- Some packages may not be found! Couldn't find index page for 'setuptools_scm' (maybe misspelled?) Download error on https://pypi.python.org/simple/: [Errno -2] Name or service not known -- Some packages may not be found! No local packages or working download links found for setuptools_scm Traceback (most recent call last): File "<string>", line 1, in <module> File "/tmp/pip-build-sc1wwqz8/django-haystack/setup.py", line 68, in <module> setup_requires=['setuptools_scm'], File "/usr/local/opt/python-3.6.1/lib/python3.6/distutils/core.py", line 108, in setup _setup_distribution = dist = klass(attrs) File "/root/cubapk/lib/python3.6/site-packages/setuptools/dist.py", line 315, in __init__ self.fetch_build_eggs(attrs['setup_requires']) File "/root/cubapk/lib/python3.6/site-packages/setuptools/dist.py", line 361, in fetch_build_eggs replace_conflicting=True, File "/root/cubapk/lib/python3.6/site-packages/pkg_resources/__init__.py", line 850, in resolve dist = best[req.key] = env.best_match(req, ws, installer) File "/root/cubapk/lib/python3.6/site-packages/pkg_resources/__init__.py", line 1122, in best_match return self.obtain(req, installer) File "/root/cubapk/lib/python3.6/site-packages/pkg_resources/__init__.py", line 1134, in obtain return installer(requirement) File "/root/cubapk/lib/python3.6/site-packages/setuptools/dist.py", line 429, in fetch_build_egg return cmd.easy_install(req) File … -
Using Django, How can i check the user is really permitted on updating post
I want update something on the already existing post. So i used javascript jQuery like this, $('#testButton').click(function () { $.ajax({ url:"/tutomain/detail/1/", type:"post", data:{ goingData : 'blah_blah' }, dataType :'json', }) }); In this case, Even i modify this javascript manually from chrome developers tools(F12 console), the chrome console says like this, and this wouldn't be changed for several post requests. Accept:application/json, text/javascript, */*; q=0.01 Accept-Encoding:gzip, deflate, br Accept-Language:ko-KR,ko;q=0.8,en-US;q=0.6,en;q=0.4 Connection:keep-alive Content-Length:11 Content-Type:application/x-www-form-urlencoded; charset=UTF-8 Cookie:sessionid=sg2l85bxk6z5vkth6gpa; csrftoken=SdNbr42GaSJJCwRMdmTs0F9MeoirDLNY5v2iYk2 Host:127.0.0.1:8000 Origin:http://127.0.0.1:8000 Referer:http://127.0.0.1:8000/tutomain/ User-Agent:Mozilla/5.0 (Windows NT 6.1; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/58.0.3029.110 Safari/537.36 X-CSRFToken:SdNbr42GaSJJCwSzsZEXe4XqbFiRMdmTs0F9MeoirDLNY5v2iYk2 X-Requested-With:XMLHttpRequest What i wonder is that, How can i check the POST request is really validated request, not a maliciously modified, hacked request. In other words, I want to check whether the user of that 'update request' has been permitted. EDIT: Sorry for edit, What i want to know is also like, 'the mechanism of validating specific user or user permission in django'. -
Efficient join using Django REST Framework serializers
I am using the below set of serializers to achieve a join, which work fine on my development setup, but performs terribly when there is any distance between the website server and the database server. I got suspicious about the SQL that's running the show and did some logging; it seems that it's doing a new query for every entry and combining the results rather than doing the entire join at once and returning the join like I want. Here are my serializers: class UserSerializer(serializers.ModelSerializer): class Meta: model = User exclude = ('password', 'last_login', 'is_superuser', 'is_staff', 'is_active', 'date_joined', 'groups', 'user_permissions') class DepartmentSerializer(serializers.HyperlinkedModelSerializer): curator = UserSerializer() class Meta: model = Department fields = '__all__' class CategorySerializer(serializers.HyperlinkedModelSerializer): class Meta: model = Category fields = '__all__' class DetailedLinkedContentSerializer(serializers.HyperlinkedModelSerializer): category = CategorySerializer() department = DepartmentSerializer() type = serializers.SerializerMethodField() class Meta: fields = '__all__' model = LinkedContent def get_type(self, obj): return 'link' class DetailedFileContentSerializer(serializers.HyperlinkedModelSerializer): category = CategorySerializer() department = DepartmentSerializer() link_url = serializers.SerializerMethodField() type = serializers.SerializerMethodField() class Meta: fields = '__all__' model = FileContent def get_link_url(self, obj): return obj.file.url def get_type(self, obj): return obj.file_type As you can see, I doing my 'join' by including fields in a serializer as serializers of other models, such as … -
Django form intergrityerror: foreign key with unique field, unique constraint fails
When trying to add a second appointment (for the same date) which has a dayplan foreign key using ModelForm and CreateView, unique constraint fails due to DayPlan having 'date' field as unique. This issue is not present using the django-admin create form. I tried to remove the unique=True from dayplan.date to see what happens -> every time i add an appointment, even if dayplan.date exist, a new dayplan is created. the issue seems to be related to these 2 line: daydate = DayPlan.objects.filter(date=planned_date) form.cleaned_data['dayplan'] = daydate The code is here: class DayPlan(models.Model): date = models.DateField(unique=True, db_index=True) comment = models.TextField(null=True, blank=True) def __str__(self): return 'Planning voor {}'.format(self.date) def get_absolute_url(self): return reverse('organizer_dayplan_detail', kwargs={'pk': self.pk}) class Appointment(models.Model): comment = models.CharField(null=True, blank=True, max_length=255) planned_date = models.DateField() doctor = models.ForeignKey(Doctor) visited = models.BooleanField(default=False) dayplan = models.ForeignKey(DayPlan) class AppointCreate(CreateView): model = Appointment form_class = AppointmentForm template_name = 'organizer/organizer_appointment_create.html' # initial = {'doctor': 'pk', 'comment': 'test',} def get_initial(self): return { "doctor": self.request.GET.get('doctor') } def form_valid(self, form): planned_date = form.cleaned_data['planned_date'] try: daydate = DayPlan.objects.filter(date=planned_date) form.cleaned_data['dayplan'] = daydate form.instance.save() except: daydate = DayPlan.objects.create(date=planned_date) form.instance.dayplan = daydate form.instance.save() return super(AppointCreate, self).form_valid(form) class AppointmentForm(forms.ModelForm): class Meta: model = Appointment fields = {'comment', 'planned_date', 'doctor', 'visited', 'dayplan'} widgets = {'visited': forms.HiddenInput(),} exclude … -
How to use url tag in django?
I am using Django version 1.10.7. Currently in my html I have: <a href={% url 'home' %}>Home<span style="font-size:16px;" class="pull-right hidden-xs showopacity glyphicon glyphicon-home"></span></a> My project urls.py has from django.conf.urls import include,url from django.contrib import admin from base import views urlpatterns = [ url(r'^admin/', admin.site.urls), url(r'^team/', include('team.urls'), name='team'), url(r'^game/', include('game.urls'), name='game'), url(r'^about/', include('base.urls'), name='about'), url(r'^$', views.home, name='home'), ] And in views.py, from django.shortcuts import render # Create your views here. def about(request): return render(request,'base/about.html',{}) def home(request): return render(request,'base/home.html',{}) This gives the error: NoReverseMatch at / Reverse for 'home' with arguments '()' and keyword arguments '{}' not found. 0 pattern(s) tried: [] Request Method: GET Request URL: http://127.0.0.1:8000/ Django Version: 1.10.7 Exception Type: NoReverseMatch Exception Value: Reverse for 'home' with arguments '()' and keyword arguments '{}' not found. 0 pattern(s) tried: [] How can I fix this? -
Update django page_cache with celery
I have a django view that loads a series of pages (based on a year parameter in the URL) and the page loads very slowly. I'm trying to set it up to cache the different pages. I am using the page_cache in the urls.py file, which is working locally--when I revisit a page for a second time, it loads very quickly. url(r'^reports/missing_item_report/(?P<year>\d+)$', cache_page(900)(vary_on_headers('Accept')( bill_text_report.missing_item_report)), name="missing_item_report"), Because my page will have data that updates, I'm trying to set up a celery task to update the cache every night. I'm a little lost here but here's what I have so far: views.py @periodic_task( run_every=(crontab(minute='*/10')), name="missing_bill_formatitem_report", ignore_result=True) def missing_item_report(request, year=current_year): (the minute=10 is for testing). I have a tasks.py file existing from other people's work, but I am unclear what to put in it, if anything (celery tasks are already functional for other places in the code base) My question is three-pronged (I can split to separate questions if necessary). 1. How can I tell if celery is even working at all? 2. How can I force page_cache to use the celery generated-value? 3. How do I tell celery to generate all the page-views for a given URL, one for every year from … -
AssertRaises not passing error
this test is not passing although it should pass. I have tried couple of workaround and got different errors. I would appreciate some help, Thanks. ERROR: test_authenticate_credentials_with_None_key (apps.authentication.tests.test_authentication.AuthenticateCredentialsTest) ---------------------------------------------------------------------- Traceback (most recent call last): File "/code/apps/authentication/tests/test_authentication.py", line 20, in test_authenticate_credentials_with_None_key self.assertRaises(self.invalid_token, self.ExpiringTokenAuth.authenticate_credentials(None)) File "/code/apps/authentication/authentication.py", line 19, in authenticate_credentials raise exceptions.AuthenticationFailed('Invalid token') AuthenticationFailed: Invalid token Trying to test this: class ExpiringTokenAuthentication(TokenAuthentication): """ Extends token auth with inactivity expiration mechanism. """ model = ExpiringToken def authenticate_credentials(self, key): try: token = self.model.objects.get(key=key) except self.model.DoesNotExist: raise exceptions.AuthenticationFailed('Invalid token') Using this: class AuthenticateCredentialsTest(TestCase): def setUp(self): self.ExpiringTokenAuth = ExpiringTokenAuthentication() self.invalid_token = exceptions.AuthenticationFailed('Invalid token') def test_authenticate_credentials_with_None_key(self): self.assertRaises(self.invalid_token, self.ExpiringTokenAuth.authenticate_credentials(None)) -
Django Admin with Multiple DBs Tries to Creates Record with Wrong One
My Django project uses its own default schema and connects to a legacy schema, and the models.Model child classes for that legacy schema are managed = False. The admin app works fine except when I create a new record in a legacy table. I know Django Admin doesn't explicitly support multiple databases, so I'm using this child class from the official docs in admin.py. Everything has worked fine except when I click add, and I get this traceback. File "/Users/stephen.kasica/Sites/django_project/venv/lib/python2.7/site-packages/django/core/handlers/exception.py" in inner 39. response = get_response(request) File "/Users/stephen.kasica/Sites/django_project/venv/lib/python2.7/site-packages/django/core/handlers/base.py" in _get_response 187. response = self.process_exception_by_middleware(e, request) File "/Users/stephen.kasica/Sites/django_project/venv/lib/python2.7/site-packages/django/core/handlers/base.py" in _get_response 185. response = wrapped_callback(request, *callback_args, **callback_kwargs) File "/Users/stephen.kasica/Sites/django_project/venv/lib/python2.7/site-packages/django/contrib/admin/options.py" in wrapper 544. return self.admin_site.admin_view(view)(*args, **kwargs) File "/Users/stephen.kasica/Sites/django_project/venv/lib/python2.7/site-packages/django/utils/decorators.py" in _wrapped_view 149. response = view_func(request, *args, **kwargs) File "/Users/stephen.kasica/Sites/django_project/venv/lib/python2.7/site-packages/django/views/decorators/cache.py" in _wrapped_view_func 57. response = view_func(request, *args, **kwargs) File "/Users/stephen.kasica/Sites/django_project/venv/lib/python2.7/site-packages/django/contrib/admin/sites.py" in inner 211. return view(request, *args, **kwargs) File "/Users/stephen.kasica/Sites/django_project/venv/lib/python2.7/site-packages/django/contrib/admin/options.py" in add_view 1509. return self.changeform_view(request, None, form_url, extra_context) File "/Users/stephen.kasica/Sites/django_project/venv/lib/python2.7/site-packages/django/utils/decorators.py" in _wrapper 67. return bound_func(*args, **kwargs) File "/Users/stephen.kasica/Sites/django_project/venv/lib/python2.7/site-packages/django/utils/decorators.py" in _wrapped_view 149. response = view_func(request, *args, **kwargs) File "/Users/stephen.kasica/Sites/django_project/venv/lib/python2.7/site-packages/django/utils/decorators.py" in bound_func 63. return func.__get__(self, type(self))(*args2, **kwargs2) File "/Users/stephen.kasica/Sites/django_project/venv/lib/python2.7/site-packages/django/utils/decorators.py" in inner 185. return func(*args, **kwargs) File "/Users/stephen.kasica/Sites/django_project/venv/lib/python2.7/site-packages/django/contrib/admin/options.py" in changeform_view 1441. if form.is_valid(): File "/Users/stephen.kasica/Sites/django_project/venv/lib/python2.7/site-packages/django/forms/forms.py" in is_valid 169. return …