Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
How to control the size of the image a user upload
I built my first django app as a website where artists can expose their paintings. I did it as part of my final project for CS50 so i'm not a professional and my knowledge knows many boundary !!! Now i tested it with a few user and found out that many uploaded very large photos (up to 55mb) and when i render the main gallery, the display image for all the paintings is the image1 so now my gallery has about 100 paintings and each time someone browse it upload all those massives photos to use as thumbnail on the gallery and it drain my bandwidth (i don't want this to cost me 200$/month) My question : is there a way to control the size of the image people upload ??? a kind of if photosize > 10mb: resize to 10mb else do nothing ... PS - The photos are uploaded to a S3 bucket Thanks -
How to make parent/child relationship work nicely in Django admin?
I'm using Django 3.1... I have a model setup like: class Order(models.Model): supplier = models.CharField("supplier",...) ... class OrderLine(models.Model): quantity = ... product = ForeignKey(Product, related_name='product', ...) order = ForeignKey(Order, ...) My admin looks something like class OrderLineAdmin(TabularInline) list_display = ('product', 'quantity',...) class OrderAdmin(admin.ModelAdmin): list_display = ... inlines = [OrderLineAdmin] I have three problems with the result. I would like to only show products in the inline product choices which are from the parent order supplier. Ideally, I would allow first selecting the supplier in the parent order and then have the inlines generated from that. It is very slow as it seems to be repeating the same query for every choice field to get all the products, I would like to cache that across all order lines. It seems like a pretty standard problem and I'm sure there's a good approach to it just couldn't work it out from the docs or other posts. Appreciate any pointers... -
how to apply the style in html for folium map in a Django template
I am not professional in Django and html. I want to build a very simple website in Django to just show a map from folium: here is my code: views.py: def home_map(request): # define the Map m = folium.Map(width=800, height=500, location=Point0, zoom_start=6) # loading database .... .... # Location marker num_of_data = len(Imported_database.index) for i in range(0, num_of_data): popup_t = (......) popup = folium.Popup(popup_t, min_width=100, max_width=500) folium.Marker([lat_p, long_p], tooltip='Some Data appears by click', popup=popup, icon=folium.Icon(color='purple')).add_to(m) # Converting exporting data to html format m = m._repr_html_() # convert the map to html view, in the html file: {{map|safe}} Imported_database = Imported_database.to_html() context = {'map': m, 'data': Imported_database} return render(request, 'home.html', contex) home.html: <body> <h1>Folium</h1> <div> <center> {{ map| safe }} </center> </div> </body> It shows the map very well. But I want to bring the map to the center of the html page. ( I want to do other styles also) I tried many tags in html but didn't work! -
Django Annotation + Distinct field
I have three models defined like this: class Match(models.Model): id = models.IntegerField() class Market(models.Model): match = models.ForeignKey(Match,on_delete=models.CASCADE) class Issue(models.Model): market = models.ForeignKey(Market,related_name='issues',on_delete=models.CASCADE) volume = models.PositiveIntegerField() It is structured like this: Every Match has several Market, and every Market has several Issue. What I want to do is: For each Match, select the Market that has the largest sum of Issue.volume It may sound quite easy, but I can't figure it out... What I've done so far: Without the DISTINCT Match condition Market.objects.annotate(total_volume=Sum('issues__volume')).order_by("-total_volume") This works as expected, but a single Match occurs multiple time in my QuerySet. First try with the DISTINCT Match condition Then I'm trying to add a DISTINCT(Match). As I'm using Postgresql, I can use distinct('match_id'): Market.objects.annotate(total_volume=Sum('issues__volume')).order_by("match","-total_volume").distinct("match_id") But it raises the following error: NotImplementedError: annotate() + distinct(fields) is not implemented. Second try with the DISTINCT Match condition I achieved to get what I expected using: Market.objects.values('match_id').annotate(total_volume=Sum('issues__volume')).order_by("-total_volume") However, I want to access to every Issue linked to a specific Market, which is impossible here because of the use of values(). Do you have any ideas on how to make it work with as few requests as possible? Thank you for your help! -
what is the correct way of defining django-extensions
I need to use Django-organizations and it seems I need to install Django-extensions. I included both to the list of installed apps but when I tried to run the dev server I get the following traceback message: Watching for file changes with StatReloader Exception in thread django-main-thread: Traceback (most recent call last): File "C:\Users\stephen\AppData\Local\Programs\Python\Python38-32\lib\site-packages\organizations\fields.py", line 81, in <module> BaseSlugField = getattr(import_module(module), klass) File "C:\Users\stephen\AppData\Local\Programs\Python\Python38-32\lib\importlib\__init__.py", line 127, in import_module return _bootstrap._gcd_import(name[level:], package, level) File "<frozen importlib._bootstrap>", line 1014, in _gcd_import File "<frozen importlib._bootstrap>", line 991, in _find_and_load File "<frozen importlib._bootstrap>", line 961, in _find_and_load_unlocked File "<frozen importlib._bootstrap>", line 219, in _call_with_frames_removed File "<frozen importlib._bootstrap>", line 1014, in _gcd_import File "<frozen importlib._bootstrap>", line 991, in _find_and_load File "<frozen importlib._bootstrap>", line 961, in _find_and_load_unlocked File "<frozen importlib._bootstrap>", line 219, in _call_with_frames_removed File "<frozen importlib._bootstrap>", line 1014, in _gcd_import File "<frozen importlib._bootstrap>", line 991, in _find_and_load File "<frozen importlib._bootstrap>", line 973, in _find_and_load_unlocked ModuleNotFoundError: No module named 'django-extensions' During handling of the above exception, another exception occurred: Traceback (most recent call last): File "C:\Users\stephen\AppData\Local\Programs\Python\Python38-32\lib\threading.py", line 932, in _bootstrap_inner self.run() File "C:\Users\stephen\AppData\Local\Programs\Python\Python38-32\lib\threading.py", line 870, in run self._target(*self._args, **self._kwargs) File "C:\Users\stephen\AppData\Local\Programs\Python\Python38-32\lib\site-packages\django\utils\autoreload.py", line 53, in wrapper fn(*args, **kwargs) File "C:\Users\stephen\AppData\Local\Programs\Python\Python38-32\lib\site-packages\django\core\management\commands\runserver.py", line 110, in inner_run autoreload.raise_last_exception() File "C:\Users\stephen\AppData\Local\Programs\Python\Python38-32\lib\site-packages\django\utils\autoreload.py", … -
Filter django view with or condition
If I want to limit an object in Django within my view to show a filtered list based on if a user is added or if the user is an author, how can I create that condition? I attempted to filter with an or statement but this just displayed duplicates. return Group.objects.filter(author=user or users__in=[user]) What would be the proper way to format or create this logic? -
can't set max height with respect to screen heigth of a div with bootstrap
i'm using bootstrap with Django and i've been trying to set the max height of a div = 75% of the screen height because it has a large picture in it. so i'm trying to resize the parent div of the image to 75% of the device screen but this doesn't seem to work. i've used class="mh-75" and it doesn't work. i went further to load static css file to style this with max-height: 75%; and it still doesn't work. here's the code: {% extends 'testapp/base.html' %} {% block content %} {% for image in Image %} <div class= "container-fluid pd-2 pt-2 mh-75"> <div class="bg-dark text-white rounded p-1"> <img class="img-responsive img-wid img-fluid mx-auto d-block" src="{{ image.url }}" alt="{{ image.name }}"> <div class="pt-2 text-center"><p>Source: {{ image.source }}</p></div> </div> </div> {% endfor %} {% endblock content %} i don't think this would help but img-wid style: .img-wid{ max-width: 99.999%; } -
problem: facing problem running this code
showing 'keyword error' 'search' This is a python project that takes the item you want to search on Flipkart as input generates and prints the URL of that product This file has the headings- Product_Name, Pricing, Ratings and Link with the entities of Flipkart's first page below it. when run this code the interpreter shows the missing keyword argument `BASE_FLIPKART_URL = 'https://www.flipkart.com/search?q={search}'` # Create your views here. `def home(request):` ` return render(request, 'base.html')` `def new_search(request):`**strong text** search = request.POST.get('search') Search.objects.create(search=search) final_url = BASE_FLIPKART_URL.format(quote_plus(search)) page = request.get(final_url) soup= bs(page.text,"html.parser") product =[] amount =[] point =[] allData = soup.find_all("div",{'class' : "_2kHMtA"}) ``` final = [] for post in allData: name = post.find('div', {'class': "_4rR01T"}) product = name.text # print(product) price = post.find('div', {'class': "_25b18c"}) amount = price.find('div', {'class': "_30jeq3 _1_WHN1"}).text # print(amount) rate = post.find('div', {'class': "_3LWZlK"}) point =rate.text # print(point) final.append((product,amount,point)) stuff_for_frontend = { 'search': search, 'final' : final, } return render(request,'search/new_search.html',stuff_for_frontend) -
Create a csv file after the first time user logs in
Is there any way of checking when a user logs in for the first time and then create a file? Pseudocode: if first_time_login == True: create_some_file -
Django: Unable to set background-image to a button in template
I am trying to set a background-image to a button but its not displayed. In the inpect element when I hover over the background url it displays the image. Meaning the url is correct. <button style="background-image: url('{{ mobile_brand.image.url }}'); !important; background-repeat: no-repeat;" name="brand" id="brand" class="btn btn-outline-info m-1" type="submit" value={{mobile_brand}}></button> I have tried different variations like using input instead of button. Putting static in the url. Removing comas, background-repeat. And tried giving the full path. Nothing works. Thankyou for any help. -
How can I display 2 models In 1 view?
So I have a Django app where I want the user to be able to input a question and then like 3 choices for another user to guess Models.py from django.conf import settings from django.contrib.auth import get_user_model from django.db import models from django.urls import reverse class Question(models.Model): question = models.CharField(max_length=255) body = models.CharField(max_length=200) author = models.ForeignKey( get_user_model(), on_delete=models.CASCADE, ) def __str__(self): return self.question def check_answer(self, choice): return self.choice_set.filter(id=choice.id, is_answer=True).exists() def get_answers(self): return self.choice_set.filter(is_answer=True) def get_absolute_url(self): return reverse('article_detail', args=[str(self.id)]) class Choice(models.Model): question = models.ForeignKey(Question, related_name='choices', on_delete=models.CASCADE) choice_text = models.CharField(max_length=200) is_answer = models.BooleanField(default=False) def __str__(self): return self.choice_text def get_absolute_url(self): return reverse('article_list') and then my views.py from django.contrib.auth.mixins import ( LoginRequiredMixin, UserPassesTestMixin ) from django.views.generic import ListView, DetailView from django.views.generic.edit import UpdateView, DeleteView, CreateView from django.urls import reverse_lazy from .models import Question from .forms import QuestionAddForm, EditQuestionForm, ChoiceAddForm class QuestionListView(LoginRequiredMixin, ListView): model = Question template_name = 'article_list.html' class QuestionDetailView(LoginRequiredMixin, DetailView): model = Question template_name = 'article_detail.html' class QuestionUpdateView(LoginRequiredMixin, UserPassesTestMixin, UpdateView): model = Question fields = ('question', 'body') template_name = 'article_edit.html' def test_func(self): obj = self.get_object() return obj.author == self.request.user class QuestionDeleteView(LoginRequiredMixin, UserPassesTestMixin, DeleteView): model = Question template_name = 'article_delete.html' success_url = reverse_lazy('article_list') def test_func(self): obj = self.get_object() return obj.author == self.request.user class QuestionCreateView(LoginRequiredMixin, … -
Disqus comment section in Django blog not showing but only in 1 post
I can create new posts and Disqus comments will appear as well as in my old posts But for some reason not in this one. They all use the same code, It doesn't have sense to me. Didn't find any info on this issue. https://gsnchez.com/blog/article/El-var-como-medida-del-riesgo-de-mercado. This is the url, u can check it online. <div id="disqus_thread"></div> <script> /** * RECOMMENDED CONFIGURATION VARIABLES: EDIT AND UNCOMMENT THE SECTION BELOW TO INSERT DYNAMIC VALUES FROM YOUR PLATFORM OR CMS. * LEARN WHY DEFINING THESE VARIABLES IS IMPORTANT: https://disqus.com/admin/universalcode/#configuration-variables*/ var disqus_config = function () { this.page.url = gsnchez.com{{ request.get_full_path }}; // Replace PAGE_URL with your page's canonical URL variable this.page.identifier = {{post.id}}; // Replace PAGE_IDENTIFIER with your page's unique identifier variable }; (function() { // DON'T EDIT BELOW THIS LINE var d = document, s = d.createElement('script'); s.src = 'https://gsnchez.disqus.com/embed.js'; s.setAttribute('data-timestamp', +new Date()); (d.head || d.body).appendChild(s); })(); </script> -
Django query merge
I have two model classes on the "models.py" file. Signup & Notes from django.contrib.auth.models import User from django.db import models # Create your models here. class Signup(models.Model): user = models.ForeignKey(User, on_delete=models.CASCADE) contact = models.CharField(max_length=10, null=True) branch = models.CharField(max_length=30) campus = models.CharField(max_length=30) role = models.CharField(max_length=15) def __str__(self): return self.user.username class Notes(models.Model): user = models.ForeignKey(User, on_delete=models.CASCADE) uploadingdate = models.CharField(max_length=30) branch = models.CharField(max_length=30) subject = models.CharField(max_length=30) topic = models.CharField(max_length=200) notesfile = models.FileField(null=True) filetype = models.CharField(max_length=30) description = models.CharField(max_length=300, null=True) status = models.CharField(max_length=15) def __str__(self): return self.user.username + " " + self.status on my function i uses notes = Notes.objects.all() & users = User.objects.all() to get them. here is the funtion def indexnotes(request): notes = Notes.objects.all() users = User.objects.all() d = {'notes' : notes,'users' : users} return render(request,'indexnotes.html',d) I am using a for loop to show the values on a datatable. The code is like this <tbody > {% for i in notes %} <tr> <td>{{forloop.counter}}</td> <td>{{i.user.first_name}} {{i.user.last_name}}</td> <td>{{i.uploadingdate}}</td> <td>{{i.campus}}</td> <td>{{i.subject}}</td> <td><a href="{{i.notesfile.url}}" class="btn btn-success" download>Download</a></td> <td>{{i.filetype}}</td> <td>{{i.description}}</td> <td>{{i.status}}</td> <td><a href="{% url 'assign_status' i.id %}" class="btn btn-success" >Assign&nbsp;Status</a></td> <td><a href="{% url 'delete_notes' i.id %}" class="btn btn-danger" onclick="return confirm('Are you sure?')">Delete</a></td> </tr> {% endfor %} </tbody> Now the problem is some value of the table … -
Can I use pytesseract in a WebApp?
I am developing a WebApp with Django that allows users to upload an image, and "read" the text present in the image.I am using pytesseract to do this task. Everything worked well on my local machine, however when deploying this app on Linode (Ubuntu 18.04 LTS server) I keep getting an error. I am curious if this is due to my code, or due to the nature of linode/pytesseract. I have read online that some hosting companies have anti-virus software that could hinder the use of such packages. Does anyone have advice or any insight on this topic? I am fairly new to web dev. so any advice will help... -
Clone an object from a model to another
I need to automatically generate a new element into copyModel when an element is created inside the mainModel. This new element into copyModel must be the copy of the relative element from mainModel. This is only an excercize. I've developed my two models: class mainModel(models.Model): ''' main table ''' text = models.CharField(max_length=250) class copyModel(models.Model): ''' completely copied datas from mainModel ''' main = models.ForeignKey(mainModel, on_delete=models.CASCADE) text_copy = models.CharField(max_length=250) def save(self, *args, **kwargs): self.text_copy = mainModel.text_copy super(copyModel, self).save(*args, **kwargs) I'm using a simple admin site to make my tests: from django.contrib import admin from .models import copyModel, mainModel admin.site.register(copyModel) admin.site.register(mainModel) When I create a new object in mainModel it isn't copied into copyModel. Probably I've misundestanding the use of save method, but what is the right way to do my aim? -
Custom authentication middleware not working when objects is not overridden in model definition
Following the question I asked here I have a custom authentication middleware that does not work anymore if I do not override the objects. The models.py looks like this: class Person(AbstractUser): company_id = models.IntegerField(null=True, blank=True, default=None) role = models.CharField(max_length=255) def __str__(self): return "{last}, {first} ({id})".format( last=self.last_name, first=self.first_name, id=self.id ) If I leave the code like this, the authentication never takes place (and I end up in an infinite loop of redirections). Now, if I update my model by adding: objects = models.Manager() All of the sudden, the authentication takes place and it is (at least this part) is working fine. I know that the custom authentication middleware is updating the database when the user logs in. However, I can't figure out why I should override objects -
Stop AWS CloudFront stripping custom domain when re-directing
I have CloudFront caching a Django Lambda (Zappa) deployment. Everything is working fine except that when I visit my custom domain such as www.example.com it is re-directing to the Lambda execution URL like https://1234xb7gmc.execute-api.eu-west-2.amazonaws.com/ rather than keeping the custom domain. I think the flow is as follows: Custom Domain > CloudFront Domain > Lambda Domain I just want it so that at the end, the user is still using the custom domain and not the Lambda one (even though behind the scenes they're being invoked). Is there a name for this behavior? -
socket.gaierror: [Errno 11001] getaddrinfo failed in django
I am trying to build an ecommerce store with python and django. I am currently building a pay_on_delivery option, and for that, I am sending an email to myself from the email of the user. Here is my OrderForm: class OrderForm(forms.Form): name = forms.CharField(max_length=30) email = forms.EmailField() city = forms.CharField(max_length=100) address = forms.CharField(widget=forms.Textarea()) zip_code = forms.CharField(min_length=6,max_length=6) product = forms.CharField(max_length=200,widget=forms.TextInput(attrs={'placeholder':'Copy and paste the exact same name of the product you want to purchase'})) phone = forms.CharField(min_length=10,max_length=10) def save(self): cleaned_data = self.cleaned_data send_mail( "Product {cleaned_data['product']} ordered by {cleaned_data['name']}", "A product from our bakery has been ordered. Address: {cleaned_data['address']}. Zip code: {cleaned_data['zip']}. Phone: {cleaned_data['phone']}", cleaned_data["email"], ["rjain1807@gmail.com"], fail_silently=False, ) And my view function that handles the form submission: def buy(request,id): product = Product.objects.get(id=id) form = OrderForm() if request.method == 'POST': form = OrderForm(data=request.POST) if form.is_valid(): form.save() return HttpResponse("Your order has been successfully placed!!") context = { 'form':form, 'product':product, } return render(request, 'buy_page.html',context) Now, when I try to place an order, I get this traceback error upon the form submission: Internal Server Error: /products/1/buy/ Traceback (most recent call last): File "C:\Users\Dell\Desktop\Django\apnibakery\venv\lib\site-packages\django\core\handlers\exception.py", line 47, in inner response = get_response(request) File "C:\Users\Dell\Desktop\Django\apnibakery\venv\lib\site-packages\django\core\handlers\base.py", line 179, in _get_response response = wrapped_callback(request, *callback_args, **callback_kwargs) File "C:\Users\Dell\Desktop\Django\apnibakery\bakery\apnibakeryy\views.py", line 33, in buy … -
I got an error like this when pushing my django website to heroku
ModuleNotFoundError: No module named 'django_filters' i was working on my first e commerce website on django, when i almost finish and want to push my file to heroku I got this error, i was tring so many times and i cant find whats wrong about my codes, can someone find what wrong in my file requerements.txt: asgiref==3.3.1 astroid==2.4.2 autopep8==1.5.4 colorama==0.4.4 Django==3.1.4 django-bootstrap-form==3.4 django-crispy-forms==1.10.0 django-filter==2.4.0 django-shortcuts==1.6 django-tastypie==0.14.3 djangorestframework==3.12.2 gunicorn==20.0.4 isort==5.6.4 lazy-object-proxy==1.4.3 mccabe==0.6.1 Pillow==8.0.1 pycodestyle==2.6.0 pylint==2.6.0 python-dateutil==2.8.1 python-mimeparse==1.6.0 pytz==2020.4 six==1.15.0 sqlparse==0.4.1 toml==0.10.2 whitenoise==5.2.0 wrapt==1.12.1 this is my error: $ git push heroku master Enumerating objects: 158, done. Counting objects: 100% (158/158), done. Delta compression using up to 4 threads Compressing objects: 100% (151/151), done. Writing objects: 100% (158/158), 6.06 MiB | 211.00 KiB/s, done. Total 158 (delta 15), reused 0 (delta 0), pack-reused 0 remote: Compressing source files... done. remote: Building source: remote: remote: -----> Python app detected remote: -----> Installing python-3.9.0 remote: -----> Installing pip 9.0.2, setuptools 47.1.1 and wheel 0.34.2 remote: -----> Installing dependencies with Pipenv 2018.5.18… remote: Installing dependencies from Pipfile.lock (68efdd)… remote: -----> Installing SQLite3 remote: -----> $ python manage.py collectstatic --noinput remote: Traceback (most recent call last): remote: File "/tmp/build_5aa9deac/manage.py", line 22, in <module> remote: main() remote: … -
Overriding a queryset for the Django Admin interface
I'm trying to limit the items available to choose from a dropdown list in the admin panel for a given model. At the moment, I overrode the save method to throw a valueerror if conditions are not met, but this is an ugly solution IMO. At the time I wrote that, I was not aware of proxy models, which seem like the solution, at least according to this answer. I have a model Entry, so I created a proxy model like so: class ApprovedEntries(Case): class Meta: proxy = True verbose_name = 'Entry' verbose_name_plural = 'Entries' def get_queryset(self, request): qs = Entry.objects.filter(assigned_contestant__approved='True', assigned_contestant__active='True') return qs Then in my admin.py I replaced the existing entry to register the Entry model with: admin.site.register(ApprovedEntries) However, this seems to have no effect. Only the unfiltered list of Entry objects is returned. Is something additional needed to 'activate' a proxy model? Is there a better solution to my problem? -
Content Object of model returning None when trying to access Generic Foreign key attribute
I have a few related models (truncated models for relevancy): class Product(models.Model): style = models.CharField(max_length=20, unique=True, primary_key=True, null=False, blank=False, verbose_name="Style ID") class Shipment(models.Model): shipment_id = models.CharField(max_length=9, blank=True, verbose_name="Shipment ID") status = models.CharField(max_length=3, verbose_name="Status") class InventoryItem(models.Model): unique_sku = models.SlugField(blank=True, verbose_name="Inventory System SKU") Shipment = models.ForeignKey(CastleShipment, blank=True, null=True, on_delete=models.SET_NULL) # GenericForeignKey fields for SKU models content_type = models.ForeignKey(ContentType, on_delete=models.PROTECT) object_id = models.CharField(max_length=50) content_object = GenericForeignKey('content_type', 'object_id') class CSKU(models.Model): ShoeProduct = models.ForeignKey(Product, verbose_name="Style", on_delete=models.CASCADE) sku = models.CharField(max_length=50, verbose_name="SKU") upc = models.CharField(max_length=25, null=True, blank=True, verbose_name="UPC") def get_style(self): return "{0}".format(self.Product.style) When I try: inv = InventoryItem.objects.first() inv.content_object.get_style It returns error: 'NoneType' object has no attribute 'get_style_id' And inv.content_object returns nothing, however inv.content_type returns <ContentType: oms | csku> and inv.object_id returns '603' (both correct.) I'm able to access other attributes of generic foreign key relationships with .content_object.attribute so is there any reason why I wouldn't be able to here? -
Django-tables2 specifying verbose_name for column header has no effect
This seems like a very simple issue with no apparent cause. I'm trying to set a verbose name in a Django Tables2 table to change the column header. The documentation indicates this is the correct way to do this. My table is simple, like so: class ContestantsTable(tables.Table): id = tables.Column(verbose_name='Contestant ID') full_name = tables.Column(verbose_name='Name') class Meta: model = Contestant template_name = "django_tables2/bootstrap.html" fields = ("id", "full_name") The verbose name setting is completely ignored. If I set verbose_name on the field in the model it works, but I want to do this at the table level and not on the model (The name I want for the column won't be used elsewhere). I have another table where I am trying to set default="Unassigned which also does not reflect in the table for fields where there is no entry. I'm not sure why such a simple thing is failing. -
Why "Error: That port is already in use."
Yes obviously I run the command: killall -9 python But not working again same error Error: That port is already in use. Well, I can also use other port like 8001 instead of 8000 and BOOM!, but please explain why this happens ? -
Django query on datetime fields is correct on local postgres but returns incorrect result when deployed to heroku
I'm using django and I have this model from django.db import models class ViewTime(models.Model): start = models.DateTimeField() end = models.DateTimeField() I then query the sum of all the view times for each day with the following query. from .models import ViewTime from django.db.models import Sum, F ViewTime.objects.all() .values("start__date") .annotate(count=Sum(F("end") - F("start"))) .order_by("start__date") On my local postgres server is returns the expected query set in the format [{start__date, count}]. However I deployed to heroku and the query returns only one item in the query set with count being a time vector of 0 and date being the most recent object in the database. My files are all up to date on heroku. Other queries are performed succesfully. I am also running the same version of python as my deployment on heroku. I have not changed my timezone settings leaving them as LANGUAGE_CODE = "en-us" TIME_ZONE = "UTC" USE_I18N = True USE_L10N = True USE_TZ = True Please let me know if there is any other information that would be useful. -
Fatal Python error: init_fs_encoding: failed to get the Python codec of the filesystem encoding, when trying to start uwsgi
I am trying to start my uwsgi server, but after I added plugin python3 option I get this error every time: !!! Python Home is not a directory: /home/env3/educ !!! Set PythonHome to /home/env3/educ Python path configuration: PYTHONHOME = '/home/env3/educ' PYTHONPATH = (not set) program name = '/home/env3/educ/bin/python' isolated = 0 environment = 1 user site = 1 import site = 1 sys._base_executable = '/home/env3/educ/bin/python' sys.base_prefix = '/home/env3/educ' sys.base_exec_prefix = '/home/env3/educ' sys.executable = '/home/env3/educ/bin/python' sys.prefix = '/home/env3/educ' sys.exec_prefix = '/home/env3/educ' sys.path = [ '/home/env3/educ/lib/python38.zip', '/home/env3/educ/lib/python3.8', '/home/env3/educ/lib/python3.8/lib-dynload', ] Fatal Python error: init_fs_encoding: failed to get the Python codec of the filesystem encoding Python runtime state: core initialized ModuleNotFoundError: No module named 'encodings' Current thread 0x00007efe89db8780 (most recent call first): <no Python frame> Here is my uwsgi.ini file: [uwsgi] base = /home/env3/educ projectname = educ plugins = python3 master = true virtualenv = /home/env3/%(projectname) pythonpath = %(base) env = DJANGO_SETTINGS_MODULE=%(projectname).settings.pro module = %(projectname).wsgi:application socket = /tmp/%(projectname).sock chmod-socket = 666 I use Python 3.8.5 I am trying to use Django + uWSGI + nginx + Postgresql If you need more details I will give it Thank you