Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
django: submit POST to create objects not working
So I am trying to do something like this: the user checks the checkbox to select which pieces of sample he or she would like to create logout record for, and then click the logout button. Then it jumps to another page with Bootstrap Modal showing the logout form like the following: My problem is, after filling out the forms and click SAVE, there is just nothing happening. I will post my relevant code here with some explanation about what I tried. Logout model: class Logout(models.Model): sample = models.ForeignKey(SampleDetail, on_delete = models.CASCADE, null=True) in_or_out = models.CharField(max_length = 200, choices = INOUT_CHOCIES, null=True, blank = True) logout_date = models.DateField(verbose_name = 'log date', null=True, blank = True) logout_by = models.CharField(max_length = 200, verbose_name = 'log by', null=True, blank = True) out_shipping_method_tracking_number = models.CharField(max_length = 200, null=True, blank = True, verbose_name = 'shipping method and tracking number') out_notes= models.CharField(max_length = 200, verbose_name = 'notes', null=True, blank = True) Logout Form: class LogOutForm(ModelForm): logout_date=forms.DateField(widget=DateWidget(attrs={'id':"logout_date"}, usel10n = True, bootstrap_version=3), initial=datetime.date.today, label="Log Date") out_notes = forms.CharField(widget=forms.Textarea) class Meta: model = Logout fields = ['in_or_out', 'logout_date','logout_by', 'out_shipping_method_tracking_number','out_notes'] update_sample_logout View.py: def update_sample_logout (request, project_id): if 'loglist' in request.GET: sample_detail_list = request.GET.getlist('loglist') samples = SampleDetail.objects.filter(id__in = sample_detail_list) else: messages.error(request, … -
Pycharm shows error on blocktrans templatetag
{% blocktrans trimmed %} is showing error: Invalid subtag for blocktrans is found. 'with', 'count' or 'and' expected. How Pycharm knows about templatetag's parameters? How can I fix this error? I use old 2.7.3 version. -
Script not working outside html body tag
I have a base template that works fine with the format that I am posting here. However, I want to keep the scripts inside one block, but when I am moving one of the scripts from the body to head, the menu does not drop when clicking. How can I fix this? html: {% load staticfiles %} <!DOCTYPE html> <html lang="en" class="no-js"> <head> {% block meta_tags %}{% endblock meta_tags%} <title> {% block title %}BPM App{% endblock title %} </title> {% block stylesheets %} <link type="text/javascript" href="{% static 'bpmapp/js/topnavbar.js' %}"> <link rel="shortcut icon" type="image/png" href="{{STATIC_URL}}/favicon.ico"/> {% endblock %} {% block javascript %} <script src="https://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script> <script> $(function() { cbpHorizontalMenu.init(); }); </script> {% endblock javascript %} {% block extra_head %}{% endblock %} </head> <body> {% include 'bpmapp/_topnavbar.html' %} {% block content %} {% endblock content %} <script src="static/bpmapp/js/cbpHorizontalMenu.min.js"></script> </body> </html> cbpHorizontalMenu.min.js: var cbpHorizontalMenu = (function() { var b = $("#cbp-hrmenu > ul > li"), g = b.children("a"), c = $("body"), d = -1; function f() { g.on("click", a); b.on("click", function(h) { h.stopPropagation() }) } function a(j) { if (d !== -1) { b.eq(d).removeClass("cbp-hropen") } var i = $(j.currentTarget).parent("li"), h = i.index(); if (d === h) { i.removeClass("cbp-hropen"); d = -1 } else { … -
Trouble Migrating database schema to Heroku (Postgres)
I have everything set up in my local environment and the code for my website up on the Heroku server, I'm just having serious trouble getting the schema to migrate to the postgres database on the Heroku server. Whenever I attempt heroku run python manage.py migrate I get the following (this would be an inital migration): Running python manage.py migrate on baseballstatview... up, run.1653 (Free) Operations to perform: Apply all migrations: admin, auth, contenttypes, sessions, statview Running migrations: Applying contenttypes.0001_initial... OK Applying auth.0001_initial... OK Applying admin.0001_initial... OK Applying admin.0002_logentry_remove_auto_add... OK Applying contenttypes.0002_remove_content_type_name... OK Applying auth.0002_alter_permission_name_max_length... OK Applying auth.0003_alter_user_email_max_length... OK Applying auth.0004_alter_user_username_opts... OK Applying auth.0005_alter_user_last_login_null... OK Applying auth.0006_require_contenttypes_0002... OK Applying auth.0007_alter_validators_add_error_messages... OK Applying auth.0008_alter_user_username_max_length... OK Applying sessions.0001_initial... OK Applying statview.0001_initial... OK Which seems fine but then using heroku pg:info it tells me I have 0 tables, and even further when I run heroku run python manage.py showmigrations this is what I get: Running python manage.py showmigrations on baseballstatview... up, run.5059 (Free) admin [ ] 0001_initial [ ] 0002_logentry_remove_auto_add auth [ ] 0001_initial [ ] 0002_alter_permission_name_max_length [ ] 0003_alter_user_email_max_length [ ] 0004_alter_user_username_opts [ ] 0005_alter_user_last_login_null [ ] 0006_require_contenttypes_0002 [ ] 0007_alter_validators_add_error_messages [ ] 0008_alter_user_username_max_length contenttypes [ ] 0001_initial [ ] 0002_remove_content_type_name sessions … -
How to make action logging in Django with Django Rest Framework
Good day everyone! I need to make logging of the actions in Django 1.10.4 with Django Rest Framework and save them in a file. I have different serializers and functions in them. I've read documentation and not quite understood what I have to do in order to log actions such as CREATE, UPDATE or DELETE with data that I'm sending For example I have: class MySerializer(serializers.HyperlinkedModelSerializer): def create(self, validated_data): ...some code... return object def update(self, instance, validated_data): ...some code... return instance How can I do this and do you have some references to similar tasks? -
Script for merging dev mysql database to deployment mysql database for Django app
I am working on a Django app and have now reached the point of setting up my deployment process. I would like to automate this as much as possible and as such am looking for any help I can get in terms of database management. As I see it, this is the rough outline of the process I would like to automate: 1. back up the current database on the live server 2. merge the structure of the dev and deploy databases so as to keep only the data in the deployment db but update the structure to match the dev db I have considered simply applying all of the new migrations from dev to the live db however I fear that this will result in a series of errors due to default values and such. Any insights into where I could look to get started would be greatly appreciated! -
Using Django Server Sent Events with Database post save
I am trying to implement Server Sent Events(SSE) in Django Framework. It is clear to me that I can implement a view like this: @csrf_exempt def event_stream(request): def eventStream(): yield "data:Server Sent Data\n\n" response = HttpResponse(eventStream(), content_type="text/event-stream") response['Cache-Control'] = 'no-cache' return response But I want to trigger the SSE call whenever a new entry is made in a database table, from the post_save of the table, How I might be able to achieve that here since eventStream here is a generator function. -
Django multiwidget and validation issue
I have been subclassing multiwidget to create an HTML5 range slider synchronised with a NumberInput field using this code: class SplitRangeNumberWidget(MultiWidget): def __init__(self): widgets = ( forms.NumberInput(attrs={'type':'range', 'onchange':'this.nextElementSibling.value=this.value', 'oninput':'this.nextElementSibling.value=this.value', 'step':'any', 'min':0, 'max':1}), forms.NumberInput(attrs={'step':'any', 'onchange':'this.previousElementSibling.value=this.value', 'oninput':'this.previousElementSibling.value=this.value',}) ) super(SplitRangeNumberWidget, self).__init__(widgets) def decompress(self, value): if value: return [value, value] return [None, None] When I instanciate it and use it in a Form such as: class ParameterForm(forms.ModelForm): class Meta: model = Parameter fields = ['name','value','min_value','max_value'] widgets = {'value':SplitRangeNumberWidget()} , the widget works fine: changing the slider or the numberinput does change the other field. However, when doing a POST, the form does not validate and I get this error in form.errors (for 3 parameters): [{'value': ['Enter a number.']}, {'value': ['Enter a number.']}, {'value': ['Enter a number.']}] The widgets alone do work well and form is correctly bound. But not in a multiwidget. What am I doing wrong? I added def value_from_datadict(self, data, files, name): num = [widget.value_from_datadict(data, files, name + '_%s' % i) for i, widget in enumerate(self.widgets)] return [float(num[0]), float(num[1])] but this still does not work. Thanks for your help. -
invalid syntax on context
I am making an application using django, I am trying to retrieve data from my database, but I keep getting an error saying that there is a syntax error with my context. views.py from django.shortcuts import render from .models import Tweet def tweet_detail_view(request, id=1): obj = Tweet.objects.get(id=id) print(obj) context { "object": obj } return render(request, "tweets/detail_view.html", context) model.py from __future__ import unicode_literals from django.conf import settings from django.db import models # Create your models here. class Tweet(models.Model): content = models.CharField(max_length=140) updated = models.DateTimeField(auto_now=True) timestap = models.DateTimeField(auto_now_add=True) user = models.ForeignKey(settings.AUTH_USER_MODEL) def __str__(self): return str(self.content) -
Disable Cached JSON response on frequent browser calls to django view
In my django app, I use views to call the django method I want to test under development. When I call my view visiting the mapped url localhost:8000/do_something, twice, it'll return me the cached JSON response and won't process the requests again which destroys my usage of testing the code. I'm aware that it's definitely not the best practice, but I'd just like to work with it, so following are the things I tried: Clearing the browser cache(In chrome, IE and firefox, all three) Restarting the server It ultimately goes clears about 2-3 restarts, and the view makes the method calls again instead of just returning the cached JSON response I'm sure it's a preference or some setting, would be glad if someone could resolve me with this issue? Thanks. -
Multiplie Django Apache servers
I currently have one server which on it Apache-django app is running with postgresDB. 1.I would like to add another server with Apache-django app that is connected to the same postgresDB. I would like both of that apps to be synchronized and running. 2.Both of the apps would run , but only one will be requested, active passive state, should I use a proxy server for this ? How should do this ? -
Django DRF - Include Foreign-Key field to serializer
How do I add 'platform_description' field to be part of battlesSerializer result? Model class battles(models.Model): # Fields created = models.DateTimeField(auto_now_add=True, editable=False) last_updated = models.DateTimeField(auto_now=True, editable=False) wager = models.FloatField(max_length=30) battle_rules = models.CharField(max_length=30,null = True,blank = True) accepting_time = models.DateTimeField() offer_expiration_time = models.DateTimeField(null = True,blank = True) battle_time = models.DateTimeField(null = True,blank = True) rake = models.FloatField() # Relationship Fields platform_id = models.ForeignKey('platforms.game_platforms', related_name='seal') class Meta: ordering = ('-created',) def __unicode__(self): return u'%s' % self.id def get_absolute_url(self): return reverse('platforms_battles_detail', args=(self.id,)) def get_update_url(self): return reverse('platforms_battles_update', args=(self.id,)) class game_platforms(models.Model): # Fields created = models.DateTimeField(auto_now_add=True, editable=False) last_updated = models.DateTimeField(auto_now=True, editable=False) platform_description = models.CharField(max_length=30) class Meta: ordering = ('-created',) def __unicode__(self): return u'%s' % self.id def __str__(self): return '%s' % self.platform_description def get_absolute_url(self): return reverse('platforms_game_platforms_detail', args=(self.id,)) def get_update_url(self): return reverse('platforms_game_platforms_update', args=(self.id,)) Serializer class battlesSerializer(serializers.ModelSerializer): class Meta: model = models.battles fields = ( 'id', 'created', 'last_updated', 'wager', 'battle_rules', 'accepting_time', 'offer_expiration_time', 'battle_time', 'rake', ) class game_platformsSerializer(serializers.ModelSerializer): class Meta: model = models.game_platforms fields = ( 'id', 'created', 'last_updated', 'platform_description', ) -
Don't want to run if statement forever
I am writing an app in Django. There is one requirement that 1st 10 users will get off on their 1st purchase. And the money deduction is written in cron.So no user input. What can i do here is that maintain column in db like used(boolean) and check if used or not. But at some point of time lets say 1 month and assuming that all 1st 10 users have purchased something the code still going to check every time this condition. Assuming that my app gonna run like forever, I was thinking that is there a way to implement this so that i don't have to write if. e.g models.py class User(something): .... user = something.Boolean() tasks.py def x(): users = User....all() for user in users: if user in 1st 10 and not user.used: charge(100) else: charge(150) After some time every user in 1st 10 has used its promo. So i want to remove that ugly if statement so my func x is: def x(): users = User....all() for user in users: charge(150) -
Can't create an instance from shell for a class that has a foreignKey
So I was trying to populate my db from Django's shell (just testing). However when I try to create an instance from a class that has a ForeignKey nothing seems to work. #models.py class Pizza(models.Model): """Bleh""" name = models.CharField(max_length=20) def __str__(self): """Devolve a representacao em string do model""" return self.name class Topping(models.Model): """Ingredients""" pizza = models.ForeignKey(Pizza) name = models.CharField(max_length=20) def __str__(self): """String rep""" return self.name #shell commands >>> from shop_app.models import Topping, Pizza >>> p = Pizza(name='Hawaiian') >>> p.save() >>> t = Topping(pizza='?',name='Pineapple') question mark stands for "no idea what should I put there". I've tried many things, including 'Hawaiian', but none of them worked. From the admin page it works correctly though. However that's not what I'm looking for -
'ReturnDict' object has no attribute 'encode' Django Rest Framework
Hi i am newbie on Django, I am try to render responses in plain text, Here is my serializer.py from django.contrib.auth import get_user_model from rest_framework import serializers User = get_user_model() class UserSerializer(serializers.ModelSerializer): class Meta: model = User fields = ( 'id', 'first_name', 'last_name', 'email', 'last_login', 'is_active', 'date_joined', 'last_updated' ) views.py from rest_framework import viewsets from django.contrib.auth import get_user_model from .serializers import UserSerializer User = get_user_model() class UserViewSet(viewsets.ModelViewSet): serializer_class = UserSerializer queryset = User.objects.all() search_fields = ('first_name', 'last_name', 'email') filter_fields = ('id', 'first_name', 'last_name', 'email') To do that im looking to this document http://www.django-rest-framework.org/api-guide/renderers/#custom-renderers Here is my renderers.py from django.utils.encoding import smart_unicode from rest_framework import renderers class PlainTextRenderer(renderers.BaseRenderer): media_type = 'text/plain' format = 'txt' def render(self, data, media_type=None, renderer_context=None): return data.encode(self.charset) So then i am getting this error massage : 'ReturnDict' object has no attribute 'encode' Why im getting this error message? What i am missing? If i don't use encode method then getting response but that has no attribute values. Just attribute names, idfirst_namelast_nameemaillast_loginis_activedate_joinedlast_updated here is the full trace: Environment: Request Method: GET Request URL: http://localhost:8000/api/users/2/?format=txt Django Version: 1.9.4 Python Version: 2.7.12 Installed Applications: ['django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'django_extensions', 'rest_framework', 'users', 'autofixture'] Installed Middleware: ['django.middleware.security.SecurityMiddleware', 'django.contrib.sessions.middleware.SessionMiddleware', 'django.middleware.common.CommonMiddleware', 'django.middleware.csrf.CsrfViewMiddleware', … -
python social app Facbook Authentication process canceled
I am using Django 1.8 and python social app, when I try to log in to facebook I get Authentication process canceled error, any ideas how to fix it? I tried almost everything, and raising exception does not help either :(( Settings.py INSTALLED_APPS = ( 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'social.apps.django_app.default', 'bookstore', 'store', 'registration', 'social_django' ) MIDDLEWARE_CLASSES = ( 'django.contrib.sessions.middleware.SessionMiddleware', 'django.middleware.common.CommonMiddleware', 'django.middleware.csrf.CsrfViewMiddleware', 'django.contrib.auth.middleware.AuthenticationMiddleware', 'django.contrib.auth.middleware.SessionAuthenticationMiddleware', 'django.contrib.messages.middleware.MessageMiddleware', 'django.middleware.clickjacking.XFrameOptionsMiddleware', 'django.middleware.security.SecurityMiddleware', 'social.apps.django_app.middleware.SocialAuthExceptionMiddleware' ) SESSION_SERIALIZER = 'django.contrib.sessions.serializers.PickleSerializer' ROOT_URLCONF = 'bookstore.urls' TEMPLATES = [ { 'BACKEND': 'django.template.backends.django.DjangoTemplates', 'DIRS': [os.path.join(BASE_DIR, 'templates')], 'APP_DIRS': True, 'OPTIONS': { 'context_processors': [ 'django.template.context_processors.debug', 'django.template.context_processors.request', 'django.contrib.auth.context_processors.auth', 'django.contrib.messages.context_processors.messages', 'social.apps.django_app.context_processors.backends', 'social.apps.django_app.context_processors.login_redirect', ], }, }, ] AUTHENTICATION_BACKENDS = ( 'social.backends.facebook.FacebookOAuth2', 'django.contrib.auth.backends.ModelBackend', ) WSGI_APPLICATION = 'bookstore.wsgi.application' # Database # https://docs.djangoproject.com/en/1.8/ref/settings/#databases DATABASES = { 'default': { 'ENGINE': 'django.db.backends.sqlite3', 'NAME': os.path.join(BASE_DIR, 'db.sqlite3'), } } SOCIAL_AUTH_FACEBOOK_KEY ='396755860661415' SOCIAL_AUTH_FACEBOO_SECRET = 'fdf43393be87095f67f996a3918742d5' LOGIN_REDIRECT_URL = '/' -
django get all childs with given parent_id
I have to populate a select field based on another select field's selection. The first select is the school and the second select should be the classes in that school. I use an ajax call and in my view I have following code but without results: def get_classes_by_school_id(request): school_id = request.POST.get('school_id', None) data = { 'listClasses': Classes.objects.filter(school=school_id).values('id', 'title', 'abbr') } return JsonResponse({'data': list(data)}) console.log($.parseJSON(data)); returns {data: ["listClasses"]} data:["listClasses"] 0:"listClasses" -
Django login "?next=" only saving one GET parameter
I'm using Django 1.10 and Python Social Auth 0.1.0. I use Django login view, having only added the template with: <a href="{% url 'social:begin' 'azuread-oauth2' %}{% if request.GET.next %}?next={{ request.GET.next }}{% endif %}" class="btn btn-primary btn-lg"><i class="fa fa-windows" aria-hidden="true"></i> {% trans 'Login' %}</a> This works fine if my ?next= is something like: app/something/ app/something/?info=blue But it doesn't work for: app/something/?info=blue&moreinfo=red What happens is that the redirect is done to: app/something/?info=blue. Is there any reason for the redirect to fail for more than one GET parameter? I've tested several times (different apps, and also with Django 1.9 and this happens always). This is a big problem because I'm building an APIusing Django Rest Framework and Django OAuth Toolkit. Having an API that may use another to log in (two oauth2 in a row) requires several parameters (?client=fasa&....) to be saved in the next variable. -
Cannot query "user": Must be "Model" instance
I'm trying to filter users on my private user to user chat, I'm getting the buyer's username with a model (User) and the seller's username with another model (Profile). The problem is that I don't understand how I can resolve this issue and why it occurs : ValueError: Cannot query "user_39": Must be "Profile" instance. On my view : uc = userComment.objects.all().first() users = userComment.objects.filter(Q(buyer=uc.buyer) | Q(seller=uc.buyer)) #error occurs with this line pdb.set_trace() (Pdb) uc.seller <Profile: user_39> (Pdb) uc.buyer <User: user_4> Here are my two models. class Profile(models.Model): name = models.CharField(max_length=120) user = models.OneToOneField(User, null=True, blank=True) class userComment(models.Model): buyer = models.ForeignKey(User, related_name="buyer", null=True) seller = models.ForeignKey(Profile, related_name="seller", null=True) On my models I don't want to change userComment.seller to ForeignKey(User, ...) How can I resolve this issue ? -
Django Complete Tutorial for Making Simple Login Page
Learning Django after learning Laravel. Laravel was extremely easy to implement authentication and create a client login page for, almost to a point where you don't really learn how its authentication works because it just does it all for you. Anyway, I have been struggling with this for several nights now and looking for a tutorial that discusses all the requirements for implementing a login and also redirecting from other pages if the user is not authenticated. I have gone through these tutorials: How to Use Django's Built-in Login System Right way of adding user authentication to Django The first one doesn't provide all the info one would need to make a complete login application. The second one doesn't work as it should--it just keeps going to the login page and never goes to the dashboard. Also a few coding mistakes it looks like: urlpatterns = [ url(r'^admin/', include(admin.site.urls)), url(r'', include('log.urls')), url(r'^login/$', views.login, {'template_name': 'login.html'}, ] And: <form method="post" action="{% url 'django.contrib.auth.views.login' %}"> Which seems like it should just be: <form method="post" action="{% url 'login' %}"> The official documentation just is a bit much to consume as I am looking for just a basic: you need this x, y, and … -
Django rest update (and partial_update) after retrieve action
I don't understand one thing into DRF(or DRFMongoengine). class SomeViewSet(MongoModelViewSet): def get_serializer_class(self): print "ACTION:", self.action return SomeSerializer After calling url for this viewset from cURL(or with get-parameters format=json), I observe: ACTION: retrieve [09/Jan/2017 17:19:08] "GET /api/some/?format=json HTTP/1.1" 200 After calling with format=api (eg from browser), I observe: ACTION: retrieve ACTION: update ACTION: partial_update ACTION: update [09/Jan/2017 17:21:50] "GET /api/some/?format=api HTTP/1.1" 200 73173 Why is that happening? Will be very thankful for any help. -
How to avoid making multiple trips to database in this Django function?
Currently this code seems to be going to the database (Postgres) two to four times on every loop iteration. First to get (and create) the Type, then to get (and create) the Component. Is there a way to do this in fewer database trips that would be an improvement over the current code? models.py: class Component(models.Model): long = models.TextField() type = models.SmallForeignKey('Type', models.CASCADE) class Type(models.Model): type = models.TextField(unique=True) class Point(models.Model): components = models.ArrayField(models.IntegerField(), default=[]) Incoming data: geocode = [ { "long_name" : "Luray", "types" : [ "locality", "political" ] }, { "long_name" : "Page County", "types" : [ "administrative_area_level_2", "political" ] }, { "long_name" : "Virginia", "types" : [ "administrative_area_level_1", "political" ] }, { "long_name" : "United States", "types" : [ "country", "political" ] } ] Function: _components = [] for c in geocode: ct = Type.objects.get_or_create(type=c['types'][0]) _components.append(Component.objects.get_or_create(long=c['long_name'], type=ct).pk) self.components = _components -
django variable incremt in views
Sorry if this is like a dumb question but im new to django and cant figure out whats wrong. So I want to display one row of a database after another, which should change after pressing a Button. The purpose is to translate vocabulary and check if its right. This is my view: counter = 3 def learn(request): obj = Vokabel.objects.filter(pk=counter) if request.method == "POST": form=addE(request.POST) if form.is_valid(): temp1 = request.POST.get('elearn') for i in obj: if temp1 == i.eVok: counter = counter + 1 return HttpResponseRedirect('/learnnext/') else: return HttpResponseRedirect('/learn/') else: form = addE() return render(request, 'learn.html', {'form' : form, 'obj' : obj}) And my forms: class addV(ModelForm): class Meta: model = Vokabel fields= ['eVok', 'dVok'] class addE(forms.Form): elearn = forms.CharField(label='Uebersetzung', max_length= 100,widget=forms.TextInput(attrs={'autocomplete':'off'})) However this returns me this error: local variable 'counter' referenced before assignment -
Which Java APIs or frameworks to use for suggesting workarounds to end users?
I am currently in need of writing an API, that will help to resolve well know issues that some of our end users might faces while using our mobile app. Let's say for example users have to login in our app, and for some reasons some users are having difficulties to login, and we have figured out a workaround that can fix the issue in most scenarios but we're waiting for a planned release date within a week. In that situation, users might be required to call our Call center and then our associates will be required to apply the workaround to see if the login issue get fixed. I want to automate this process, i feel like i could write a backend service that for example the UI will call if a specific kind of exception happens; and then the service will have to query the DataBase to see if we have a workaround for the issues. If yes the service should ask the END users required inputs like UserID... and then the API should take care of applying the work around so that the user could login. This approaches raises many questions: Is it secure? every day the … -
Developing a django project that uses a third party DBAL package
I am writing a django project, that makes extensive use of a python package I'm writing (let's call it foo, for convenience). The python package foo, will consist mainly of functions and classes that munge data obtained from a backend database. I want to write the package in such a way that it will have no dependency on django - and can be used in other projects outside of django. I am thinking of writing the package so that functions accept a database connection - and classes uses IoC for the database connection - that way, I can obtain a database connection from django and pass it to the DBAL package - when using it in django, and instantiate a DB connection via other means when using the package outside django. I have two questions: Is this an acceptable way of approaching this problem (i.e. no gotchas) Where/how do I obtain a database connection within django?