Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Proper way to run a backend project in a VPS
I have a project in Pycharm which is django. its backend is mySQL and uses redis-server and memcached. my VPS is Windows-server 2008. In order to run it in a VPS do i have to move the whole IDE with the project, to VPS and just hit Run in the IDE? It's my first time running a server of my own and it's the only way i can think of. please do correct me if i missed the whole concept. -
Model missing all fields in Django Admin
I have a model with a bunch of fields, and after deploying to production, the django admin shows no fields for that specific model, like at all. I see the top title "Change MODELNAME", and the bottom toolbar with the save buttons. But when i click save, i get a validation error, but still no fields. I get no errors, it's just not showing. The issue occurred after changing something unrelated in the database, and minor changes in the code. But from what i can see, nothing related to the admin. Also the most weird part, it works when running locally using a local database (using postgres in both production and dev env). Django version 1.11.6 -
Change/Update value from an Object via AJAX in Django
I'm using Django Framework and I need some help with POST/GET data via AJAX. I want to change/update is_viewed=True from an Object, when the user click on a specific anchor tag. index.html <ul class="dropdown-menu getNotification"> {% for n in notifications %} <li><a class="dropdown-item" href="/analysis/media/{{ n.n_media_no }}" id="{{ n.n_media_no }}">{{ n.n_media_no }}</a></li> {% endfor %} </ul> <script> $(document).ready(function(){ $('ul.getNotification a').click(function(event) { event.preventDefault(); var media_id = $(this).attr('id'); $.ajax({ //url: window.location.href, type: "POST", // or "get" data: media_id, success: function(data) { alert(data.result); }}); }); }); </script> view.py def home(request): """Renders the home page.""" m_notif = Notification.objects.filter(is_viewed=False) c_notif = Notification.objects.filter(is_viewed=False).count() if request.method == 'POST': if request.is_ajax(): get_value = request.POST.get('media_id') p = MediaNotification.objects.get(pk=get_value) p.is_viewed = 1 p.save() assert isinstance(request, HttpRequest) return render( request, 'app/index.html', { 'c_notif': c_notif, 'm_notif': m_notif, } ) -
Django QuerySet update_or_create creating duplicate entries
Recently I'm facing issues in update_or_create method. Let me give a full explanation first. Model: class TransactionPageVisits(models.Model): transactionid = models.ForeignKey( Transaction, on_delete=models.CASCADE, db_column='transactionid', ) sessionid = models.CharField(max_length=40, db_index=True) ip_address = models.CharField(max_length=39, editable=False) user_agent = models.TextField(null=True, editable=False) page = models.CharField(max_length=100, null=True, db_index=True) method = models.CharField(max_length=20, null=True) url = models.TextField(null=False, editable=False) created_dtm = models.DateTimeField(auto_now_add=True) class Meta(object): ordering = ('created_dtm',) Function: def _tracking(self, request, response, **kwargs): txn_details = kwargs.get('txn_details') data = { 'sessionid': request.session.session_key, 'ip_address': get_ip_address(request), 'user_agent': get_user_agent(request), 'method': request.method, 'url': request.build_absolute_uri(), 'transactionid': txn_details.txn_object, 'page': kwargs.get('page') } # Keep updating/creating tracking data to model obj, created = TransactionPageVisits.objects.update_or_create(**data) Notes: I know I'm not passing any defaults arguments to update_or_create(), as at the time the code was written it was not required (wanted to create a new row only when all the columns as per data is collectively unique). Also _tracking() is in middleware and will be called in each request and response. Everything was going smoothly until today I got following exception: File "trackit.py", line 65, in _tracking obj, created = TransactionPageVisits.objects.update_or_create(**data) File "/usr/local/lib/python2.7/dist-packages/Django-1.10.4-py2.7.egg/django/db/models/manager.py", line 85, in manager_method return getattr(self.get_queryset(), name)(*args, **kwargs) File "/usr/local/lib/python2.7/dist-packages/Django-1.10.4-py2.7.egg/django/db/models/query.py", line 488, in update_or_create obj = self.get(**lookup) File "/usr/local/lib/python2.7/dist-packages/Django-1.10.4-py2.7.egg/django/db/models/query.py", line 389, in get (self.model._meta.object_name, num) MultipleObjectsReturned: get() returned more … -
'Response' object has no attribute 'get'
I am trying perform an auto login by redirecting the user to an external website supplying the authentication information in the header. Tested that it's working in postman. But I am getting a 'Response' object has no attribute 'get' in django when I click on a button which perform this request. I think I am doing this wrongly. What would be the best way to redirect to an external web provided I have the authorization information? Ajax? if req.method == 'POST': url = "https://server.to.reach" headers = { 'Authorization': "Basic YWRtaW46YWRtaW4=", 'Cache-Control': "no-cache", 'Postman-Token': "546de0c9-a4fc-4c0b-8b99-bfbadc9ee7e4", 'Content-Type': "application/x-www-form-urlencoded" } response = requests.request("POST", url, headers=headers) print(response.text) return response -
forms.DateInput default value
I am using a calendar widget using django forms, part of the code- class DateForm(forms.ModelForm): helper.layout = Layout( Div( Field('start', placeholder='date') ) class Meta: model = Date widgets = { 'start': forms.DateInput(attrs={'class':'datepicker'}), } How can I add a default value of todays date to the 'start' variable? I cannot seem to find any default for dateinput. -
python django admin interface, browse records
I want to add two buttons to the record editing window of admin django. One button is to the next record while the other is to the previous. How can I do this? Is there a config parameter to set? -
Django delete() command
I'm building a web app in Django. Their I have a model "DocFile" with a FileField "update". class DocFile(models.Model): name = models.CharField('Bezeichnung', max_length=100) md5sum = models.CharField(max_length=32) upload = models.FileField('Datei', upload_to=media_file_name, storage=MediaFileSystemStorage()) In the followng view I try to delete the database entry (not the file in my media dir) of DocFile where pk=pd. def delete_doc(request, pd, pk): doc = get_object_or_404(DocFile, pk=pd) doc.delete() return redirect('list_docfile', pk=pk) But sadly the delete() command deletes both the database entry and the file in the media dir. I tried to search for a solution but all i got was this: Django delete FileField If Django removed the function that delete() removes the file of the filefield, why does the commadn still removes both in my django application. -
NoReverseMatch in django with kwargs
I'm having trouble getting the {% url %} tag to work with a django view. When visiting the site I get the error: NoReverseMatch at /betalinger/ Reverse for 'confirm' with keyword arguments '{'plan': ''}' not found. 2 pattern(s) tried: ['betalinger/confirm/', 'betalinger/confirm/(?P<plan>.+)/$'] It complains about not finding the url with a keyword argument, but at least one of the urls accepts the plan keyword. urls.py: ... url(regex=r'^confirm/(?P<plan>.+)/$', view=ConfirmFormView.as_view(), name='confirm'), url(regex=r'^confirm/', view=ConfirmFormView.as_view(), name='confirm'), ... And the template making noise: <html> ... <form action="{% url 'payments:confirm' plan=plan.plan %}"> ... </html> -
Getting error when changing sqlite3 to mysql in windows 2012 server iis
i am trying hosting django application to windows server 2012 iis, everything working fine with sqlite3, but when i changed my database to mysql i am getting error. raise ImproperlyConfigured("Error loading MySQLdb module: %s" % e) ImproperlyConfigured: Error loading MySQLdb module: No module named MySQLdb. I changed database settings in django to mysql. Thanks -
Pass username and password with angular 5 http request to django rest api
am integrating django rest api with angular 5. Django rest framework implements it's basic auth and accept username and password. Am able to hit api with postman by providing username and password in Headers menu but when i hit api from angular it retruning 401. I have tried multiple solutions but not getting perfect solution here is what i am trying httpOptions = { headers: new HttpHeaders({ 'Content-Type': 'application/json', 'Username': <username>, 'Password': <password> }) }; return this.http.get(url, this.httpOptions) .toPromise() .then(res=>{ return res; }); -
How to reference class instance outside method - Python
I'm writing Django app, I want to create different directory for every different Trip. This code doesn't work (using method): class TripPhoto(models.Model): def __str__(self): return self.trip_id.title trip_id = models.ForeignKey(Trip, on_delete=models.CASCADE) def get_trip_title(self): return self.trip_id.title photo = models.ImageField(upload_to="reservations/" + get_trip_title() + "/") # NEED FIX photo = models.ImageField(upload_to="reservations/" + get_trip_title() + "/") # NEED FIX TypeError: get_trip_title() missing 1 required positional argument: 'self' This code doesn't work too (using attribute): class TripPhoto(models.Model): def __str__(self): return self.trip_id.title trip_id = models.ForeignKey(Trip, on_delete=models.CASCADE) photo = models.ImageField(upload_to="reservations/" + str(trip_id.title) + "/") # NEED FIX photo = models.ImageField(upload_to="reservations/" + str(trip_id.title) + "/") # NEED FIX AttributeError: 'ForeignKey' object has no attribute 'title' I know that I can use self.trip_id.title, because I used it in another part of the code. Is there any way to use self (instance reference?) outside of class method? -
Django rest framework logging different levels on different files
I am working on Django REST framework and I want to have separate files for logging data. I want to have a file for the simple transactions e.g. GET, PUT, POST etc. and one file with the errors that I will collect in case of an error. I have been reading the Django Logging Documentation and I came up with some configurations on how to log the info data. Sample of configurations bellow: settings.py STATIC_URL = '/static/' PROJECT_ROOT = os.path.dirname(os.path.abspath(__file__)) STATIC_ROOT = os.path.join(PROJECT_ROOT, 'static') LOGGING_ROOT = os.path.join(STATIC_ROOT, 'logging') LOGGING = { 'version': 1, 'disable_existing_loggers': False, 'handlers': { 'file': { 'level': 'INFO', 'class': 'logging.FileHandler', 'filename': LOGGING_ROOT + "/info.log", }, }, 'loggers': { 'django': { 'handlers': ['file'], 'level': 'INFO', 'propagate': True, }, }, } It works as expected sample of data in file: "PUT /upload/dat.txt HTTP/1.1" 204 14 "OPTIONS / HTTP/1.1" 200 10020 "GET / HTTP/1.1" 200 9916 I tried to apply another handler in the settings.py file e.g.: LOGGING = { 'version': 1, 'disable_existing_loggers': False, 'handlers': { 'fileInfo': { 'level': 'INFO', 'class': 'logging.FileHandler', 'filename': LOGGING_ROOT + "/info.log", }, 'fileDebug': { 'level': 'DEBUG', 'class': 'logging.FileHandler', 'filename': LOGGING_ROOT + "/debbug.log", }, }, 'loggers': { 'django': { 'handlers': ['fileInfo'], 'level': 'INFO', 'propagate': True, }, … -
Authenticate AWS Lambda in Django
Issue: I want to authenticate the response from lambda to Django Summary: My Django app invokes an AWS Lambda with some url, lambda does the processing and a couple of seconds later should return the result to Django. Now, how do I ensure that the response from lambda is valid, and it's not someone trying to call my django endpoint? Setup: Django running on an EC2 machine behind nginx + uwsgi Lambda called from Django using boto3.client('lambda').invoke(...) Lambda code: def handler(event, context): data = event['data'] result = get_my_result(data) requests.post('https://www.example.com/foo/bar', data=json.dumps(result)) I was considering Django REST framework, but it's not like I have a specific user calling the lambda, so I think it doesn't quite suite the purpose. I have never done this kind of 3rd party service authentication in Django, not sure what the most elegant (+secure and efficient) approach would be. Thanks for help! -
Django Foreign Key class not showing
The goal is to have a dashboard show a list of users in your area. The list of users works and it shows the Username. The only issue is I can't get the users images (ideally just have 1st image) to show. There are no error messages currently. Just nothing appearing. models.py class Images(models.Model): image = models.ImageField(upload_to='profile_image', null=True, default='profile_image/none/no-img.png') user = models.ForeignKey(User, on_delete=models.CASCADE, null=False) class Profile(models.Model): user = models.OneToOneField(User, on_delete=models.CASCADE) bio = models.TextField(max_length=500, blank=True, null=True) birth_date = models.DateField(null=True, blank=True) ... views.py class DashboardView(TemplateView): template_name = 've/cp/dashboard.html' @method_decorator(login_required) def dispatch(self, *args, **kwargs): return super(DashboardView, self).dispatch(*args, **kwargs) def get(self, request, pk=None): users = User.objects.exclude(id=request.user.id) try: favorite = Favorite.objects.get(current_user=request.user) favorites = favorite.users.all() except Favorite.DoesNotExist: favorites = None args = { # 'users': users, 'favorites':favorites, 'images': images, } return render(request, self.template_name, args) dashboard.html <div class="col-12"> <h2>People near you</h2> {% for user in users %} <a href="{% url 've:view_profile_with_pk' pk=user.pk %}"> <!--THIS WORKS--> <h4>{{ user.username }}</h4> <p>{{ user.profile.bio }}</p> <!--But not this... why..--> <p>{{ user.images.image.url }}</p> ''' Or this.. However it does work on view_profile page where there is a pk. Seem like it's not finding images for users, as this results in a "No images message on localhost ''' {% if images %} {% … -
Auto Fake Django Migration
I need to auto fake a Django 1.9 migration. Is there a flag that can put in the migration file that will auto fake, rather than having to log onto multiple servers and run. The migrations layout is like this migtarions |-- 0001_initial.py |-- 0002.py |-- 0003.py I know I can do ./manage.py my_app migrate 0002 --fake, but can migration 0002 be auto faked ? and all I need to run is ./manage.py my_app migrate -
What IP do I use to send data from Android to Django Server?
I need to send a JSON from my Mobile Application to a Django server on Ubuntu (which I'm using on Virtualbox). My primary OS is Windows. What IP should I use? Sequence: Android -> Windows -> Ubuntu -> Django Server -
Django - field missing from cleaned data
I am using model form and I'm trying to bypass validation of one particular field. I have ascertained that I need use the clean() method to bypass the field. however when im printing out the cleaned data the assigned_subnets field is not in the dictionary, it is missing output from print: {'site_data': None, 'switches': None, 'hostname': 'STR--RTR-01', 'template': <ConfigTemplates: STR-RTR-01>, 'model': <DeviceModel: Cisco - 4431>, 'install_date': datetime.date(2016, 5, 26), 'ospf_area': None, 'snmp_data': <SNMPData: XXXX>, 'available_subnets': <QuerySet []>} forms.py class DeviceForm(forms.ModelForm): class Meta: model = DeviceData fields = ['site_data', 'switches', 'hostname', 'template', 'model', 'install_date','ospf_area','snmp_data'] def clean(self): super(DeviceForm, self).clean() print(self.cleaned_data) if self.cleaned_data.get('assigned_subnets') in self._errors: del self._errors['assigned_subnets'] return self.cleaned_data def __init__(self, *args, **kwargs): site_id = kwargs.pop('site_id', None) device_id = kwargs.pop('device_id', None) self.is_add = kwargs.pop("is_add", False) super(DeviceForm, self).__init__(*args, **kwargs) devicesubnet = Subnets.objects.filter(devicesubnets__device_id=device_id) sitesubnet = Subnets.objects.filter(sitesubnets__site_id=site_id) common_subnets = list(set(devicesubnet) & set(sitesubnet)) subnet_id_list = [] for s in common_subnets: subnet_id_list.append(s.id) available_subnet_data = sitesubnet.exclude(id__in=subnet_id_list) assigned_choices = [] devicesubnet_data = DeviceSubnets.objects.filter(device_id=device_id) for choice in devicesubnet_data: assigned_choices.append((choice.subnet.id,choice.subnet.subnet)) self.fields['available_subnets'] = forms.ModelMultipleChoiceField( label='Available Subnets', queryset=available_subnet_data, widget = forms.SelectMultiple( attrs = {'class': 'form-control', 'size' : '15'} ) ) self.fields['assigned_subnets'] = forms.MultipleChoiceField( label='Assigned Subnets', choices=assigned_choices, widget = forms.SelectMultiple( attrs = {'class': 'form-control', 'size' : '15'} ) ) self.fields['available_subnets'].required = False self.fields['assigned_subnets'].required = False … -
Django JSON serializer use lowercase for the model
My problem is that Django serializers convert the models names to lowercase. Client side, I get this : { "fields": {"key":"val", "key2":"val2"}, "pk" : 12, "model" : "MyApp.mymodelnametolowercase" } In the documentation is is said : Each such object has two attributes: « pk » and « model », the latter being represented by the name of the app (« sessions ») and the lowercase name of the model (« session ») separated by a dot. This is my code : def list(): lDataList = Book.objects.all() oData = serializers.serialize('json', lDataList) return oData Sorry for not respecting pep8, you'll have to talk to my boss about that though... Anyway, is there a way to tell the serializer not to convert the model name to lowercase ? -
Multiprocessing function in python3 starts throwing several Keyerrors while processing a large pandas dataframe after 1200 lines of processing
I'm processing pandas dataframes from a csv file having more than 10,000 lines of data and after processing 1200 lines properly, my code randomly starts throwing keyerrors for a few entries and at the same indexes every time, regardless of which entry falls under those indexes. Here's my code: p = multiprocessing.Process(target = calc, args = (i, c, df, a, b, file_id, user.pk)) db.connections.close_all() p.start() p.join() That's where the keyerror occurs in calc(): df = df.append([[ i, t_data.loc[c.index(i), 'Asset Description'], t_data.loc[c.index(i), 'Asset Value'], (str(key.loc[j, 'Keyword_1']) + ' ' + str(key.loc[j, 'Keyword_2'])), t_data.loc[c.index(i), 'Current Asset Category'], t_data.loc[c.index(i), 'Current Depreciation'], '%.2f' % float((int(t_data.loc[c.index(i), 'Current Depreciation']) * float(t_data.loc[c.index(i), 'Asset Value'])) / 100), key.loc[j, 'Suggested Asset Category'], key.loc[j, 'Depreciation Rate'], '%.2f' % float((int(key.loc[c.index(i), 'Depreciation Rate']) * float(t_data.loc[c.index(i), 'Asset Value'])) / 100), key.loc[j, 'Probability']]]) df[1:].to_csv('media/' + '%s_%s.csv' % (user_pk, file_id), sep='\t', mode = 'a', header = False, index = False) The error says: enter image description here "Process Process-9623: Traceback (most recent call last): File "/usr/local/lib/python3.5/dist-packages/pandas/core/indexing.py", line 1506, in _has_valid_type error() File "/usr/local/lib/python3.5/dist-packages/pandas/core/indexing.py", line 1501, in error axis=self.obj._get_axis_name(axis))) KeyError: 'the label [9622] is not in the [index]' In the final result, I get 98 keyerrors in 10,000 lines. How do I get rid of it? -
openPyxl does not append values when used in for loop
for users in user_ids: user_detail_obj = Users.objects.filter(id=users).first() benchmark_data = get_data_point(users, user_ids) headers = ['User ID', 'Name', 'Email', 'Parameter Name', 'Pre-Assess-Score', 'Current-Score', 'Org-Score'] ws = book.create_sheet(str(user_detail_obj.name) + "-" +str(users)) ws.append(headers) ws.cell(row=2, column=1).value = user_detail_obj.id ws.cell(row=2, column=2).value = user_detail_obj.name ws.cell(row=2, column=3).value = user_detail_obj.email ws.cell(row=4, column=4).value = "hi" i = 3 column = 4 for obj in benchmark_data: ws.cell(row=i, column=4).value = obj['parameter_name'] i = i +1 This code fails in inner for loop, it doesnt throw any error, excel file is properly generated with headers and their data. What I want to do is to create sheet for every user and inside that sheet we get single(User ID , name , email) multiple( parameter,name , preassess-score, curr-score, org-score) Function get_data_point gives list of dictionaries. I tried with xlsxwriter but same issue. Please suggest correct and alternative way to do this. Sample below { "result": [ { "preassess_score": 0, "current_score": 0, "current_org_score": 0, "parameter_name": "Influencing Skills", "parameter_id": 18 }, { "preassess_score": 0, "current_score": 0, "current_org_score": 0, "parameter_name": "Influence without authority", "parameter_id": 97 }, ] } -
Dockerize Django App and Apache2 with Docker
I'm trying to Dockerize my Django Web App with Docker in order to migrate it to my production server. This server is based to Linux Ubuntu 16.04 and I would like to install Apache2 into my container. I found different way to use Docker, particulary to this github repository : https://github.com/ramkulkarni1/django-apache2-docker ------------------------------------------------------------------------------------------------------------------------------------ FIRST PART - My tree project : ------------------------------------------------------------------------------------------------------------------------------------ DatasystemsCORE ├── API_GED ├── Authentification ├── Configurations ├── DatasystemsCORE ├── App1 ├── App2 ├── App3 ├── App4 ├── lib ├── static ├── templates ├── wsgi.conf ├── docker-compose.yml ├── Dockerfile ├── manage.py ├── requirements.txt ├── start.sh ------------------------------------------------------------------------------------------------------------------------------------ SECOND PART - Files according to Docker : ------------------------------------------------------------------------------------------------------------------------------------ So I created a Dockerfile : FROM ubuntu RUN apt-get update RUN apt-get install -y apt-utils vim curl apache2 apache2-utils RUN apt-get -y install python3 libapache2-mod-wsgi-py3 RUN ln /usr/bin/python3 /usr/bin/python RUN apt-get -y install python3-pip RUN ln /usr/bin/pip3 /usr/bin/pip RUN pip install --upgrade pip RUN pip install django ptvsd ADD ./demo_site.conf /etc/apache2/sites-available/000-default.conf EXPOSE 80 3500 CMD ["apache2ctl", "-D", "FOREGROUND"] FROM python:3.6 ENV PYTHONUNBUFFERED 1 ADD ./requirements.txt /requirements.txt RUN pip install -U pip && LIBRARY_PATH=/lib:/usr/lib /bin/sh -c "pip install -r /requirements.txt --no-cache-dir" RUN mkdir /code WORKDIR /code ADD ./src . EXPOSE 8000 ADD ./start.sh /start.sh RUN … -
from common.decorators import ajax_required throws error: ModuleNotFoundError: No module named 'common'
I have a view in Django that requires @ajax_required decorator So i try to import it in my app views: from common.decorators import ajax_required Server throws an error while trying to import the module: from common.decorators import ajax_required ModuleNotFoundError: No module named 'common' Is there any good workaround on this - import the decorators module to python? Any help much appreciated! Regards, Lukasz -
access current user in django model manager
I am making a CRUD application, and I have the current piece of code in my view: def dashboard(request): template = 'dashboard/index.html' form = CustomerForm() if request.user.groups.filter(name__in=['West']).exists(): customers = Customer.objects.filter(Q(department='630') | Q(department='635')).all() elif request.user.groups.filter(name__in=['North']).exists(): customers = Customer.objects.filter(Q(department='610') | Q(department='615') | Q(department='620')).all() elif request.user.groups.filter(name__in=['East']).exists(): customers = Customer.objects.filter(Q(department='660') | Q(department='655') | Q(department='650')).all() elif request.user.groups.filter(name__in=['South']).exists(): customers = Customer.objects.filter(Q(department='640') | Q(department='645')).all() elif request.user.groups.filter(name__in=['North-West']).exists(): customers = Customer.objects.filter(Q(department='625')).all() else: customers = Customer.objects.all() context = { "customers": customers, "form": form, } return render(request, template, context) I have separate create, update and delete functions that also need to use the same if-statement. I learned about model-manages and created the following: class CustomerQueryset(models.query.QuerySet): def customer_department_query(self): if request.user.groups.filter(name__in=['West']).exists(): customers = Customer.objects.filter(Q(department='630') | Q(department='635')).all() elif request.user.groups.filter(name__in=['North']).exists(): customers = Customer.objects.filter(Q(department='610') | Q(department='615') | Q(department='620')).all() elif request.user.groups.filter(name__in=['East']).exists(): customers = Customer.objects.filter(Q(department='660') | Q(department='655') | Q(department='650')).all() elif request.user.groups.filter(name__in=['South']).exists(): customers = Customer.objects.filter(Q(department='640') | Q(department='645')).all() elif request.user.groups.filter(name__in=['North-West']).exists(): customers = Customer.objects.filter(Q(department='625')).all() else: customers = Customer.objects.all() class CustomerManager(models.Manager): def get_queryset(self): return CustomerQueryset(self.model, using=self.db) def get_customer_group(self): return self.get_queryset().customer_department_query() I of course found out that the model-manager can't access the request so I created the following middleware: class GetUser(object): def __init__(self, get_response): self.get_response = get_response def __call__(self, request): user = (request.user) request.current_user = user user_group = request.user.groups.all() print(user) print(user_group) response = … -
Django not show tzinfo=<UTC>
I am using three different database and when I run a query the tzinfo= not appear despite in my settings the UTC timezone was set. In my developer environment the tzinfo appear, although I use just one databse there. That is why the main problem is that the databse show 1 hour minus from UTC. Here is my timezone setting: TIME_ZONE = 'UTC' My databseses: DATABASES = { 'default': { 'ENGINE': 'django.db.backends.sqlite3', 'NAME': os.path.join(BASE_DIR, 'db.sqlite3'), }, 'db2_database': { 'ENGINE': 'django.db.backends.postgresql', 'NAME': 'db2_name', 'USER': 'db2', 'PASSWORD': '', 'HOST': '', 'PORT': '', }, 'db3_database': { 'ENGINE': 'django.db.backends.postgresql', 'NAME': 'db3_name', 'USER': 'db3', 'PASSWORD': '', 'HOST': '', 'PORT': '', } } My result: 'time_stamp': datetime.datetime(2018, 3, 7, 7, 50, 44)} My result in my developer environment: 'time_stamp': datetime.datetime(2018, 3, 7, 7, 50, 44, tzinfo=<UTC>)} In my databse | time_stamp | +------------------------+ | 2018-03-07 07:50:44+01 |