Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Not able to install tensorflow in Mac M1
I am trying to install tensorflow on my Mac M1 and I am getting the following error: ERROR: Could not find a version that satisfies the requirement tensorflow (from versions: none) ERROR: No matching distribution found for tensorflow I have python3- 3.9.7, pip- 21.3.1 -
how to migrate just specific table in django?
I tried multiple databases in django. So, I set databases like that # settings.py DATABASE_ROUTERS = [ 'stage1.routers.MultiDBRouter', ] DATABASE_APPS_MAPPING = { 'stage1': 'stage1', } DATABASES = { 'default': { 'ENGINE': 'django.db.backends.sqlite3', 'NAME': BASE_DIR / 'db.sqlite3', }, 'stage1': { 'ENGINE': 'django.db.backends.mysql', 'NAME': 'stage1', 'HOST': 'localhost', 'USER': 'root', 'PASSWORD': '######', 'PORT': 3306, 'CHARSET': 'utf8mb4', }, } # stage1.routers.py class MultiDBRouter(object): def __init__(self): self.model_list = ['stage1'] def db_for_read(self, model, **hints): if model._meta.app_label in self.model_list: return model._meta.app_label return None def db_for_write(self, model, **hints): if model._meta.app_label == 'stage1': return 'stage1' return None def allow_relation(self, obj1, obj2, **hints): if (obj1._meta.app_label in self.model_list or obj2._meta.app_label in self.model_list): return True return None def allow_migrate(self, db, app_label, model_name=None, **hints): if app_label == 'stage1': return db == 'stage1' return None # stage1.models.py from django.db import models class Room(models.Model): name = models.CharField(max_length=100) sort = models.CharField(max_length=100) class Meta: app_label = "stage1" I did manage.py migrate --database=stage1 and it worked. But there are something wrong I didn't intend. I just wanted stage1 database has only one table room. But it has all tables that are basically set like auth_group, django_session ... How can I do to make only one table room in stage1 database? Please help me. -
Swedish BankID QR code Server/Client Interaction in Django
This post is related to my last post BankID has the ability to offer animated QR code generation for authorization. It generates a new QR every second and you scan with a mobile app and then their server returns a success once the user enters their code or scans their fingerprint. You can just skip the QR code and have bankID ping the user to enter their code to auth, but I want to have the QR code functionality for my app. Now my question is this. When the POST request is sent Views gets a qr_start_token, and qr_start_secret returned from the bankID server. Views is waiting for a status change from the BankID server to do something, but that leaves me at a lost on how I can render the changing QR code on the client. How can I do this without rendering a new page, passing the secret through context and using javascript to replicate this process? Here is the relevant code: if request.META['HTTP_USER_AGENT']: ua_string = request.META['HTTP_USER_AGENT'] user_agent = parse(ua_string) if user_agent.is_pc: status=client.collect(order_ref=auth["orderRef"])["status"] order_time = time.time() while status == "pending": qr_start_token = auth["qrStartToken"] qr_start_secret = auth["qrStartSecret"] print(qr_start_secret) qr_time = str(int(time.time() - order_time)) qr_auth_code = hmac.new(qr_start_secret.encode(), qr_time.encode(), hashlib.sha256).hexdigest() qr_data … -
Django admin on many-to-many relation: Variant-category relationship with this Variant and Category already exists
In Django admin if i select new field in inline of category which is many to many relation with variant, if i select the same category it raise error Variant-category relationship with this Variant and Category already exists. How would i select new inline field with same category for many to many field. Here's my code Admin.py class VariantInline(admin.TabularInline): model = Variant.category_id.through extra = 0 @admin.register(Category) class CategoryAdmin(ImportExportModelAdmin): ... inlines = [VariantInline] Models.py class Category(models.Model): category_id = models.AutoField(primary_key=True) category_name = models.CharField(max_length=50) ... class Variant(models.Model): ... variant_id = models.AutoField(primary_key=True) category_id = models.ManyToManyField(Category) -
"'Request' object has no attribute 'learner'": Django Restframework
There is an error in my code "'Request' object has no attribute 'learner'". Here, My requirement is "request.learner" is empty then call "CDetailsSerializer" otherwise call "CourseDetailsSerializer". def list(self, request, **kwargs): try: queryset = self.get_queryset() queryset = self.filter_queryset(queryset) if not request.learner: serializer = CDetailsSerializer(queryset, many=True) else: serializer = CourseDetailsSerializer(queryset, many=True) print('s', serializer.data) response_data = {'course': serializer.data} return self.jp_response(s_code='HTTP_200_OK', data=response_data) except Exception as e: print(e) return self.jp_error_response('HTTP_500_INTERNAL_SERVER_ERROR', 'EXCEPTION', [str(e), ]) Here always calling (else part) CourseDetailsSerializer, but in some situations, I also want to call (if part) CDetailsSerializer.Give me a solution to fix this. -
django factory using a factory gives "Database access not allowed"
I want to create a user_profile from a factory called UserProfileFactory which uses a User object from UserFactory. the error is: RuntimeError: Database access not allowed, use the "django_db" mark, or the "db" or "transactional_db" fixtures to enable it. here are the relivant classes. from django.contrib.auth import get_user_model from factory import Faker, post_generation from factory.django import DjangoModelFactory class UserFactory(DjangoModelFactory): username = Faker("user_name") email = Faker("email") name = Faker("name") @post_generation def password(self, create: bool, extracted: Sequence[Any], **kwargs): password = ( extracted if extracted else Faker( "password", length=42, special_chars=True, digits=True, upper_case=True, lower_case=True, ).evaluate(None, None, extra={"locale": None}) ) self.set_password(password) class Meta: model = get_user_model() django_get_or_create = ["username"] class UserProfileFactory(DjangoModelFactory): user = UserFactory.create() #### the problem line ### country = Faker("country") # which laws apply birth_date = Faker("date_of_birth") # in the US you can't collect data from <13yo's class Meta: model = UserProfile and in the tests/test.py class TestUserProfileDetailView(): def test_create_userprofile(self): """creates an APIRequest and uses an instance of UserProfile to test a view user_detail_view""" factory = APIRequestFactory() request = factory.get('/api/userprofile/') request.user = UserProfileFactory.create() # problem starts here # response = user_detail_view(request) self.assertEqual(response.status_code, 200) -
Empty lines in form-select django template
i have a choice form, the user has to select a country from a dropdownlist. my html code: <div class="mb-3"> <label for="{{ profile_form.country.id_for_label }}" id="country_label" class="form-label">Country</label> <select class="form-select" name="{{ profile_form.country.html_name }}" id="{{ profile_form.country.id_for_label }}"> {% for country in profile_form.counry %}<option>{{ country }}</option>{% endfor %} </select> </div> But in html i get a dropdown with a empty line between every country: -Usa -emptyline -Germany -emptyline How can i get rid of those empty lines ? -
Can the APIRequestFactory create a request with data and user attributes
I'm trying to make a unit test for a function that takes a django Request object as a parameter; the Request object being one of the params from a Django class based view method. From the request object param, it's assumed there is a data and user attribute. My problem is that I can't replicate the request object using DRF's APIRequestFactory. When I'm using the python requests package and I do something like headers = { 'Authorization': "Token {}".format(settings.AUTH_TOKEN), 'Accept': 'application/json', 'Content-Type': 'application/json', } data['foo'] = foo_id response = requests.post( '{}/api/foo/{}/action/'.format(settings.ROOT_URL, foo_id), headers=headers, json=data) Then the user and data attribute exist in the request object of the class based views. If, however, I use DRF's APIRequestFactory and do data = {"foo_id": 1234} factory = APIRequestFactory() request = factory.post('/api/foo/1/action/', data, format="json") ...then I have to explicitly add request.user = user request.data = data Only the body attribute as data, and thats as a bytestream e.g. body: b'{"foo_id":"1234"}' Is what I'm trying to do possible? As an aside, it could also be that I'm violating the law of demeter and that my function being tested should be taking a dict and a user object as params instead of an entire request object, … -
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 …