Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
mod_wsgi runtime using old python version
I'm running a django server on httpd service. I had to upgrade my python version(2.7.12). After installing the new python I rebuild the mod_wsgi with the new python (using with-python argument). I also rebuild the mod_python with the new python version. My new python path is /usr/local/bin/python2.7. In the /etc/httpd/conf.d/django.conf I added the following line : WSGIPythonHome /usr/local. However I see this error in my error_log file (httpd error log): [Tue Sep 20 12:32:12.743338 2016] [:warn] [pid 8567:tid 139972130834496] mod_wsgi: Compiled for Python/2.7.12. [Tue Sep 20 12:32:12.743376 2016] [:warn] [pid 8567:tid 139972130834496] mod_wsgi: Runtime using Python/2.7.5. What i'm missing ? FYI : I cannot change or redirect the default python that exists in /usr/bin/python because this affect centos package management. -
Django sometimes leaks %20 instead of space
I am totally confused as to what is going on here. I am sending a string containing spaces to my Django app using the url. When I testrun locally using the development server I get the string encoded using " " and everything is fine. Later on my deployed server using nginx I get "%20" in the string instead of " ". I don't even know where to start debugging this. I thought such translations were made by Django and hence the behaviour would be the same. I am totally new at all this web stuff so I don't know where to start looking for a solution. Can someone perhaps point me in the right direction? -
Getting JSON data as QueryDict
I am using Django REST Framework and have this code to do a PUT call: $.ajax({ url: '/api/v1/order/'+orderid+'/', type: 'PUT', data: { book: true } }); and this is the view that handles that: @api_view(['PUT', 'POST']) @authentication_classes((SessionAuthentication, TokenAuthentication, BasicAuthentication)) @permission_classes((IsAuthenticated,)) def api_orderbook(request, orderid): logger.debug(request.data) if request.method == 'PUT' and request.data.get("book") == True: ... do stuff ... But, the request.data.get("book") is not a boolean, but a string: <QueryDict: {u'book': [u'true']}> When I use JSON.stringify({ book: true }) in my Ajax call, it is even worse: <QueryDict: {u'{"book":true}': [u'']}> How can I get the Javascript object as a correct Python QueryDict in my code? -
Django detecting not needed changes
django 1.10, py 3.5 Here's my Enum-like class: @deconstructible class EnumType(object): @classmethod def choices(cls): attrs = [i for i in cls.__dict__.keys() if i[:1] != '_' and i.isupper()] return tuple((cls.__dict__[attr], cls.__dict__[attr]) for attr in attrs) def __eq__(self, other): return self.choices() == other.choices() Here's an example of the class: class TransmissionType(EnumType): TRANSMISSION_PROGRAM = 'TRANSMISSION_PROGRAM' INFO_PROGRAM = 'INFO_PROGRAM' SPORT_PROGRAM = 'SPORT_PROGRAM' Here's how i use it on a model: type = models.TextField(choices=TransmissionType.choices(), db_index=True, default=None) I think I made everything right according to the current django deconstruct docs but apparently makemigration script still creates everytime migration like this: operations = [ migrations.AlterField( model_name='transmission', name='type', field=models.TextField(choices=[('TRANSMISSION_PROGRAM', 'TRANSMISSION_PROGRAM'), ('INFO_PROGRAM', 'INFO_PROGRAM'), ('SPORT_PROGRAM', 'SPORT_PROGRAM')], db_index=True, default=None), ), ] -
How to reverse url for custom Django method?
I want to have a custom route: /person/<id>/addresses class Persons(ModelViewSet): @detail_route def addresses(self): some_code Though I am struggling with finding a way how to reverse this url: reverse('order-detail', args=[1, 'addresses']) is not working -
How to find complete sentence in string in Python?
Can anyone please help me to find the complete sentence from string in Python? For example I have this type of paragraph. CIBC World Markets Inc. cut its stake in shares of Rite Aid Corp. (NYSE:RAD) by 44.5% during the second quarter, according to its most recent filing with the Securities and Exchange Commission (SEC). The fund owned 126,617 shares of the company’s stock after selling 101,714 shares during the period. CIBC World Markets Inc.’s holdings in Rite Aid Corp. were worth $948,000 as of its most recent SEC filing. A number of other institutional investors have also modified their holdings of the stock. Pioneer Investment Management Inc. acquired a new position in shares of Rite Aid Corp. during the fourth quarter valued at about $7,230,000. Nomura Asset Management Co. Ltd. raised its position in shares of Rite Aid Corp. by 4.0% in the fourth quarter. Nomura Asset Management Co. Ltd. now owns 130,700 shares of the company’s stock valued at $1,024,000 after buying an additional 5,000 shares during the period. Norges Bank acquired a new position in shares of Rite Aid Corp. during the fourth quarter valued at about And the script I need is to find fist three … -
Display value in a button by linking two modals
I have two modals each of it having different content. My first modal has a button which opens the second one. The second modal has Key Id's which should be displayed in the button of the first modal upon selection. I'm able to display the value in my second modal by just using label(Used this just to check if my selected is working). I'm not able to display the selected value in the button of my first modal. Any idea how it can be done? Here's the code which I used, In the template of the the first Modal, <button class="btn btn-default btn-lg" ng-click="Modal()" ng-model="cp.se"></button> Function to Open Modal and link to Controller, $scope.Modal = function() { // function to open modal and link to Modal Controller var modalInstance = $modal.open({ backdrop: 'static', templateUrl: '{% url 'critical_process' %}', controller: 'Controller', }); modalInstance.result.then(function (msg) { $log.info('Modal success'); //console.log(msg); }); }; // End:function to open modal and link to Modal Controller In the controller, {{ngapp}}.controller( "Controller", function($scope, $http, $modalInstance){ $scope.selected=[]; $scope.items=[ { value:'Impact to Safety, regulatory compliance, or /n environment', key:10, color:'red'}, { value:'Reliability Impact',key:9, color:'brown'}]; }); In the template of the second modal, <div class="well form-group" > <table class="table"> <tr ng-repeat="item … -
Django OneToMany adding to set throws index out of range
I have a flight model which consists of legs and pricingoption via foreign key. In my view I can parse a leg with leg = self.parse_leg(itinerary["OutboundLegId"], json) which gives me a leg object. But when I do flight = Flight() flight.leg_set.add(self.parse_leg(itinerary["OutboundLegId"], json)) I get a list index out of range. Why? This is my flight model: class Flight(models.Model): creation_date = models.DateTimeField(default=timezone.now) # Pricing Option, Outbound/Inbound leg via ForeignKey Here goes a leg class Leg(models.Model): ... flight = models.ForeignKey("flight.Flight", null=True) and a PricingOption class PricingOption(models.Model): ... flight = models.ForeignKey("flight.Flight", null=True) -
django celery unit tests with pycharm 'No module named celery'
my tests work fine when my target is a single function (see 'Target' field in the image): questionator.test_mturk_views.TestReport.submit However, when I specify my target to include all tests within my questionator app: questionator I get this error: Error ImportError: Failed to import test module: src.questionator.test_mturk_views Traceback (most recent call last): File "C:\Python27\Lib\unittest\loader.py", line 254, in _find_tests module = self._get_module_from_name(name) File "C:\Python27\Lib\unittest\loader.py", line 232, in _get_module_from_name import(name) File "C:\Users\Andy\questionator_app\src__init__.py", line 5, in from .celery import app as celery_app # noqa ImportError: No module named celery Note that my tests include my settings via 'Environment variables' (see this in the pic too): DJANGO_SETTINGS_MODULE=questionator_app.settings.development;PYTHONUNBUFFERED=1 The celery documentation mentions a "Using a custom test runner to test with celery" but this is in the now defunct djcelery package. I did though copy/paste/tweak this mentioned test runner and used it as described, but I get the same error. Unfortunately using CELERY_ALWAYS_EAGER also does not work http://docs.celeryproject.org/en/latest/configuration.html#celery-always-eager I would appreciate some guidance. With best wishes, Andy. -
Django haystack is returning fewer results
A pair of eyes will be much appreciated. Here is my Elasticsearch console (Kibana/Sense) output that returns 31 hits for this query However the same query in Django Haystack is returning just 12 hits. Am I using the right query? Request: GET haystack/_search { "query": { "match": { "text": "safety issues" } } } Response: { "timed_out": false, "_shards": { "total": 5, "successful": 5, "failed": 0 }, "hits": { "total": 31, Now in my python console In [34]: from haystack.query import SearchQuerySet ...: from haystack.inputs import AutoQuery ...: len(SearchQuerySet().filter(content=AutoQuery('safety issues'))) ...: Out[34]: 12 Thoughts? -
Django + Apache - Can't find directory of my website
I have done a website by using django framework. Now I'm trying to deploy using apache+wsgi. Here is my setting. So I have a ip 59.120.185.12 and here is my .config: <VirtualHost *:80> ServerName www.vbgetech.com ServerAlias vbgetech.com ServerAdmin webmaster@localhost Alias /media/ /home/max/v_bridge/media/ Alias /static/ /home/max/v_bridge/static/ <Directory /home/max/v_bridge/media> Require all granted </Directory> <Directory /home/max/v_bridge/static> Require all granted </Directory> WSGIScriptAlias / /home/max/v_bridge/v_bridge/wsgi.py <Directory /home/max/v_bridge/v_bridge/> <Files wsgi.py> Require all granted </Files> </Directory> </VirtualHost> And its my wsgi.py """ WSGI config for website project. It exposes the WSGI callable as a module-level variable named ``application``. For more information on this file, see https://docs.djangoproject.com/en/1.8/howto/deployment/wsgi/ """ import os from django.core.wsgi import get_wsgi_application from os.path import join,dirname,abspath PROJECT_DIR = dirname(dirname(abspath(__file__)))#3 import sys # 4 sys.path.insert(0,PROJECT_DIR) # 5 os.environ.setdefault("DJANGO_SETTINGS_MODULE", "v_bridge.settings") from django.core.wsgi import get_wsgi_application application = get_wsgi_application() I think I do follow all the instruction by official document. And It seems that If I type the ip on browser it still return me a apache default page. I guess that is because my server can't map the ip to the .conf file. Anyone has idea about it? -
inside {% %} is it work {{ }} in jina?
i want to check condition in jinja like this {% if {{ choosediffuser }} == 'Disc Diffusers (models AFD270/AFD350)' | {{ choosediffuser }} == 'AFD270' | {{ choosediffuser }} == 'AFD350'%} is it workable code? this condition is coming from data base I am rendering in to my html page. The "choosediffuser" is already in my DOM. How can I use here jinja or something other. -
How do i edit django-machina forum template and styling
I am using django-machina for forum in my app. I want to change the template and also style on my own. I did that by copying all the templates of its to my template directory and copied style(machina.board_theme.min.css) to my static folder. Is this a best way if i want to edit the style and template? Also if i want to upload image for my profile, the profile gets updated but image is not shown({{ profile.avatar.url }}). Configuration 'DIRS': [os.path.join(BASE_DIR, 'templates'),MACHINA_MAIN_TEMPLATE_DIR,] STATIC_ROOT = os.path.join(BASE_DIR,"staticcollection") STATICFILES_DIRS = (os.path.join(BASE_DIR,"static"),MACHINA_MAIN_STATIC_DIR, ) my template structure Please advise me the best way to override my template styling. I could not understand from the documentation part. -
How to get all users of a group in Django?
I want to get a list of all users who are within a Django Group. For example: User.objects.filter(group='Staff') I cannot find how to do this query anywhere in the docs. -
How to connect to AWS active directory using python/django?
After web search, I found multiple solutions such as use of python-ldap, django-ldap, use of aws-adfs, and lot more. Kindly suggest me a solution that works, Im new to this AWS connection and all, so any help regarding this is appreciated -
Django Tastypie calling multiple resources
I have 3 resources. User, Profile and Settings. Profile and Settings have a FK to User. I have to implement a search that combines all 3 resources. I have applied filters to all 3 resources and can search using tastypie filters. I have also overwritten the alter_list_data_to_serialize and ask it to return only ID's def alter_list_data_to_serialize(self, request, data): if request.GET.get('id_only'): obj={} list=[] for x in data['objects']: list.append(get_pk_from_uri(x.data['user'])) obj['user_ids']=list return obj return data eg: http://127.0.0.1:8000/settings/?visible=True&id_only=true, ( get the ID's) then run http://127.0.0.1:8000/profile/?State=Alaska&User__id__in=[ID LIST FROM REQueST 1] Is there a easier and better way to do this using just one request instead of two. Such as creating a another Resource and getting it to call the other resources ? -
Use bootstrap modal in django class based views, (create, update, search, etc)
Bootstrap modal implementation on standalone page is quite easy, and can be triggered using a button or tag, but lets assume that I have the below classes class CustomerMixin(object) class CustomerFormMixin(CustomerMixin, CreateView) CustomerListView(CustomerMixin, ListView) CustomerCreateView(CustomerMixin, CreateView) CustomerUpdateView(CustomerFormMixin, UpdateView) URL: urlpatterns = [ url(r'^$', CustomerListView.as_view(), name='index'), url(r'^create$', CustomerCreateView.as_view(), name='create'), url(r'^detail/(?P<pk>[0-9]+)$', CustomerDetailView.as_view(), name='detail'), url(r'^delete/(?P<pk>[0-9]+)$', CustomerDeleteView.as_view(), name='delete'), url(r'edit/(?P<pk>[0-9]+)$', CustomerUpdateView.as_view(), name='edit'), ] In the index page I have 3 link each referring to its own Class <a href="{% url 'myapp:create' %}">Create</a> and in the list on Index page for each row in the table I have 2 link for Edit and Delete for that row. So now I want to have bootstrap modal for both Create and Update once user clicks on Create a tag on the Index page so I can trigger modal and at the same time trigger Create class. I have checked the below blogs but no luck: https://libraries.io/pypi/django-fm (This one looks good, but I couldn't implement it) https://dmorgan.info/posts/django-views-bootstrap-modals/ -
Referencing a object of a model with all foreign keys in Django admin UI
I am developing my Djnago app for processing data into DB from admin frontend. I have a table with both foreign keys in it. class exam_questions(models.Model): exam_id=models.ForeignKey(exams,on_delete=models.CASCADE) question_id=models.ForeignKey(questions,on_delete=models.CASCADE) def __int__(self): return self.exam_id When I am trying to return the above field it is shown in admin UI as exam_questions object for all values added into table. Is there a way to get the actual value of the column displayed on admin UI. I have other tables which have have different definitions and I am able to display the required field from that. The issue is observed only when all keys in model are foreign keys Any help is appreciated. -
Swagger Integration in Django
I need to integrate Swagger in Django. So, can anyone discuss the steps to integrate Swagger in Django. I need the full description. Thanks in advance. -
I'm trying to learn Django from django documentation and thenewboston video tutorials
My background is okayish in c++(can do file handling and file operations, and data structures) I know python upto classes and functions, but no file handling these are the two languages I know, nothing else So, I wanted to learn something new and found Django. But even with the official documentation and video tutorials, most syntaxes dont make any sense. why something is written in a specific file and all that kind of thing. I can follow the codes, and maybe write my own by continously looking into the vids or documentation, but cant do it completely myself, as I dont know the meaning of half the stuff is my method of learning django ok? or shud I try learning something else first like java or javascript? -
Using django user authentication from another app on server
I'm trying to reuse my django authentication system to authorize another app running on another docker container on the same server. def get_username_auth(request): # Return the username if authenticated, None if not. if request.user.is_authenticated(): print('Checked authorization for user: request.user.get_username()') return HttpResponse(request.user.get_username()) else: print('Returned user not authorized') return HttpResponse('NOT_AUTHORIZED') Since the request is coming internally (via another docker container), I don't think the cookies are read by django and the user is not authorized. Is there any elegant way to do this? -
Django mock unit test form filefield
I have a form that I want to unittest: app/form.py class MyForm(forms.Form): file = forms.FileField() app/test.py class MyFormTest(TestCase): def test_my_form(self): file_mock = MagicMock(spec=File) form = MyForm({'file':file_mock}) self.assertTrue(form.is_valid()) How can i unit test this form using mock or other was? If possible i would like to test this form using mock. How can i patch and mock test it?enter code here -
Wanted to create a custom button using custom stripe integration
So this is from Stripe itself: <script src="https://checkout.stripe.com/checkout.js"></script> <button id="customButton">Purchase</button> <script> var handler = StripeCheckout.configure({ key: 'pk_test_****', image: 'https://stripe.com/img/documentation/checkout/marketplace.png', locale: 'auto', token: function(token) { // You can access the token ID with `token.id`. // Get the token ID to your server-side code for use. } }); document.getElementById('customButton').addEventListener('click', function(e) { // Open Checkout with further options: handler.open({ name: 'Company', description: '2 widgets', zipCode: true, amount: 2000 }); e.preventDefault(); }); // Close Checkout on page navigation: window.addEventListener('popstate', function() { handler.close(); }); </script> Question is what goes in here from above: token: function(token) { // You can access the token ID with `token.id`. // Get the token ID to your server-side code for use. } I read that Ajax helps and I tried this piece in there: $.ajax({ url: '/path/to/file', type: 'POST', data: {token: token.id}, success: function(s) { // Do something on success }, error: function(e){ // Do something with the error } }); But that didn't work. What am I supposed to put in the url:? I am trying to get the stripe token to be sent to the server then to charge the card. -
Django unittest : 'or' assertEqual test possible?
What I want to do is, a = 1 b= [1,2,3,4] c="hi" d=["hi", "bye"] self.assertIn(a, b) or self.assertIn(c, d) # pass either one pass test. Is it possible in Django? -
why Django deployed on Heroku is not serving static files?
I've just deployed a project and I've noticed that no CSS/PNG files are served, here's my setting files STATIC_URL = '/static/' STATICFILES_DIRS = (os.path.join(BASE_DIR, ''),os.path.join(BASE_DIR, 'WebInterface/'),os.path.join(BASE_DIR, 'WebInterface/static'),os.path.join(BASE_DIR, 'WebInterface/static/WebInterface/'),) STATIC_ROOT = os.path.join(BASE_DIR, 'staticcollector') As you can see my stylesheets and images are under path-in-heroku-to-app/WebInterface/static/WebInterface/x.y Where x is file name and y is the extension.