Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Getting "Requested runtime is not available for this stack (heroku-20)." error with correct versions of Python
The main issue that I could not find anywhere else is that the bracket contains all the other lines of runtime.txt. which makes me believe something else is wrong but I can't find any solution online. Buildlog attached for reference. -----> Building on the Heroku-20 stack -----> Determining which buildpack to use for this app -----> Python app detected -----> Using Python version specified in runtime.txt ! Requested runtime (asgiref==3.4.1 colorama==0.4.4 comtypes==1.1.10 cycler==0.10.0 dj-database-url==0.5.0 Django==3.2.6 docx2pdf==0.1.7 gunicorn==20.1.0 joblib==1.0.1 kiwisolver==1.3.2 lxml==4.6.3 matplotlib==3.4.3 mysql-connector-python==8.0.26 numpy==1.21.2 Pillow==8.3.2 psycopg2==2.9.1 pyparsing==2.4.7 python-dateutil==2.8.2 python-docx==0.8.11 pytz==2021.1 pywin32==227 scikit-learn==0.24.2 scipy==1.7.1 six==1.16.0 sklearn==0.0 sqlparse==0.4.1 threadpoolctl==2.2.0 tqdm==4.62.3 whitenoise==5.3.0 python-3.9.7) is not available for this stack (heroku-20). ! Aborting. More info: https://devcenter.heroku.com/articles/python-support ! Push rejected, failed to compile Python app. ! Push failed -
Are there any difference between these two?
I am little lost, from my understanding there should be no difference between these two code lines. As I am creating tuple list in both cases. But I feel like I am wrong, could you point where I am wrong and why. class Meta: ordering = tuple(('-pub_date',)) And class Meta: ordering = ('-pub_date') -
Convert raw query to django orm
I written this query in MySQL and I'm confused of conversion of this query to django orm SELECT * FROM student.student_data where created_by in (select user_id from user_profile where user_location in(7, 8)); -
I've installed packages in python but its still showing module error
I've done few python projects in the past and the modules have worked fine.From few days im getting Error that "no module found" even though ive installed the packages I reinstalled python updated pip tried in Virtual env but I can't find a solution -
While installing Open-Edx we are facing ValueError: Unable to configure handler 'logfile'
I understand it is because python is not able to find the log file so that it logs the exceptions. My question is why it is not able to configure. is it because of improper installation of python or other programs or any other possible reason. -
Problem with performing a groupby count using an annotated field
Context I have a table/model called Article. Within this model, I have several fields such as expiry date, visibility, and status. These fields determine if the Article should be displayed or not. Essentially, the desired logic is like so: display = True if status == 'Private'; display = False if visibility == False; display = False ... For the sake of simplicity, in this post, I'm just going to be using one field: status. The status field is a CharField with choices being 'Private' or 'Public'. In order to work out the display logic, I use annotation. This is relatively simple: all_articles = Article.objects.annotate( display=Case(When(status='Private', then=Value(False)), default=Value(True), output_field=models.BooleanField()) ) displayed_articles = all_articles.filter(display=True) notdisplayed_articles = all_articles.filter(display=False) Goal With this setup, I would like to use Django ORM to perform a count with group by to determine how many articles are being displayed, and how many are not. The outcome would like like this in SQL tabular format: display count True 500 False 2000 Problem This is the natural way to achieve my goal: queryset = Article.objects.annotate( display=Case( When(status='Private', then=Value(False)), default=Value(True), output_field=models.BooleanField() ) ).values('display').annotate(count=Count('id')).order_by() print(queryset) Expectation I'm expecting something like this: <QuerySet [{'display': True, 'count': 500}, {'display': False, 'count': 2000}]> Error However, … -
Canvas: Remove scrollbar functionality and grey border box/outline?
I'm working on a project in Django whereby I have one canvas element superimposed over another with functionality that allows me to mouseover the top canvas to reveal an image loaded into the canvas underneath it. The functionality works great however it seems to be wreaking havoc in other ways, namely: The window width and height are larger than the canvases causing unnecessary scrolling. I want to get rid of this. There is a light grey border around my canvas elements and I can't get rid of it. Tried setting outline and border to none but no dice. I'm also having issues centering the canvases in the window. My gut is telling me these problems have something to do with the fact that my canvas stack is set to absolute position while its parent div is set to relative (this is the functionality that allows me to stack canvases) but this is just a hunch. I've looked at a variety of other similar SO questions, but none of their solutions worked for my code. Any help would be greatly appreciated. Thanks. window.onload = function() { //Create Bottom canvas & context var canvas = document.getElementById('canvas'); var ctxB = canvas.getContext('2d'); //Create Top … -
How to use token generated by knox in api view function
I am using knox and not rest_framework.authtoken. I am also able to generate tokens right now but I am having issue in using it. According to the documentation (https://www.django-rest-framework.org/api-guide/authentication/), an api function view requires @authentication_classes([SessionAuthentication, BasicAuthentication]) @permission_classes([IsAuthenticated]) I replace Session and Basic to TokenAuthentication but I am getting the error of NameError: name 'authentication_classes' is not defined In my views according to the documentation, i have imported the following: from rest_framework.authentication import TokenAuthentication from rest_framework.permissions import IsAuthenticated -
Django traceback / cannot import name 'TypeVarTuple' from 'typing_extensions'
Hi all I'm new to django & python. I keep getting this traceback while using django when I tried runserver or migrate. ImportError: cannot import name 'TypeVarTuple' from 'typing_extensions' I already tried 1/ upgrading django with pip 2/ upgrading typing extensions with pip and both didn't work for me... Does anyone faced the same problem and solved? Thank you! -
Django Python ICalendar
I want to upload a file with the extension ICS, after uploading that file only keep the events with code "10059707" and output the download file. This is my code : views.py def calendar_list(request): calendars = CalendarModel.objects.all() return render(request, 'upload_app/calendar_list.html',{ "calendars" : calendars }) def upload_calendar(request): if request.method == "POST": form = CalendarForm(request.POST, request.FILES) g = request.FILES['calendarfile'] gcal = Calendar.from_ical(g.read()) cal2 = Calendar() for component in gcal.walk(): if component.name == "VEVENT": ATTENDEE = component.get('ATTENDEE') SUMMARY = component.get('SUMMARY') if ATTENDEE is not None and '10059707' in ATTENDEE: print("1:{}\n 2:{}\n".format(ATTENDEE,SUMMARY)) event2 = Event() event2.add('attendee',vCalAddress(ATTENDEE)) event2.add('summary', "作業予定あり") cal2.add_component(event2) ***** What can I do in here?******** cal2.to_ical() if form.is_valid(): form.save() return redirect('calendar_list') else: form = CalendarForm() return render(request, 'upload_app/upload_calendar.html',{ "form" :form }) ..... I don't know how I can handle that request in Django to parse ics file. models.py # Create your models here. class CalendarModel(models.Model): calendartitle = models.CharField("ファイル名",max_length=100) calendarfile = models.FileField("ファイル追加",upload_to="icsfile") cover = models.ImageField("ファイルイメージ",upload_to="cover_img", null=True,blank=True) ... -
how can we store Django forms user data to database
I am a newbie to MVC architecture. I just wanted to know, how can we store Django forms data into Database(admin) as we do with models in Django? -
How to display cleaned email data in django import-export
I have this widget: class EmailWidget(CharWidget): def clean(self, value, row=None, *args, **kwargs): if value: email_field = EmailField() if email_field.clean(value): return value return None which I use here: some_email= fields.Field(attribute='some_email', widget=EmailWidget(), column_name='some_email') cleaning is fine but it does not specify the data to be cleaned on the table view in errors. [![enter image description here][1]][1] what I was expecting was something like this: [![enter image description here][2]][2] I only need to specify it and display it among the list of errors in the second row and second column. [1]: https://i.stack.imgur.com/NHc2E.png [2]: https://i.stack.imgur.com/fMar4.png -
I want to scape play store apps categories and subcategories in my django app. When use give a input in app and display on website
I want to scape play store apps categories and subcategories for specific app name that user gives as input. And then store that app categories and subcategories to database as well as display to website instantly. Is their is any way to do this? -
How to download datatable with filtering applied
I'm using django, and using the xlsxwriter module to download data to excel. Currently, the code is running as below, but I am using the 'Datatable' plugin, so the filter function works. What do I need to modify to download the data after applying the filter? The method I thought of is to download only the data currently being output in developer mode. Is it possible? def download_excel(request, school_id): school= get_object_or_404(School, pk=school_id) row += 1 col = 0 students = school.student_set.filter(is_deleted=False).order_by('no') for student in students: worksheet.write(row, col, student.status) col += 1 worksheet.write(row, col, student.no) col += 1 worksheet.write(row, col, student.phone_number) col += 1 ... -
How do I create an optional dropdown in django using mmpt and bootstrap
I'm struggling getting my dropdowns to work for my categories. I also need to make it optional. For example, if there are no subcategories, make it a navlink instead of a dropdown (not all categories will have subcategories/children). Incrementally I was trying to just do them all dropdowns. There are 3 total categories, but 2 are subcategories of a parent category. For some reason, the parent category is showing 3 times on my navbar with no children coming off the dropdown. Here's my code: {% recursetree categories %} <li class="nav-item dropdown"> <a class="nav-link dropdown-toggle" href="node.get_absolute_url" id="navbarDropdown" role="button" data-bs-toggle="dropdown" aria-expanded="false"> {{ node.name|title }} </a> <ul class="dropdown-menu" aria-labelledby="navbarDropdown"> {% if not node.is_leaf_node %} <ul class="children"> <li><a class="dropdown-item" href="#">{{ children }}</a></li> </ul> {% endif %} </ul> </li> {% endrecursetree %} This was borrowed from the documentation for this example (changing variable to match my project): {% recursetree categories %} <li> {{ node.name }} {% if not node.is_leaf_node %} <ul class="children"> {{ children }} </ul> {% endif %} </li> {% endrecursetree %} I know my database is set up correctly because when displaying this above the navbar, it shows the correct relation (1 parent, 2 children). It's just displaying it in navbar isn't showing … -
Why is Django unable to run properly?
I am recently working on Django following the description from the book Python Crash Course. I followed every step and tried to restart from the beginning a couple of times, still unable to solve the problem(Even reinstalled MacOS to get a cleaner desktop). Here is my code: class Topic(models.Model): '''A topic the user is learning about''' text = models.CharField(max_length=200) date_added = models.DateTimeField(auto_now_add=True) def __str__(self): '''Return a string represent model''' return text The tracebacks are below: Traceback (most recent call last): File "/Users/bryan/Desktop/python/learning_log/learning_logs/models.py", line 3, in <module> class Topic(models.Model): File "/Library/Frameworks/Python.framework/Versions/3.10/lib/python3.10/site-packages/django/db/models/base.py", line 108, in __new__ app_config = apps.get_containing_app_config(module) File "/Library/Frameworks/Python.framework/Versions/3.10/lib/python3.10/site-packages/django/apps/registry.py", line 253, in get_containing_app_config self.check_apps_ready() File "/Library/Frameworks/Python.framework/Versions/3.10/lib/python3.10/site-packages/django/apps/registry.py", line 135, in check_apps_ready settings.INSTALLED_APPS File "/Library/Frameworks/Python.framework/Versions/3.10/lib/python3.10/site-packages/django/conf/__init__.py", line 82, in __getattr__ self._setup(name) File "/Library/Frameworks/Python.framework/Versions/3.10/lib/python3.10/site-packages/django/conf/__init__.py", line 63, in _setup raise ImproperlyConfigured( django.core.exceptions.ImproperlyConfigured: Requested setting INSTALLED_APPS, but settings are not configured. You must either define the environment variable DJANGO_SETTINGS_MODULE or call settings.configure() before accessing settings. [Finished in 304ms with exit code 1] [cmd: ['python3', '-u', '/Users/bryan/Desktop/python/learning_log/learning_logs/models.py']] [dir: /Users/bryan/Desktop/python/learning_log/learning_logs] [path: /Library/Frameworks/Python.framework/Versions/3.10/bin:/usr/local/bin:/usr/bin:/bin:/usr/sbin:/sbin] -
No 'backend' or 'backend.custom_azure' modules
Running "python manage.py collectstatic" for a Django app I hope to host on Heroku results in this error: Traceback (most recent call last): File "C:\Code\Django\store\manage.py", line 22, in <module> main() File "C:\Code\Django\store\manage.py", line 18, in main execute_from_command_line(sys.argv) File "C:\Users\E\AppData\Local\Programs\Python\Python310\lib\site-packages\django\core\management\__init__.py", line 419, in execute_from_command_line utility.execute() File "C:\Users\E\AppData\Local\Programs\Python\Python310\lib\site-packages\django\core\management\__init__.py", line 413, in execute self.fetch_command(subcommand).run_from_argv(self.argv) File "C:\Users\E\AppData\Local\Programs\Python\Python310\lib\site-packages\django\core\management\base.py", line 354, in run_from_argv self.execute(*args, **cmd_options) File "C:\Users\E\AppData\Local\Programs\Python\Python310\lib\site-packages\django\core\management\base.py", line 398, in execute output = self.handle(*args, **options) File "C:\Users\E\AppData\Local\Programs\Python\Python310\lib\site-packages\django\contrib\staticfiles\management\commands\collectstatic.py", line 161, in handle if self.is_local_storage() and self.storage.location: File "C:\Users\E\AppData\Local\Programs\Python\Python310\lib\site-packages\django\contrib\staticfiles\management\commands\collectstatic.py", line 215, in is_local_storage return isinstance(self.storage, FileSystemStorage) File "C:\Users\E\AppData\Local\Programs\Python\Python310\lib\site-packages\django\utils\functional.py", line 246, in inner self._setup() File "C:\Users\E\AppData\Local\Programs\Python\Python310\lib\site-packages\django\contrib\staticfiles\storage.py", line 438, in _setup self._wrapped = get_storage_class(settings.STATICFILES_STORAGE)() File "C:\Users\E\AppData\Local\Programs\Python\Python310\lib\site-packages\django\core\files\storage.py", line 366, in get_storage_class return import_string(import_path or settings.DEFAULT_FILE_STORAGE) File "C:\Users\E\AppData\Local\Programs\Python\Python310\lib\site-packages\django\utils\module_loading.py", line 17, in import_string module = import_module(module_path) File "C:\Users\E\AppData\Local\Programs\Python\Python310\lib\importlib\__init__.py", line 126, in import_module return _bootstrap._gcd_import(name[level:], package, level) File "<frozen importlib._bootstrap>", line 1050, in _gcd_import File "<frozen importlib._bootstrap>", line 1027, in _find_and_load File "<frozen importlib._bootstrap>", line 992, in _find_and_load_unlocked File "<frozen importlib._bootstrap>", line 241, in _call_with_frames_removed File "<frozen importlib._bootstrap>", line 1050, in _gcd_import File "<frozen importlib._bootstrap>", line 1027, in _find_and_load File "<frozen importlib._bootstrap>", line 1004, in _find_and_load_unlocked ModuleNotFoundError: No module named 'backend' I tried following that path and saw that there was no python file … -
mod_wsgi - Permission denied - Unable to start Python home
I am attempting to run django on an unmanaged VPS running Ubuntu 20.04. I connected to the freshly installed server, installed Django and Postresql. Apache was already installed. I then installed mod_wsgi. I then attempted to configure my .conf file. Edited file etc\apache2\sites-available\000-default.conf to include the following: Alias /static /root/django-apps/dmsemapping/staticfiles <Directory /root/django-apps/dmsemapping/staticfiles> Require all granted </Directory> <Directory /root/django-apps/dmsemapping/dmsemapping> <Files wsgi.py> Require all granted </Files> </Directory> WSGIDaemonProcess dmsemapping python-path=/root/django-apps/dmsemapping python-home=/root/django-apps/env WSGIProcessGroup dmsemapping WSGIScriptAlias / /root/django-apps/dmsemapping/dmsemapping/wsgi.py dmsemapping is the name of my django project /root/django-apps/dmsemapping is the path to my project /root/django-apps/env is the path to my environment variable for python When I run this I get a 403 error. In the error.log file I get: Current thread 0x00007f84dde19c40 (most recent call first): <no Python frame> [Tue Oct 26 22:55:44.887129 2021] [wsgi:warn] [pid 12089:tid 140208634960960] (13)Permission denied: mod_wsgi (pid=12089): Unable to stat Python home /root/django-apps/env. Python interpreter may not be able to be initialized correctly. Verify the supplied path and access permissions for whole of the path. Python path configuration: PYTHONHOME = '/root/django-apps/env' PYTHONPATH = (not set) program name = 'python3' isolated = 0 environment = 1 user site = 1 import site = 1 sys._base_executable = '/usr/bin/python3' sys.base_prefix = '/root/django-apps/env' sys.base_exec_prefix … -
Django REST framework is changing object values when request method is GET
i have problem with (not wanted) objects values setting. I have viewset where serialiser is chosen by request.method. I want to update DateTimeField only WITH POST/PUT method, and then can check this value with GET method but.. after posting new object I got json like this { "datetimefield": "2021-10-26 23:01:53.272194" } and after GET method I got this (for the same object): { "datetimefield": "" } my code: class SomeViewSet(viewsets.ModelViewSet): queryset = SomeModel.objects.all() def get_serializer_class(self): if (self.request.method == 'POST'): return FirstSerializer else: return SecondAppSerializer class FirstSerializer(serializers.HyperlinkedModelSerializer): datetimefield = serializers.SerializerMethodField() def get_datetimefield(self, obj): return str(datetime.today()) class Meta: model = SomeModel fields = ('datetimefield') class SecondSerializer(serializers.HyperlinkedModelSerializer): class Meta: model = SomeObject fields = ('datetimefield') class SomeModel(models.Model): datetimefield = models.CharField(max_length=100) Anyone know how to solve this? -
Django serializers methods
I have model called SecondAddress with fields like street, apartment, number, city. For this model I have serializer second_address - with the same fields. This models and serializer are using in Client and Recipient modelserializer as a basic field but not required, it can be null. In the client and Recipient client I have basic_address and this is required. The idea is that if basic_address fields are incorrect, client must to provide second_address fields. Everything works and for checking the status of second_address field I have folowing serializer: matching_address = serializers.SerializerMethodField() And fucntion: def get_matching_address(self, client): return client.second_address is None If basic_address fields is correct there no needed second_address fields and field matching_address will have True. If second_address is provided matching_address field show False. I would like to create function that if matching_address field is True and second_address fields are provided the data must to be deleted from second_address. And if False need to provide second_address fields. Please help me with this function and method -
RegEx length range not working for Django/Python? (re.error: multiple repeat at position)
I'm trying to add a custom Validator with a regex for a-z, A-Z, 0-9, _ and between 3 and 20 characters. class Validator(validators.RegexValidator): regex = r"^[A-Za-z0-9_]{3,20}+\Z" flags = re.ASCII RegEx works fine when there's no character range i.e. r"^[A-Za-z0-9_]+\Z" And I think {3,20} is the correct way of specifying the length... so I'm not sure why the regex isn't working. I get this error re.error: multiple repeat at position 19 regardless of the string that I'm trying to validate. Full traceback: backend-web-1 | Traceback (most recent call last): backend-web-1 | File "/usr/local/lib/python3.10/site-packages/django/core/handlers/exception.py", line 47, in inner backend-web-1 | response = get_response(request) backend-web-1 | File "/usr/local/lib/python3.10/site-packages/django/core/handlers/base.py", line 181, in _get_response backend-web-1 | response = wrapped_callback(request, *callback_args, **callback_kwargs) backend-web-1 | File "/usr/local/lib/python3.10/site-packages/django/views/decorators/csrf.py", line 54, in wrapped_view backend-web-1 | return view_func(*args, **kwargs) backend-web-1 | File "/usr/local/lib/python3.10/site-packages/django/views/generic/base.py", line 70, in view backend-web-1 | return self.dispatch(request, *args, **kwargs) backend-web-1 | File "/usr/local/lib/python3.10/site-packages/django/utils/decorators.py", line 43, in _wrapper backend-web-1 | return bound_method(*args, **kwargs) backend-web-1 | File "/usr/local/lib/python3.10/site-packages/django/views/decorators/debug.py", line 89, in sensitive_post_parameters_wrapper backend-web-1 | return view(request, *args, **kwargs) backend-web-1 | File "/usr/local/lib/python3.10/site-packages/dj_rest_auth/registration/views.py", line 47, in dispatch backend-web-1 | return super().dispatch(*args, **kwargs) backend-web-1 | File "/usr/local/lib/python3.10/site-packages/rest_framework/views.py", line 509, in dispatch backend-web-1 | response = self.handle_exception(exc) backend-web-1 | File "/usr/local/lib/python3.10/site-packages/rest_framework/views.py", … -
Caching in django-pytest
In an API Client Library that supports Django, I am implementing a way for users to configure Django Cache when the API Client gets used in a Django application. How do I test the caching behavior without an actual Django app in the Client Library? I have tox set up with pytest-django as a test requirement, and I am getting this error when I run test_django_cache.py: django.core.cache.backends.base.InvalidCacheBackendError: The connection 'django.core.cache.backends.dummy.DummyCache' doesn't exist. # test_django_cache.py import django from django.conf import settings from .django_cache import DjangoCache settings.configure() django.setup() def test_set_get(settings): cache_name = 'django.core.cache.backends.dummy.DummyCache' cache = DjangoCache(cache_name=cache_name) vals = { "status": "live", "configuration": { "name": "features", "value": ["bi_connector", "google_tag_manag Blockquote er"] } } cache_key = 'client.040e0ec3-2578-4fcf-b5db-030dadf68f30.live' cache.set(key=cache_key, value=vals) assert cache.get(key=cache_name) == vals # django_cache.py class DjangoCache: def __init__(self, cache_name, cache_timeout=60): self.cache_name = cache_name self.cache_timeout = cache_timeout self._django_cache = None def get_django_cache(self): if not self._django_cache: from django.core.cache import caches self._django_cache = caches[self.cache_name] return self._django_cache def set(self, key, value): kwargs = {} if self.cache_timeout is not None: kwargs['timeout'] = self.cache_timeout return self.get_django_cache().set(key, value, **kwargs) def get(self, key): return self.get_django_cache().get(key) -
Django LRU_Cache with API Calls
I'm trying to use the Reddit API via PRAW (https://praw.readthedocs.io/en/stable/) with Django, and am thinking of trying to use functools lru_cache decorator to implement some kind of caching so I can cache the results of similar API calls to reduce overall calls being made. I've never done anything like this so I've been mainly following examples of implementing the @lru_cache decorator. I have 3 files that are primarily involved with the API calls / display here. I have: account.html {% extends 'myapp/base.html' %} <h1> {{ name }} </h1> <h3> {{ comment_karma }} </h3> <h5> Top Posts </h5> <table> <tr> <th> Post </th> <th> Subreddit </th> </tr> {% for s in top_submissions %} <tr> <td> {{ s.title }} </td> <td> {{ s.subreddit }} </td> </tr> {% endfor %} </table> views.py from . import reddit reddit = reddit.Reddit() def account_page(): context = reddit.details(request.user.reddit_username) return render(request, 'stats/dashboard.html', context) reddit.py from functools import lru_cache class Reddit: def __init__(self): self.praw = praw.Reddit( client_id = CLIENT_ID, client_secret = CLIENT_SECRET, user_agent = USER_AGENT ) @lru_cache(maxsize = 256) def details(self, redditor): redditor = self.praw.redditor(redditor) overview = { 'name': redditor.name, 'comment_karma': redditor.comment_karma, 'top_submissions': redditor.submissions.top(limit=10), } return overview Here's the problem: when I don't have the lru_cache, then everything works … -
Reverse for 'dome_view' with no arguments not found. 1 pattern(s) tried: ['dome2/(?P<id>[0-9]+)/$']
I have try to send request to external API in order to perform PATCH method. I have a view defined as below: def dome_view(request, id): ...... I need id in order to pass it to form action and make necessary update on other endpoint which is external.My url pattern is like that path('dome2/int:id/', views.dome_view, name='dome_view'), When I put id to my form action like below, i got an error "Reverse for 'dome_view' with no arguments not found. " But when i put the exact id that i want to update, then PATCH method succeded. For example: form action="{% url 'dome_view' 5 %}" method="post"> How can i achieve to successfully send PATCH request without specifiying exact id to form action? I just want to do it like What am i missing? Thanks -
Store multiple files in dabatase, django
I have a model that will contain multiple files. Is it better to create a new model and as a foreign key to set to which object of other model it belongs or is it better to save a object in database in that model, not creating new one. Thanks in advance