Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
django template "<" changed to '<'
in the views. I have a str str = "<div class='rprtnum nohighlight'>" I pass str to a template. When I load the template, it doesn't display correctly. I looked at the source of the html, it shows &lt;div class=&quot;rprtnum nohighlight&quot;&gt; How do I keep <, >, " in the str in the html page? I tried html.escape(str), it didn't work. Thanks! -
show specific columns for a given table given variable number of tables
i am using postgresql in django. i have to return specific column namesbased on given table name, and the tablenames are userdefined, i.e. user selects the number of tables he wishes to be displayed. I am currently using dictionary in django, torender request in GET part of the page which sends the dictionary, the code given as:(note this store column names and table names from filemaster and tablesmasters) fileMaster = FilesMaster.objects.all() tablesmasters = Tablesfromdb.objects.all() data = {} data['object_list'] = fileMaster data['table_list'] = tablesmasters is there a way to loop dictionary so that for each different table, i can use different dictionary on i or can someone give the exact example where using this same code, i can show different columns in the UI so that in the GET part of UI, i simply add some constraint such that for specific table name, i can get specific column name. My UI code is as: <select id="fileName1" class="form-control"> <option>Select</option> {% for fileset in object_list %} <option value="{{ fileset.FileId_id }}">{{ fileset.FileName_text}}</option> {% endfor %} </select> <select id="tables" class="tables"style="float:left;"> <option>Select</option> {% for fileset in table_list %} <option value="{{ fileset.TableID }}">{{ fileset.Tablename}}</option> {% endfor %} </select> -
how to use the csv file column headers as fields in a form?
In a form,the user has to upload a csv file and the column headers of the file are used as the fields of the form. Then for each column header a data type is to be selected by the user from a drop down list. I've tried using django but was unsuccessful.What is the best approach? -
How to use mysql's "find_in_set" on peewee?
This is django's raw sql servers.objects.raw("select a.id,a.Name,a.IP from servers a, info b where a.Name=b.Plat and find_in_set(a.Server,b.Range)>0") This is peewee's sql, has a error on this one servers.select().join(info, on=(servers.Name == info.Plat).alias('info')).where(servers.Server << info.Server) -
Django: access user information from a generic.view
I am trying to access to the current user information to filter the client's items but I am stuck with an error. I guess must be a different way to request the information of the current user. I am using this: self.kwargs.request.user AttributeError at 'dict' object has no attribute 'request' class CampaignUpdate(generic.UpdateView): model = Campaign fields = [.....] template_name = 'campaign/campaign.html' success_url = '../../' def get_context_data(self, *args, **kwargs): context = super(CampaignUpdate, self).get_context_data(**kwargs) items = items.objects.get(client= self.kwargs.request.user) -
How can I ensure a write has completed in PostgreSQL before releasing a lock?
I have a function on a Django model that calculates a value from a PostgreSQL 9.5 database and, based on the result, determines whether to add data in another row. The function must know the value before adding the row, and future values of the calculation will be dependent on the new row. To enforce these rules, I'm trying to use advisory locks. A simplified version of what I'm trying to do is below: from django.db import connection, models, transaction ... def create_usage(self, num_credits): LOCK_SQL = '''SELECT pg_advisory_lock(1) FROM {} WHERE id={}''' UNLOCK_SQL = '''SELECT pg_advisory_unlock(1) FROM {} WHERE id={}''' cursor = connection.cursor() try: # Create an advisory lock on the instance's row print('obtaining lock for object {}'.format(id(self)) cursor.execute(LOCK_SQL.format(self._meta.db_table, self.id)) print('obtained lock for object {}'.format(id(self)) # Perform some read and update when the lock is obtained with transaction.atomic(): # -- SELECT SUM(...) FROM table WHERE ... sum_credits = self.credits_used.aggregate( sum_credits=models.Sum('num_credits'))['sum_credits'] print('existing credits: {}'.format(sum_credits)) if sum_credits < 100 - num_credits: print('inserting') # -- INSERT INTO table VALUE (...) self.credits_used.add(CreditUsage(num_credits=num_credits)) else: print('not inserting') finally: # Release the lock when done, or when an exception occurs print('releasing lock for object {}'.format(id(self)) cursor.execute(UNLOCK_SQL.format(self._meta.db_table, self.id)) print('released lock for object {}'.format(id(self)) I have this code running … -
How to get and display checkbox values saved as Character field in Database
I have a Checkbox in html and I save the selected checkbox values as a character field in Database. Now I want to display the saved values of the checkbox field when certain operations were performed. I'm thinking of using cached property of django, but I'm not sure how to use it. Is there any other way to do it? Kindly help. I'm new here. Below is my code, HTML: <td><label>Main Concern</label> <li ng-repeat="item in main_concern"> <input type="checkbox" checklist-model="arform.main_concern" checklist-value="item.name" value="main_concern"/>{{item.name}} </li></td> Controller: $scope.main_concern = [{ name: 'Printability', value: false }, { name: 'Defectivity', value: false }, { name: 'Process Window', value: false }, { name: 'Parametric Shift', value: false }, { name: 'Yield Impact', value: false }, { name: 'Reliability', value: false }, { name: 'Other', value: false }]; $scope.arform['main_concern'] = []; angular.forEach($scope.arform['main_concern'], function(item){ if (item.selected) $scope.arform['main_concern'].push(item.name); }); I also have the below function in my controller to push the value(true or false) of the saved checkbox fields. This doesn't work. Rectify if there should be any changes to be made. main_concern = []; if ($scope.arform['main_concern']) { for (i=0; i<$scope.arform['main_concern']; i++) { angular.forEach($scope.arform['main_concern'], function(value, key) { if (arform.main_concern[i]== value) { $scope.arform['main_concern'].push(value); } }); }; } Thanks! -
Bootstrap accordion with Django: How to only load the data for the open accordion section?
I'm trying to make a webpage that will display recipes in the format of a bootstrap accordion like so (see here). This is how I'm doing it as of now: <div class="panel-group" id="accordion"> {% for recipe in recipes %} <div class="panel panel-default"> <div class="panel-heading"> <h4 class="panel-title"> <a data-toggle="collapse" data-parent="#accordion" href="#collapse{{ forloop.counter }}"> {{ recipe }} </a> </h4> </div> <div id="collapse{{ forloop.counter }}" class="panel-collapse collapse"> <div class="panel-body"> <table class="table table-hover"> {% for ingredient in foodtype|ingredients_in_recipe:recipe %} <tr> <td> {{ ingredient.ingredient_name }} </td> <td> {{ ingredient.ingredient_quantity }} </td> </tr> {% endfor %} <p>{{ recipe.details }}</p> </table> </div> </div> </div> {% endfor %} </div> I have made a custom template tag for this like so: @register.filter def ingredients_in_recipe(foodtype, recipe): return foodtype.ingredient_set.filter(recipe=recipe).order_by("ingredient_name") The problem is that I have 200+ recipes and loading all this data is way too slow. Ideally the template tag function ingredients_in_recipe should only be called when the user clicks on the recipe. However from my understanding this isn't possible because Django runs it all then sends the rendered HTML to the user. Is there anyway I could circumvent this issue whilst still keeping the accordion style like in the picture? Thanks in advance, Max -
django adding quotes on subsequent submits
Here's the goal: when the user submits the form, use one view to send the submitted data to the database, then redirect back to the form, but with the data pre-populated. This is mostly working, but something about my implementation is wrapping extra quotes around the string. For now, I'm just using a super-simple form, btw. I enter Billy, and the pre-pop is: "Billy", if I click submit again, it comes back as: "\"Billy\"", then "\"\\\"Billy\\\"\"", and so on (as far as I have tested, anyways. relevant views are: def editUsers(request): if request.method == 'POST': # create a form instance and populate it with data from the request: form = usersForm(request.POST) # check whether it's valid: # process the data in form.cleaned_data as required # redirect to a new URL: name = json.dumps(form.data['user_name']) request.session['editUserName'] = name # call out to limboLogic.py to update values test = name return redirect('../users') # if a GET (or any other method) we'll create a blank form else: return redirect('../users') from .forms import * def users(request): form = None if 'editUserName' not in request.session: # create a blank form form = usersForm() else: # form = equipmentForm(initial='jim') - used to make sure I was branching … -
DRF auth_token: "non_field_errors": [ "Unable to log in with provided credentials."
Both JWT packages written for Django gave me issues with poor documentation, so I try DRF-auth_token package. This is a good example I followed, Django Rest Framework Token Authentication. You should in theory be able to go to localhost:8000/api-token-auth/ urls.py: from django.conf.urls import url, include from django.contrib import admin from django.contrib.auth.models import User from rest_framework.authtoken import views urlpatterns = [ url(r'^admin/', admin.site.urls), url(r'^api/', include('api.urls', namespace='api')), url(r'^orders/', include('orders.urls', namespace='orders')), url(r'^api-token-auth/', views.obtain_auth_token, name='auth-token'), ] Getting a token for users is not working so I have rewritten it myself to make it work: @api_view(['POST']) def customer_login(request): """ Try to login a customer (food orderer) """ data = request.data try: username = data['username'] password = data['password'] except: return Response(status=status.HTTP_400_BAD_REQUEST) try: user = User.objects.get(username=username, password=password) except: return Response(status=status.HTTP_401_UNAUTHORIZED) try: user_token = user.auth_token.key except: user_token = Token.objects.create(user=user) data = {'token': user_token} return Response(data=data, status=status.HTTP_200_OK) My version works: http://localhost:8000/api/login/customer-login/ {"username": "thisguy@example.com", "password": "wombat"} --> { "token": "292192b101153b7ced74dd52deb6b3df22ef2c74" } The DRF auth_token does not work: http://localhost:8000/api-token-auth/ {"username": "thisguy@example.com", "password": "wombat"} --> { "non_field_errors": [ "Unable to log in with provided credentials." ] } settings.py INSTALLED_APPS = [ 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', # third party: 'django_extensions', 'rest_framework', 'rest_framework.authtoken', REST_FRAMEWORK = { 'DEFAULT_PERMISSION_CLASSES': ( 'rest_framework.permissions.IsAuthenticated', ), 'DEFAULT_AUTHENTICATION_CLASSES': ( … -
Getting Django PROD ready best practice on Heroku
I have recently run into some problems flipping off Debug mode on my Heroku instance of Django (filled from the Heroku Django template). I have begun diving through the specific Heroku logs. However, was wondering if anyone has already made a checklist for things one should do after turning off Debug mode on Heroku (allowed hosts, email services etc)? -
Passing request (user) to a class based view
As someone who is a bit new to class based views, I have decided to use them to drive some charts in an application I am working on. However, I would like to make this chart dynamic and would like it to change based on who is seeing it. How can one pass a request (to get the user from) to a class based view? Below is my non-working implementation (working with dummy data but no request being passed): View: class LineChartJSONView(BaseLineChartView, request): user = request.user def get_labels(self): labels = [] items = Item.objects.filter(user = user) for i in items: labels.add(i.name) return labels def get_data(self): prices = [] items = Item.objects.filter(user = user) for i in items: prices.add(i.price) return prices line_chart = TemplateView.as_view(template_name='dashboard/test_chart.html') line_chart_json = LineChartJSONView.as_view() URL: url(r'^chart_data/$', LineChartJSONView.as_view(), name='line_chart_json'), url(r'^chart/$', views.ViewBaseChart, name='basic_chart'), HTML: {% load staticfiles %} <html> <head> <title>test chart</title> </head> <body> <canvas id = "myChart" width="500" height="200"></canvas> <!-- jQuery 2.2.3 --> <script src="{% static 'plugins/jQuery/jquery-2.2.3.min.js' %}"></script> <!-- Bootstrap 3.3.6 --> <script src="{% static 'bootstrap/js/bootstrap.min.js' %}"></script> <!-- ChartJS 1.0.1 --> <script src="{% static 'plugins/chartjs/Chart.min.js' %}"></script> <!-- FastClick --> <script src="{% static 'plugins/fastclick/fastclick.js' %}"></script> <!-- AdminLTE App --> <script src="{% static 'dist/js/app.min.js' %}"></script> <!-- AdminLTE for demo purposes --> … -
Verbose logging in Django on openshift
as mentioned in my other question Django IO error I'm facing some trouble in the download function of my django application. Therefore I want more verbose logging of apache in my openshift logfile python.log. Can anybody point me to the file where I can set the apache log more verbose in an openshift django environment? I'm using this cartridge django example According to the mod_wsgi help page the default log level is WARN. I would like to change it to INFO, but I cant figure out which file I need to modify on my openshift repository. -
Is git required when working with elastic beanstalk?
I've been trying to learn how to use elastic beanstalk for django and have so far gone off these tutorials: Real Python Blog Tutorial AWS Documentation Tutorial The AWS tutorial creates an elastic beanstalk environment and updates it without using a git repository at all. Although the AWS tutorial does not cover setting up an RDS database on AWS, I'd like to accomplish what the AWS tutorial does and additionally set up a mysql database for my django app. Can I do so without a git repository? Any suggestions as to how I can get this done? I've been struggling with trying to connect my app to a database for sometime now. -
Django admin dashboard, not able to "select all" records
I have a weird issue were I am not able to "select all" records for any model in my Django admin dashboard. This is using Django 1.10.1 It is a small issue, but I still rather have it solved. Appreciate any help! -
Target WSGI script cannot be loaded as Python module + no module named Django
I know that the question has already been asked here. I've read tons of answers, but nothing helped. I'm using virtualenv (/root/eb-virt); my Django project is called mediar. All public files are stored in /var/www/html/xxx.com/public_html/ From error log: [Sun Oct 16 18:40:11.737747 2016] [:error] [pid 27659] [client 128.75.240.205:60486] mod_wsgi (pid=27659): Target WSGI script '/var/www/html/xxx.com/django.wsgi' cannot be loaded as Python module. [Sun Oct 16 18:40:11.737808 2016] [:error] [pid 27659] [client 128.75.240.205:60486] mod_wsgi (pid=27659): Exception occurred processing WSGI script '/var/www/html/xxx.com/django.wsgi'. [Sun Oct 16 18:40:11.745983 2016] [:error] [pid 27659] [client 128.75.240.205:60486] Traceback (most recent call last): [Sun Oct 16 18:40:11.746153 2016] [:error] [pid 27659] [client 128.75.240.205:60486] File "/var/www/html/xxx.com/django.wsgi", line 9, in <module> [Sun Oct 16 18:40:11.746165 2016] [:error] [pid 27659] [client 128.75.240.205:60486] import django.core.handlers.wsgi [Sun Oct 16 18:40:11.746191 2016] [:error] [pid 27659] [client 128.75.240.205:60486] ImportError: No module named 'django' My apache2.conf: Mutex file:${APACHE_LOCK_DIR} default PidFile ${APACHE_PID_FILE} Timeout 300 KeepAlive Off MaxKeepAliveRequests 100 KeepAliveTimeout 5 User ${APACHE_RUN_USER} Group ${APACHE_RUN_GROUP} HostnameLookups Off ErrorLog ${APACHE_LOG_DIR}/error.log LogLevel warn IncludeOptional mods-enabled/*.load IncludeOptional mods-enabled/*.conf Include ports.conf <Directory /> Options FollowSymLinks AllowOverride None Require all denied </Directory> <Directory /usr/share> AllowOverride None Require all granted </Directory> <Directory /var/www/> Options Indexes FollowSymLinks AllowOverride None Require all granted </Directory> #<Directory /srv/> # Options … -
Models in Python Django not working for Many to Many relationships
I am trying to create the proper Django model that could fit the following reqs: Person Class has 1 to many relations with the Address Class Person Class has many to many relations with the Group Class Book Class contains the collections of the Persons and the Groups This is my code: class Person(models.Model): first_name = models.CharField(max_length=15) last_name = models.CharField(max_length=20) def __str__(self): return self.first_name+ ' - ' + self.last_name class Address(models.Model): person = models.ForeignKey(Person) address_line = models.CharField(max_length=200) def __str__(self): return self.address_line class Group(models.Model): group_name = models.CharField(max_length=12) persons = models.ManyToManyField(Person) def __str__(self): return self.group_name class Book(models.Model): record_name = models.CharField(max_length=12) person = models.ForeignKey(Person ) group = models.ForeignKey(Group ) def __str__(self): return self.record_name However it's not correct: 1) A Group can now contain multiple Persons but the Persons do not contain any Group. I am not sure if I should add to the Person class the following code: groups = models.ManyToManyField(Group) 2) The Book class now contains only 1 record of Person & Group per Book record. 3) When I added the Foreign Keys to the models, I removed on_delete tag: person = models.ForeignKey(Person, on_delete=models.CASCADE()) because it does not compile it, asking for some params. I know how to make all this for … -
Python Django Queryset
Hello guys I'm playing with querysets in django. What I'm looking it's to save a new foreign product or item but I can not achieve it. shell from applaboratorio.models import Datos_empresa_DB, Datos_equipo_DB detalle = Datos_empresa_DB.objects.filter(pk=58) resp = Datos_equipo_DB(equipo='dell-labtop',marca='dell', modelo='432423',Foraneo_Datos_empresa_DB = detalle) What am I doing bad? I'm trying to create a new product for a client that already exist in db. -
ImportError: No module named socialaccountallauth.socialaccount.providers
I was creating a django app, adding the social auth with django-allauth, i addded 'allauth.socialaccount.providers.facebook' in setting.py; but it gives the following error, and I'm unable to figure out why! Unhandled exception in thread started by <function wrapper at 0x7f8e9ab7c488> Traceback (most recent call last): File "/usr/local/lib/python2.7/dist-packages/django/utils/autoreload.py", line 226, in wrapper fn(*args, **kwargs) File "/usr/local/lib/python2.7/dist-packages/django/core/management/commands/runserver.py", line 113, in inner_run autoreload.raise_last_exception() File "/usr/local/lib/python2.7/dist-packages/django/utils/autoreload.py", line 249, in raise_last_exception six.reraise(*_exception) File "/usr/local/lib/python2.7/dist-packages/django/utils/autoreload.py", line 226, in wrapper fn(*args, **kwargs) File "/usr/local/lib/python2.7/dist-packages/django/__init__.py", line 27, in setup apps.populate(settings.INSTALLED_APPS) File "/usr/local/lib/python2.7/dist-packages/django/apps/registry.py", line 85, in populate app_config = AppConfig.create(entry) File "/usr/local/lib/python2.7/dist-packages/django/apps/config.py", line 116, in create mod = import_module(mod_path) File "/usr/lib/python2.7/importlib/__init__.py", line 37, in import_module __import__(name) ImportError: No module named socialaccountallauth.socialaccount.providers -
django.core.exceptions.ImproperlyConfigured: Could not resolve URL for hyperlinked relationship using view name "user-detail"
I am going through the django-rest-framework tutorial and am currently at a point where function based views (FBV) were switched to class, mixin, and generic based views (CBV, MBV, GBV respectively). After switching to GBV, when I went to test my API, I received this error AssertionError: Expected view SnippetDetail to be called with a URL keyword argument named "pk". Fix your URL conf, or set the '.lookup_field' attribute on the view correctly.. I did some research and found that lookup_field needs to be set to the in the urlpatterns. Currently, my urls.py look like this: from django.conf.urls import url, include from rest_framework.urlpatterns import format_suffix_patterns from snippets import views # API endpoints urlpatterns = format_suffix_patterns([ url(r'^$', views.api_root), url(r'^snippets/$', views.SnippetList.as_view(), name='snippet-list'), url(r'^snippets/(?P<id>[0-9]+)/$', views.SnippetDetail.as_view(), name='snippet-detail'), url(r'^users/$', views.UserList.as_view(), name='user-list'), url(r'^users/(?P<id>[0-9]+)/$', views.UserDetail.as_view(), name='user-detail') ]) # Login and logout views for the browsable API urlpatterns += [ url(r'^auth/', include('rest_framework.urls', namespace='rest_framework')), ] and my views.py look like so: from snippets.models import Snippet from snippets.serializers import SnippetSerializer, UserSerializer from snippets.permissions import IsOwnerOrReadOnly from rest_framework import generics from rest_framework import permissions from rest_framework.decorators import api_view from rest_framework.response import Response from rest_framework.reverse import reverse from django.contrib.auth.models import User @api_view(['GET']) def api_root(request, format=None): return Response({ 'users': reverse('user-list', request=request, format=format), 'snippets': … -
Data from POST is being ignored by Django
I'm having trouble with a form related issue where the data from a POST is clearly being sent back, but Django is stripping it out so that it won't go into my form class. Here are some code snippets from my class's post() that show the data is being returned from the template and then how the data is not making it through the form class filtering. Why is this happening? What is the harm with me taking the data directly from the POST and not using the built-in form class filtering? print(request.POST) Yields this: <QueryDict: {'book': ['Zippity do dah,'], 'weather': ["It's raining!"], 'dividend': ['Zippity aye!'], 'earnings': ['Yo man, one step at a time.'], 'csrfmiddlewaretoken': ['3MWFOwebVeYfCum8JaGvITRB542b3jbp']}> and main_form = self.main_form_class(request.POST) print('\n','main_form: ',main_form) Yields this: main_form: <tr><th><label for="id_weather">weather:</label></th><td><input id="id_weather" maxlength="256" name="weather" size="36" type="text" /></td></tr> <tr><th><label for="id_book">book:</label></th><td><input id="id_book" maxlength="256" name="book" size="36" type="text" /></td></tr> <tr><th><label for="id_dividend">dividend:</label></th><td><input id="id_dividend" maxlength="256" name="dividend" size="36" type="text" /></td></tr> <tr><th><label for="id_earnings">earnings:</label></th><td><input id="id_earnings" maxlength="256" name="earnings" size="36" type="text" /></td></tr> <tr><th><label for="id_csrfmiddlewaretoken">csrfmiddlewaretoken:</label></th><td><input id="id_csrfmiddlewaretoken" maxlength="256" name="csrfmiddlewaretoken" size="36" type="text" /></td></tr> You can see that no 'values' are being included in main_form. main_form.is_valid() is never True main_form.cleaned_data throws an error - if I pull it out in front of main_form.is_valid() Help! -
Django Can't collect static files
STATIC_URL = '/static/' STATIC_ROOT = os.path.join(BASE_DIR ,"static_root") STATICFILES_DIR = [ os.path.join(BASE_DIR,"static") ] When I add files inside static it doesn't go to static_root after making python manage.py collectstatic : 0 static files copied to '/Users/nimeton/memo/static_root' -
User defined fields model in django
I want to allow my users to define custom properties. They are managing apartments so each customer manages the apartments in different way. I want to allow them to define some custom properties for they apartments. class Unit(CommonInfo): version = IntegerVersionField( ) number = models.CharField(max_length=30,null=True, blank=True) max_occupants = models.PositiveSmallIntegerField() floor = models.PositiveSmallIntegerField() rooms = models.PositiveSmallIntegerField() is_disabled_access = models.BooleanField(default=False) balcony_quantity = models.PositiveSmallIntegerField() building = models.ForeignKey(Building) recomended_price = models.DecimalField(max_digits=7, decimal_places=2) I want them to be able additional fields to this model. For example - is_breaker is_fuse Number_of Since I cant predict what data they will require. how can I do it? -
POST request from React classes gets CSRF error from Django server
I am trying to create simple WEB application using Django and React. And last weekend I've spend in attempts to fix curious bug. As you may guess my Django application views use CSRF protection. To provide the most proper CSRF setting I used that article from django project and just copy-paste that code: function getCookie(name) { var cookieValue = null; if (document.cookie && document.cookie !== '') { var cookies = document.cookie.split(';'); for (var i = 0; i < cookies.length; i++) { var cookie = jQuery.trim(cookies[i]); // Does this cookie string begin with the name we want? if (cookie.substring(0, name.length + 1) === (name + '=')) { cookieValue = decodeURIComponent(cookie.substring(name.length + 1)); break; } } } return cookieValue; } var csrftoken = getCookie('csrftoken'); function csrfSafeMethod(method) { // these HTTP methods do not require CSRF protection return (/^(GET|HEAD|OPTIONS|TRACE)$/.test(method)); } $.ajaxSetup({ beforeSend: function(xhr, settings) { if (!csrfSafeMethod(settings.type) && !this.crossDomain) { xhr.setRequestHeader("X-CSRFToken", csrftoken); } } }); into my index.js. And $.post(...) requests (outside React classes) like that: function registration_post() { var msg = $('#registration-form').serialize(); $.ajax({ type: 'POST', url: '/users/', data: msg, success: function(data) { if (typeof data === 'object') { console.log('Account successfully created.'); console.log(data); } else { console.log('Some unnormal errors have been occurred. Here … -
Issues deplying Django project
Okay I am new to the Django framework but I have a basic site that I want live. I have a droplet up on Digital Ocean and my files have been moved over to there. I get this error: mportError at / cannot import name patterns Request Method: GET Request URL: http://188.166.147.202/ Django Version: 1.10.2 Exception Type: ImportError Exception Value: cannot import name patterns Exception Location: /home/django/django_project/django_project/urls.py in <module>, line 1 Python Executable: /usr/bin/python Python Version: 2.7.6 Python Path: ['/home/django/django_project', '/home/django', '/usr/bin', '/usr/lib/python2.7', '/usr/lib/python2.7/plat-x86_64-linux-gnu', '/usr/lib/python2.7/lib-tk', '/usr/lib/python2.7/lib-old', '/usr/lib/python2.7/lib-dynload', '/usr/local/lib/python2.7/dist-packages', '/usr/lib/python2.7/dist-packages', '/usr/lib/python2.7/dist-packages/gtk-2.0'] Server time: Sun, 16 Oct 2016 16:26:46 +0000 urls.py looks like: from django.conf.urls import patterns, include, url from django.contrib import admin admin.autodiscover() urlpatterns = [ url(r'^admin/', include(admin.site.urls)), url(r'^', include('personal.urls')), url(r'^blog/', include('blog.urls')), ] The doplet is currently using python 2.7 but I used python3 while developing so how can I upgrade the version of python on my droplet?