Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Which model field type would be appropriate for a date-time object that is repeatedly saved in the database, and needs to be displayed as a string?
The question is a bit ambiguous, allow me to explain: I'm creating something like a changelog, which will note the date-time an object is created along with the objects created. When the objects are updated in the database, I'll get a snapshot of the date-time and record the newly changed objects along with the current & new date-time--the previous snapshots of object+date-time are already also stored. Here is an example of the kind of "changelog" I am trying to display as text on the site: Oct. 24, 2017, 11:22 a.m "Cats and dogs", "Apples and oranges" Oct. 19, 2017, 12:04 p.m "This is a string object", "This is the second object/preference" Sep. 03, 2017, 01:22 a.m "This object was saved long ago", "As was this one" So, the question is two-fold--which model fieldtypes would be appropriate for an object that needs to record the current date-time, but also how do I have the previous changelogs persist in the DB as text to be displayed, instead of just querying the most recent one? In the following failed attempt, the Profile model contains the objects/"preferences" to be changed and recorded, and an updated field to save the current date-time when the object … -
Django-rest-framework: Validate a ListSerializer
I receive a number of similar objects as an input for my API, and I deserialize them using my own serializer with the parameter many=True like this: serializer = MySerializer(data=request.data, many=True) The serializer is an instance of ListSerializer. Then I need to make sure that there are certain combinations of objects in that list. However, I don't seem to find a way to write a .validate() method on the ListSerializer of replace it by my own ListSerializer implementation. Is there a way to do this validation in the serializer, or do I have to iterate over the deserialized objects and check them? -
Javascript (string) Equality with Django Template
I'm new in Javascript and this is my html code that contain django template : <img src="{% static 'basic/main.js' %}" alt="img"/> and my js is : var myImg = document.querySelector('img'); var myImgSrc = myImg.getAttribute('src'); my problem is when i try equality test in web console : myImgSrc === "{% static 'basic/main.js' %}" is return false may be there is escape character or special character to represent my django template, can someone explain how to represent django template in literal js string. Thank you sorry for my bad english. -
Trying to add custom fields to users in Django
I am fairly new to django and was it was going well until this. i'm trying to add fields 'address' and 'phone_number' to users (create custom user basically) but i keep getting this error like this... File "C:\Users\will5\Desktop\City\city_info\forms.py", line 5, in <module> class UserForm(forms.ModelForm): File "C:\Users\will5\AppData\Local\Programs\Python\Python36-32\lib\site- packages\django\forms\models.py", line 257, in __new__ raise FieldError(message) django.core.exceptions.FieldError: Unknown field(s) (phone_number, address) specified for User this is models ... from django.contrib.auth.models import AbstractUser class User(AbstractUser): phone_number = models.IntegerField(default=0) address = models.CharField(max_length=150) ... this is in my forms from django.contrib.auth.models import User from django import forms class UserForm(forms.ModelForm): password = forms.CharField(widget=forms.PasswordInput) class Meta: model = User fields = ['username', 'email', 'password', 'address', 'phone_number'] I also read that in order to fix this problem i will have to restart my project by creating the custom user and migrating and i don't wanna do that. -
Page not found (404) error happens
I got an error,Page not found (404) when I put logout button in detail.html. I wrote in header.html <header class="clearfix"> <h1 class="title">WEB SITE</h1> <div class="collapse navbar-collapse head_content" id="navbarNavDropdown"> <ul class="navbar-nav top-menu"> <li class="nav-item top-menu-item"><i class="fa fa-plus" aria-hidden="true"> <a class="nav-link icon_head" href="/accounts/see">SEE</a></i> </li> <li class="nav-item dropdown top-menu-item"><i class="fa fa-eye" aria-hidden="true"> <a class="nav-link dropdown-toggle icon_head" href="" id="navbarDropdownMenuLink" data-toggle="dropdown" aria-haspopup="true" aria-expanded="false"> KNOW </a> <div class="dropdown-menu" aria-labelledby="navbarDropdownMenuLink"> <div class="dropdown-content"> <a class="dropdown-item" href="/accounts/nowknow">KNOW1</a> </div> <div class="dropdown-content"> <a class="dropdown-item" href="/accounts/pastknow">KNOW2</a> </div> </div> </i> </li> </ul> </div> <a class="logout_button" href="/accounts/logout_view">LOGOUT</a> </header> I wrote in views.py @login_required def logout_view(request): logout(request) return redirect('regist') @login_required def regist(request): return render(request, 'registration/regist.html') @login_required def see(request): return render(request, 'registration/see.html') @login_required def nowknow(request): return render(request, 'registration/nowknow.html') @login_required def pastknow(request): return render(request, 'registration/pastknow.html') @login_required def detail(request): return render(request, 'registration/detail.html') in urls.py urlpatterns = [ url(r'^product$', views.logout_view,name='logout_view'), url(r'^past_result$', views.see,name='see'), url(r'^privacy_policy$', views.nowknow,name='nowknow'), url(r'^privacy_policy$', views.pastknow,name='pastknow'), url(r'^detail$', views.detail,name='detail'), ] I wrote in index.html <html lang="ja"> <head> <meta charset="UTF-8"> <script src="https://code.jquery.com/jquery-1.11.0.min.js"></script> <title>WEB SITE</title> </head> <body class="relative"> {% include '../header.html' %} <main> <p>HELLO WORLD</p> </main> </body> </html> When I acsess index.html and put LOGOUT link,logout is done accurately.But I wrote in detail.html <html lang="ja"> <head> <meta charset="UTF-8"> <script src="https://code.jquery.com/jquery-1.11.0.min.js"></script> <title>DETAIL</title> </head> <body class="relative"> {% include '../header.html' %} <main> <p>HOGE</p> </main> </body> … -
django markdownx isn't allowing normal html tags
yesterday i added django-markdownx to my project every thing is working fine with this custom filter: import markdown @register.filter def markdownify(text): return markdown.markdown(text, safe_mode='escape') this is converting markdown to html but if the filed contain normal html it will convert the markdown successfully but not the normal html this is how i use the filter {{ Post.body|markdownify|safe|linebreaks }} thanks in advanced -
Django: get duplicates based on annotation
I want to get all duplicates based on a case insensitive field value. Basically to rewrite this SQL query SELECT count(*), lower(name) FROM manufacturer GROUP BY lower(name) HAVING count(*) > 1; with Django ORM. I was hoping something like this would do the trick from django.db.models import Count from django.db.models.functions import Lower from myapp.models import Manufacturer Manufacturer.objects.annotate( name_lower=Lower('name'), cnt=Count('name_lower') ).filter('cnt__gt'=1) but of course it didn't work. Any idea how to do this? -
Select a valid choice. x is not one of the available choices
I know this question has been asked a dozen times already on Stackoverflow, but I have been through all of them and they don't fix my problem. Usually most of them are related to choices being characters when the model field is integer and vice versa. But this is my situation I'm working on Django helpdesk, an open source django based ticketing platform that can be found here: https://github.com/django-helpdesk/django-helpdesk And I have made a few changes to their forms.py for Public ticket submission and it was working all this while until I recently added a new queue. Forms.py class PublicTicketForm(CustomFieldMixin, forms.Form): queue = forms.ChoiceField( widget=forms.Select(attrs={'class': 'form-control'}), label=_('Queue'), required=True, choices=() ) So, this form will get choices populated in the views when its called form = PublicTicketForm(initial=initial_data) form.fields['queue'].choices = [(q.id, q.title) for q in Queue.objects.filter(allow_public_submission=True)] + \ [('', 'Other')] #I'm thinking this line may be the problem here return render(request, 'helpdesk/public_homepage.html', { 'form': form, 'helpdesk_settings': helpdesk_settings, }) Here's what the form.fields['queue'].choices prints: [(6L, u'Account'), (7L, u'Support'), (4L, u'Orders'), (5L, u'Products'), (8L, u'Request '), (u'', u'Other')] So, whenever I select a queue and submit, the form won't submit and will throw me "Not one of the available choices" error. As far I … -
Getting latest value in a queryset?
I have a table that looks a bit like this: date | timestamp | predicted_value 2017-10-25| 21758492893 | 0.4 2017-10-25| 21758492917 | 0.3 2017-10-25| 21758493210 | 0.4 2017-10-25| 21758493782 | 0.2 2017-10-25| 21758494903 | 0.1 2017-10-26| 21758492893 | 7.2 .... I'd like to be able to use a single query to get the latest predicted_value for a given date, by timestamp. I.E in my output I want: date | timestamp | predicted_value 2017-10-25| 21758494903 | 0.1 2017-10-26| 21758494903 | 7.7 .... I think it should go something like this: Predictions.objects.all().order_by( '-timestamp' ).values( 'date' ).annotate( prediction=F('predicted_value') ) Is this going to work? Will F select the first value found in the aggregation or can I not use it that way? -
How to three-level query in Django?
I have three tables, names A, B, C: class A(models.Model): name = models.CharField(max_length=12) class B(models.Model): name = models.CharField(max_length=12) a = models.ForeignKey(to=A) class C(models.Model): name = models.CharField(max_length=12) email = models.EmailField() b = models.ForeignKey(to=B) I want get the bellow data: [ {"name":"a1", "data":[{ "name":"b1", "data":[ {"name":"c1", "data":{"c1_name":"c1_name", "c1_id":"c1_id"} }, {"name":"c2", "data":{"c2_name":"c2_name", "c2_id":"c2_id"} } ] }, { "name":"b1", "data":[ {"name":"c1", "data":{"c1_name":"c1_name", "c1_id":"c1_id"} }, {"name":"c2", "data":{"c2_name":"c2_name", "c2_id":"c2_id"} } ] } ] } ] You see, there is three-level data, if there is only table A and B, I can multi-table connection query: B.objects.filter(a='search_id') But now there is three tables, and you see the table C's email is not contain in the query data. How to realize this requirement in my scenario? -
Django migration between branches releases
We are to start branching our master code in the first stable version, and the company has to maintain 2 feature releases. To manage the migrations we use the django migration, but what we don't know is how to load with the hotfix scripts that we could have in the feature releases and master too. I used to use flyway witch let you run the migration with out of order, so if you had in you branch the versions [001, 002, 003, 006], and master [001, 002, 003, 004, 005, 006, 007], where 006 was a hotfix replicated in both, when you migrate to the next version from master the 006 will be skipped. I need a solution like this or a workflow that solve it in django. I couldn't find it. Thank you -
How to add lists containing dictionaries and sort them?
I've 15 lists, each of them contains dictonaries. I've made all of them into a single list by adding all of them. For that I've used following code: UnSorted List: [ {'timestamp': '2017-10-25 15:17:17', 'pk': 80, 'tag': 'SystemBoundaryTriggers'}, {'timestamp': '2017-10-25 15:17:24', 'pk': 81, 'tag': 'SystemBoundaryTriggers'}, {'timestamp': '2017-10-24 17:14:19', 'tag': 'Generate_RequirementsTriggers'}, {'timestamp': '2017-10-24 17:16:13', 'tag': 'Generate_RequirementsTriggers'}, {'timestamp': '2017-10-24 17:16:40', 'tag': 'Generate_RequirementsTriggers'}, {'timestamp': '2017-10-24 17:40:38', 'tag': 'Generate_RequirementsTriggers'}, {'timestamp': '2017-10-24 17:40:39', 'tag': 'Generate_RequirementsTriggers'}, {'timestamp': '2017-10-24 17:40:40', 'tag': 'Generate_RequirementsTriggers'}, {'timestamp': '2017-10-25 16:35:08', 'tag': 'User_Sustainability_DefinitionsTrigger'}, {'timestamp': '2017-10-25 16:35:15', 'tag': 'User_Sustainability_IndicatorsTrigger'}, {'timestamp': '2017-10-25 16:35:22', 'tag': 'TaskClarification_gmTrigger'}, {'timestamp': '2017-10-25 16:35:28', 'tag': 'TaskClarification_gmTrigger'}, {'timestamp': '2017-10-25 16:35:36', 'tag': 'TaskClarification_sTrigger'}, {'timestamp': '2017-10-25 16:41:08', 'tag': 'TaskClarification_sTrigger'}, {'timestamp': '2017-10-25 16:41:51', 'tag': 'TaskClarification_sTrigger'}, {'timestamp': '2017-10-25 16:35:46', 'tag': 'Conceptual_gsTrigger'}, {'timestamp': '2017-10-25 16:35:51', 'tag': 'Conceptual_esTrigger'}, {'timestamp': '2017-10-25 16:36:23', 'tag': 'Conceptual_esTrigger'}, {'timestamp': '2017-10-25 16:36:46', 'tag': 'Conceptual_esTrigger'}, {'timestamp': '2017-10-25 16:36:49', 'tag': 'Conceptual_esTrigger'}, {'timestamp': '2017-10-25 16:37:02', 'tag': 'Conceptual_esTrigger'}, {'timestamp': '2017-10-25 16:37:07', 'tag': 'Conceptual_gsmsTrigger'}, {'timestamp': '2017-10-25 16:38:40', 'tag': 'Conceptual_gsmsTrigger'}, {'timestamp': '2017-10-25 16:38:42', 'tag': 'Conceptual_gsmsTrigger'}, {'timestamp': '2017-10-25 16:38:46', 'tag': 'Conceptual_gsmsTrigger'}, {'timestamp': '2017-10-25 16:38:52', 'tag': 'Conceptual_gsmsTrigger'}, {'timestamp': '2017-10-25 16:40:16', 'tag': 'Conceptual_gsmsTrigger'}, {'timestamp':'2017-10-25 16:40:21', 'tag': 'Conceptual_gsmsTrigger'}, {'timestamp': '2017-10-25 17:11:05', 'nstep': '1', 'tag': 'Step Data'}, {'timestamp': '2017-10-25 17:11:05', 'nstep': '2', 'tag': 'Step Data'}, {'timestamp': '2017-10-25 17:18:16', 'nstep': '2', 'tag': 'Step Data'}] I used … -
Django heroku Forbidden (Referer checking failed - no Referer.)
Trying to setup Facebook Messenger webhook to heroku review app. Weired issue can't get rid of Forbidden (Referer checking failed - no Referer.): Heroku logs 2017-10-25T12:48:44.573509+00:00 heroku[router]: at=info method=POST path="/integrations/messenger/webhook/" host=fiobot-pr-10.herokuapp.com request_id=4adf281c-bd8e-40c8-873b-6731372af69c fwd="173.252.98.197" dyno=web.1 connect=0ms service=14ms status=403 bytes=3571 protocol=https 2017-10-25T12:48:44.562928+00:00 app[web.1]: Forbidden (Referer checking failed - no Referer.): /integrations/messenger/webhook/ Tried Made these changes in settings but the problem still occours. CSRF_TRUSTED_ORIGINS = ['*.herokuapp.com'] views.py @csrf_exempt @require_POST def webhook_post(request): """ Respond to messenger POST method web hook call -
AWS AMI Virtual Host showing
i have tried creating the virtual hosts via this following link Digital Ocean Virtual Host However it is using only first vhost settings. i have tried many tutorials but nothing is working. Finally i have put the vhost settings in httpd.conf file Listen 8000 <VirtualHost *:80> ServerName abc.edu ServerAlias www.abc.edu DocumentRoot /var/www/html/abc/frontend/dist <Directory /var/www/html/abc/frontend/dist> Options +Indexes +FollowSymLinks +MultiViews AllowOverride All Order allow,deny allow from all </Directory> </VirtualHost> <VirtualHost *:8000> ServerName apiabc.edu ServerAlias www.apiabc.edu Alias /static /var/www/html/abc/abc/static <Directory /var/www/html/abc/abc/static> Require all granted </Directory> <Directory /var/www/html/abc/abc/abc> <Files wsgi.py> Require all granted </Files> </Directory> WSGIDaemonProcess abc python-path=/var/www/html/abc/abc python-home=/var/www/html/abc/env WSGIProcessGroup abc WSGIScriptAlias / /var/www/html/abc/abc/abc/wsgi.py </VirtualHost> -
Cant figure out DJango error
Hey guys is there any way to figure out what file this error is being thrown for? serverad@ubuntu:~/django14_project/my_django15_project$ python manage.py runserver --traceback --settings=settings -v 3 Performing system checks... Unhandled exception in thread started by Traceback (most recent call last): File "/usr/local/lib/python2.7/dist-packages/django/utils/autoreload.py", line 228, in wrapper fn(*args, **kwargs) File "/usr/local/lib/python2.7/dist-packages/django/core/management/commands/runserver.py", line 125, in inner_run self.check(display_num_errors=True) File "/usr/local/lib/python2.7/dist-packages/django/core/management/base.py", line 405, in check raise SystemCheckError(msg) django.core.management.base.SystemCheckError: SystemCheckError: System check identified some issues: ERRORS: events.SystemLog.text: (fields.E121) 'max_length' must be a positive integer. events.SystemLog.type: (fields.E121) 'max_length' must be a positive integer. System check identified 2 issues (0 silenced). -
What are some ideas for a graduation project involving PHP or Python?
Please some ideas for a graduation project involving PHP or Python in general "Build Web Application"? -
Django POST Response throws exception if page is refreshed/reopened
I'm using Django in order to create a server which will download and track the progress of files. It has an input field for the url of the download link, and once I click on Download, it executes the following javascript code: index.html function startDownload() { var xhttp = new XMLHttpRequest(); xhttp.onreadystatechange = function() { if (this.readyState == 4 && this.status == 200) { completedFile = xhttp.responseText; document.getElementById(completedFile + "ProgBar").style.width = "100%"; document.getElementById(completedFile + "ProgBar").innerHTML = "Completed!"; setTimeout(delProgBar, 5000, completedFile); } }; xhttp.open("POST", "http://localhost:8000/download/start/", true); xhttp.setRequestHeader("X-CSRFToken", '{{ csrf_token }}'); xhttp.setRequestHeader("Content-type", "application/x-www-form-urlencoded"); var downloadLink = document.getElementById("downloadInput").value; var sendString = "url=" + downloadLink; var downloadArray = downloadLink.split('/'); var downloadName = downloadArray[downloadArray.length-1]; addProgBar(downloadName, "0"); xhttp.send(sendString); } Django views.py def start(request): aux = request.POST['url'] file_name = start_download(aux) print("###########") print(file_name) return HttpResponseRedirect(file_name) This works completely fine IF I don't reload the page after starting the download. The POST Request is only being logged on Django Command Prompt window after it is completed (readyState check). However, the page should show the download progress for other people that open the page after the download started. This however is throwing a big error on Django, with something like 4 Exceptions. I can post it later if necessary, but … -
Django python error
When i run server i receive error, i am using python 2.7 with Django. Traceback (most recent call last): File "manage.py", line 22, in <module> execute_from_command_line(sys.argv) File "F:\python\lib\site-packages\django\core\management\__init__.py", line 364, in execute_from_command_line utility.execute() File "F:\python\lib\site-packages\django\core\management\__init__.py", line 338, in execute django.setup() File "F:\python\lib\site-packages\django\__init__.py", line 27, in setup apps.populate(settings.INSTALLED_APPS) File "F:\python\lib\site-packages\django\apps\registry.py", line 85, in populate app_config = AppConfig.create(entry) File "F:\python\lib\site-packages\django\apps\config.py", line 94, in create module = import_module(entry) File "F:\python\lib\importlib\__init__.py", line 37, in import_module __import__(name) ImportError: No module named smart_selects -
Django: Compare two querysets
I have a model named Music and it has artist ManyToManyField. I want to validate that artist and name fields are unique_together. Django will not let to put ManyToManyField into the unique_together list of Meta class. Below is what I am doing and I is giving me an error <"Music: Hello> needs to have a value for field "id" before this many-to-many relationship can be used. class Music(models.Model): name = models.CharField(max_length=256) artist = models.ManyToManyField(Performer, related_name='all_songs') file = models.FileField(upload_to='music/') def save(self, *args, **kwargs): similar_musics = self.__class__.objects.filter(name=self.name) for music in similar_musics: artists = music.artist.all() diff = set(artists.all()).difference(set(self.artist.all())) if diff: raise ValidationError('This song seems to be already created!') super(Music, self).save(*args, **kwargs) What is the easiest way to validate so that artist and name fields unique together ? Additionally, I want to compress music file and stream my compressed music to browser and in the browser uncompress received parts and play. So, it may be similar to spotify but very simple version. What may be best way to do this task? Thank you in advance -
Retrofit: response 500, Internal Server Error
I am working on a project. The web team has implemented the API for signup and login. I will implement the Android part. So when I post a request to the server to sign up, using Postman, It is working. But When I try to signup in Android, It returns 500-Internal Server Error. I used Retrofit for sending request. Here is my code: SignUpActivity.java: public class SingUpActivity extends AppCompatActivity { @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_signup); final EditText email = (EditText) findViewById(R.id.input_email); final EditText username = (EditText) findViewById(R.id.input_name); final EditText password = (EditText) findViewById(R.id.input_password); final EditText gender = (EditText) findViewById(R.id.gender); final EditText location = (EditText) findViewById(R.id.location); Button btn_signUp = (Button) findViewById(R.id.btn_signup); btn_signUp.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { String email_str = email.getText().toString().trim(); String username_str = username.getText().toString().trim(); String password_str = password.getText().toString().trim(); if(!TextUtils.isEmpty(email_str) && !TextUtils.isEmpty(username_str) && !TextUtils.isEmpty(password_str)) { // Toast.makeText(getApplicationContext(), "username: " + username_str + " email: "+ email_str + " password: " + password_str, Toast.LENGTH_SHORT).show(); sendPost(username_str, email_str, password_str); } } }); } public void sendPost(String email, String username, String password){ Retrofit retrofit = ApiClient.getApiClient(); ApiInterface apiInterface = retrofit.create(ApiInterface.class); Call<JsonResponseSignUp> call = apiInterface.signUp(new SignUpBody(username, email, password)); call.enqueue(new Callback<JsonResponseSignUp>() { @Override public void onResponse(Call<JsonResponseSignUp> call, Response<JsonResponseSignUp> response) { if … -
Django view is not rendering a template when using ajax
So i'm trying to a render a template in view,when i click a button in another template,i make an ajax call to a method in view,but i'm not sure what is wrong in this,i'm not able to render another template,am i doing something wrong in this my view.py @csrf_exempt def checkLogin (request): if request.is_ajax(): param = request.POST.get('param', None) param1 = request.POST.get('param1', None) if (param=="admin" and param1=="admin"): Datenow = datetime.datetime.now().strftime('%H:%M:%S') return render(request,'sample/test.html',{'Datenow': Datenow}) else: Datenow = datetime.datetime.now().strftime('%H:%M:%S') return render(request,'sample/login.html',{'Datenow': Datenow}) return HttpResponseBadRequest() this is my ajax call in my template loginbt.onclick = function() { var uName = $('#username').val(); var pWord = $('#password').val(); $.ajax({type: 'POST', url: '/sample/checkLogin/', // some data url data: {param: uName, param1: pWord}, // some params success: function (response) { // callback if (response.result === 'OK') { if (response.data && typeof(response.data) === 'object') { window.alert("its working"); } } else { // handle an unsuccessful response } } }); } i get a 200OK result when i click the button in the template,but the template just doesn't change,any inputs would be helpful -
Django how to print data when using runserver
I have a dictionary data with how many players every user created: views.py def statistics(request): users = User.objects.all() data = dict() for user in users: players = Players.objects.filter(created__email=user.email).count() if players > 0: data[user.email] = players How can i print this dictionary in the console when i use runserver? I have seen django loggers but i didn't understand them fully. -
Django - formatting string representing a JSON into indented string and rendering it in a template
I have come across several posts addressing this question, but none of them helped. Here's what I want to do: I have a view like this: def test_view(request, request_id): params = '{"tz_name":"Asia/Yerevan","tz_gmt":"GMT+04:00"}' params = json.dumps(params, sort_keys=True, indent=4).encode('utf8') context = {'params':params} template = 'template.html' return render(request, template, context) ...and template.html": <div> {{params|safe}} </div> Basically, I want to render an HTML page that renders indented JSON object. But all my attempts fail. I always end up with HTML that renders my object not indented like this: and the corresponding HTML looks like this: <div id="json_container" style="font-size: 13px;"> "{\"tz_name\":\"Asia/Yerevan\",\"tz_gmt\":\"GMT+04:00\"}" </div> Any hints on this? -
TruncDate timezone parameter is not working in Django
Not able to change TImezone in Trunc functions. It always take timezone from settings.py import pytz ind = pytz.timezone('Asia/Calcutta') Query: queryset = Order.objects.annotate(date=TruncDate('created_at', tzinfo=ind)).values('date') While inspecting sql query by queryset.query SELECT DATE(CONVERT_TZ(`nm_order`.`created_at`, 'UTC', UTC)) AS `date` FROM `nm_order` Reference: Trunc in Django But for Extract, it's get working ORM: queryset = Order.objects.annotate(date=ExtractDay('created_at',tzinfo=ind)).values('date') Query: SELECT EXTRACT(DAY FROM CONVERT_TZ(`nm_order`.`created_at`, 'UTC', Asia/Calcutta)) AS `date` FROM `nm_order` Am I miss something in Trunc ? TimeZone Settings in my settings.py IME_ZONE = 'UTC' USE_I18N = True USE_L10N = True USE_TZ = True -
Connect to upstream client from nginx to gunicorn fails
I followed the steps in link and installed gunicorn and nginx "https://www.digitalocean.com/community/tutorials/how-to-set-up-django-with-postgres-nginx-and-gunicorn-on-centos-7" Now If I try from localhost / different computer in same network then it works fine. When I allocate a public IP address to the machine and try to access it I get the following error message, 2017/10/25 11:19:31 [crit] 12866#0: *1 connect() to unix:/tmp/controller.sock failed (2: No such file or directory) while connecting to upstream, client: 220.227.187.194, server: 127.17.3.124, request: "GET / HTTP/1.1", upstream: "http://unix:/tmp/controller.sock:/", host: "117.91.133.124" I tried the to disable selinux for network to socket with following command, As in the link "(13: Permission denied) while connecting to upstream:[nginx]" setsebool -P httpd_can_network_connect 1 All above steps are not solving my issue, even I tried to change to socket to /tmp directory in gunicon but its not working. The issue is only when trying to access from public IP not from private IP. All machines if I do curl local_ip_address it gives me nginx works fine and 200 OK