Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Django template regorup
I want to regroup this on the basis of ingredients. this is my sample result which I want Ingredient_name, all the stop names associated with that ingredient, all the stop_longitude associated with that ingredient and so on in one table row. model class SupplyChainStops(models.Model): ingredient = models.ForeignKey(Ingredients, null=True, on_delete=models.CASCADE) stop_name = models.CharField(max_length=1024, null=True, blank=True) stop_longitude = models.CharField(max_length=500, null=True, blank=True) stop_latitude = models.CharField(max_length=500, null=True, blank=True) is_supplier = models.BooleanField(default=False, blank=True, null=True) def __str__(self): return f'{self.stop_name}' query items = SupplyChainStops.objects.all() template {% for item in items %} <tr class="text-black"> <td>{{ item.ingredient }}</td> <td>{{ item.stop_name }} <td>{{ item.stop_longitude }} <td>{{ item.stop_latitude }} -
How can we get all usernames list only not user objects with django ORM
I want to know that how can we get list of required field data from django models. In my case i want to get all usernames from users models. receivers = User.objects.all() this return all users objects. I want to get usernames directly. Something like below: receivers = User.objects.all(username) output: ["ahmed","dummy","hamza","sentence"] in sql query looks like below: SELECT username from USER -
How to prevent use of urls outside mysite
I am creating a small website to download free games. I uploaded the games to my database via filefield. I have a link like this : domain.com/media/games/game_name.exe The question here is: 1 - How do I prevent this link from being copied from my site and used on other sites. 2 - How to redirect the link to my site if it is used on another site. this is my models: class games(models.Model): class Meta : verbose_name_plural = 'games' game_title = models.CharField(max_length=50) game_requirements = models.CharField(max_length=100) game_picture = models.ImageField(upload_to='images') game_desc = models.TextField() game_size = models.CharField(max_length=20) game_upload = models.fileField(upload_to='games') def __str__(self): return self.game_title this is my media_config: MEDIA_URL = '/media/' MEDIA_ROOT = os.path.join(BASE_DIR, 'media') this is my download_template_url: {% for game in all_games %} <a href="{{game.game_upload}}">download<i class="fa fa-download"></i></a> {% endfor %} this is my views: def download(requset,game_title): all_games = games.objects.filter(game_title=game_title) context ={ 'all_games' :all_games, } return render( requset,'download.html',context) Thanks in advance. -
How to add additional function to form submit button in Django
I have a form and a submit button for it, how can I add additional functionality to this button, like for example I want to call sendNotification function when submit button is pressed. I googled and so far understand that this can be done by adding "onclick" javaScript function to that Submit button but then I need to call sendNotification in javaScript which seems to me kind of doing stuff around the corner, so I was wondering if there is some way to add function call to Submit button directly? #updateProduct.html <h1 style="font-size: 20px; margin-left: 10px;" class="p-2"> Update Job </h1> <div class="container m-1"> <form id=form action="" method="post" enctype="multipart/form-data"> {% csrf_token %} {{ form.as_p }} <input type="submit" name="Save Changes" class="btn btn-success m-0" value="Save Changes"> <a class="btn btn-primary mt-0" href="{% url 'showProducts' %}" > Cancel </a> </form> <!--This button below separately works but can it be integreted to the submit button above--> <a href="{% url 'sendNotification' id email %}" class="btn btn-success" >Notify</a> </div> Below is the sendNotification function itself #views.py @login_required(login_url='sendNotification') def sendNotification(request, pk, email): product = Product.objects.get(id=pk) msg = EmailMessage() msg.set_content(product.description + " Here is the link for details: ZZZ+str(pk)+"/" ) msg['subject'] = product.name msg['to'] = email user = "XX@gmail.com" msg['from'] … -
name 'displayhtml' is not defined in python 3.7
I have upgraded my code from Django 1.8 to Django 3.0 and my python version is python 3.7 when i deploy my code to dev server i m getting this issue "name 'displayhtml' is not defined" my requirements.txt django-recaptcha== 2.0.6 settings.py file INSTALLED_APPS = [ .... .... 'captcha', ] here is my views.py def enquiry_external(request, client_pk): form_data={} admin = ClientUser.objects.filter(client_id=client_pk,is_admin=True)[0].id user_id = request.user public_key = settings.RECAPTCHA_PUBLIC_KEY script = displayhtml(public_key=public_key) id = request.GET.get('gid','') ..... ..... ..... I couldn't understand why i m getting this error -
The dynamic data in my Django project doesn't change after I change the data
My Django project is linked with dynamic data from my google sheet API. However, when I edit on my google sheet and reload the page, the data doesn't change accordingly. I have to manually reload the server to refresh all the changes. I used gspread and pandas to convert my google sheet into a list of dictionaries. I was advised that I am reading the google sheet once, outside the view handling function. That only gets executed once while Django is starting up, and then my data is "fixed". If I want to refresh the data on each request, I need to read it inside the view function that handles the request, but I don't understand how. The following is my views.py from django.shortcuts import render from django.http import HttpResponse from django.template import loader import gspread import pandas as pd import datetime from oauth2client.service_account import ServiceAccountCredentials scope = ['https://www.googleapis.com/auth/spreadsheets'] creds = { "type": "service_account", "project_id": "ringed-arcana-338821", "private_key_id": "c1b2438db2651b90b92e06974a08cd40da42c696", "private_key": "-----BEGIN PRIVATE KEY-----\nMIIEugIBADANBgkqhkiG9w0BAQEFAASCBKQwggSgAgEAAoIBAQCdzjDytlclQ+g1\n3jsbmHwXrGtLhVhAV3aPzeuWzIvOfer1qYxgAeIiClWxsV/uF8sz/DHCEtY35ZBX\nW73brqSt34dfwLl2fBbvDUVVLyZZsrDw3MxrDhagbn3VUBJtn04WNCkk6E1HKP1E\no9ugvdj+sCLuT9NOQvMqhWQPP/KGs1NhmUJfmNF2dput6u6N26MHT09y28waxhEr\n73gFZOjD3qhIYHQEUOnXb/U4QmDBmwPks2R1IwBAVJq9tjyOgRaC9Kz7fKHUhMZH\n1OG1KWlb+3LUImqju7/kPV2N9wQO5z5xlMWq+S4kTE0C2wy8OPXycv3Ckz3K1OFL\nbNwjmsKLAgMBAAECggEAK8IqZpNTdPzwnkdigpN1Dad9FTMDtsvKD7RdOLK9rePS\nzI5YY6MCDsho3N4/qKkmauLq9VL93gAlV2QUMJ+sAJ70TgQGKandPiqi6C0r6EGZ\nuSCw+pqsgY5CDG2ovocnQxbxtc9I5ouiN29sjpU2X+F9vjGaeaAtB8R3a5ci7GDL\n6T9YEupA6QkowtpTj0xtUMBRuiMi5a1Oc1ofETMg7mTSsgLbuIUUtfTbDNOpT6ri\nWn1ziTzCOB8wkty8anVUF8je+GfcBKzPLvCpjDkqPW2nUjVXRhCuL4PavsrZrXvd\nxD9evOmUvYRgclhZVo1qU09V87USdAZUlHnXEAEAuQKBgQDXVBl6ePhuW3ZeUBmf\nevstAw5U3TwliNXRuudTsRAoACbqEoHXKUuX+FuyrQIEJQjpPCAbJfsT8Dwn43ze\nsFeyZnEB4CnEZEvQSfj8behWrbe83EMzt4YJP5ZjVqNB2NUx4KAzJVEXIsHc5sxc\nndUwyfyvdllTFmlEgBKBYsWBdQKBgQC7nKVcKUCraLspJtXhnDk93S6d8WpU3nvD\nEt4LZ8EJX/G1hWyZASgY0beDG75+SeDVy/pxoU5jRyFpgxtUYngEGAyfv7SQtsWT\n4WCoOkUqbDoX0TyMDssr1Cqksy8uvtwtcXvDjevLy4e72CXLegrJDMWudDCzpu2g\nG4PjlLKz/wKBgBlbuBxqPqeQceItgLb9XrMwVvG7lCe/c57dafy7L3Hmgq6yO0RB\ngruE7heetEwUqHX/NLC9ylHQyuTPr5byIYHK+qgD5CdSwHLpIz9nGiOLFcZSEj/2\n7vwL1wQf4d4RURosn/EmBeS5nScMryiBFehHAVEQmPhl/UOp6YP/Q885An9oEHuo\nozk72tv195Srj/wwVH+HHGHesYn0qoJ/0Q1CJfXsuhWCySF0ot8n2jvP0SrlbD9+\nx/qzFsFxxUdjhzsLCkv2UF/X5YmyfVEf/zJeVanjjCwJhCsuJIGC2eFSDIwUqN39\nmrswT7T6fOp58zgITQ1ZtxlMjUtBhAGkOtblAoGAXtQvXK1kZ1kXXPdJObHyejml\nv3LXDFd4r6J4es6bIQsjY3ggLDWyiyZ9SzLRIyrejgcU4hVZPyOAiq01gJLXU+/p\nbQsTj9sux6kmJOVhGuFLLNl13JeC8GuMfNteme3M+R1FIAZPXOQ6Z0BkB4SU+ijK\nnsJQT+FQEDXWjZk1FXo=\n-----END PRIVATE KEY-----\n", "client_email": "returnrecord@ringed-arcana-338821.iam.gserviceaccount.com", "client_id": "110831427047173795415", "auth_uri": "https://accounts.google.com/o/oauth2/auth", "token_uri": "https://oauth2.googleapis.com/token", "auth_provider_x509_cert_url": "https://www.googleapis.com/oauth2/v1/certs", "client_x509_cert_url": "https://www.googleapis.com/robot/v1/metadata/x509/returnrecord%40ringed-arcana-338821.iam.gserviceaccount.com" } client = gspread.service_account_from_dict(creds) def CreateSheet(Return_record): sheet = client.open(Return_record).sheet1 return sheet from sheet2api import Sheet2APIClient sheet = client.open('Return Record 2022') sheet_instance = sheet.get_worksheet(0) mylist … -
How do I resolve this urllib3 issue when trying to get a forked django project up and running?
I have a fork of a django project I am trying to get up and running for my local development environment. When I run my requirements it chokes with ~ this message [Cannot install -r requirements.txt (line 28), urllib3[secure]==1.26.0, urllib3[secure]==1.26.1]... etc. (this error spans ~20 lines). So there are conflicting dependencies it says. I have tried removing the specific version declaration and same issue. And, I have tried running under sudo and same issue. It seems like overall there's a discussion around doing some sort of declaration that specifies less than and greater than versions of a package with this general notion that pip isn't great at sorting this sort of thing out on its own but most of that conversation seems a few years old and I'm unclear on how such a declaration should be properly configured. Is this a common issue others have experienced of late? The project is running on django 3.0.2 and I tried to force an update to django to 4.0.2 in the hopes that the issue centers there but that didn't seem to address it either. Thanks in advance for your help. -
failed to push some refs to ... (heroku)
I'm trying to host a django website to heroku platform but i get this error, what should I do ? remote: Building source: remote: remote: -----> Building on the Heroku-20 stack remote: -----> Determining which buildpack to use for this app remote: -----> Python app detected remote: -----> No Python version was specified. Using the buildpack default: python-3.9.10 remote: To use a different version, see: https://devcenter.heroku.com/articles/python-runtimes remote: -----> Installing python-3.9.10 remote: -----> Installing pip 21.3.1, setuptools 57.5.0 and wheel 0.37.0 remote: -----> Installing SQLite3 remote: -----> Installing requirements with pip remote: ERROR: PyAudio-0.2.11-cp39-cp39-win_amd64.whl is not a supported wheel on this platform. remote: ! Push rejected, failed to compile Python app. remote: remote: ! Push failed remote: Verifying deploy... remote: remote: ! Push rejected to mighty-garden-63583. remote: To https://git.heroku.com/mighty-garden-63583.git ! [remote rejected] master -> master (pre-receive hook declined) error: failed to push some refs to 'https://git.heroku.com/mighty-garden-63583.git' -
add a single data to serializer in django
I'm writing an API where the user's followers are listed.I also want to send the total number of followers in this API.But the totalFollower field keeps repeating.I only want it sent once. Like that: [ totalFollower:2 followers: { { "following": "gizli_takip", }, { "following": "herkeseacikvetakip", } }] MY serializer class SerializerUserFollowings(serializers.ModelSerializer): following = serializers.CharField(source="follower.username") totalFollower = serializers.ReadOnlyField() class Meta: model = ModelFollower fields = ("following","totalFollower") -
'WSGIRequest' object has no attribute 'job_title'
I am currently working on a Job application app as a personal project. I am currently stuck on a page where the following error pops up when ever I try to access a parameter that is passed through the URL: The error trace back looks like this: Traceback (most recent call last): File "C:\Users\E.Musonda\AppData\Local\Programs\Python\Python310\lib\site-packages\django\core\handlers\exception.py", line 47, in inner response = get_response(request) File "C:\Users\E.Musonda\AppData\Local\Programs\Python\Python310\lib\site-packages\django\core\handlers\base.py", line 181, in _get_response response = wrapped_callback(request, *callback_args, **callback_kwargs) File "C:\Users\E.Musonda\AppData\Local\Programs\Python\Python310\lib\site-packages\django\views\generic\base.py", line 69, in view return self.dispatch(request, *args, **kwargs) File "C:\Users\E.Musonda\AppData\Local\Programs\Python\Python310\lib\site-packages\django\views\generic\base.py", line 101, in dispatch return handler(request, *args, **kwargs) File "C:\Users\E.Musonda\AppData\Local\Programs\Python\Python310\lib\site-packages\django\views\generic\edit.py", line 170, in get return super().get(request, *args, **kwargs) File "C:\Users\E.Musonda\AppData\Local\Programs\Python\Python310\lib\site-packages\django\views\generic\edit.py", line 135, in get return self.render_to_response(self.get_context_data()) File "C:\Users\E.Musonda\AppData\Local\Programs\Python\Python310\lib\site-packages\django\views\generic\edit.py", line 68, in get_context_data kwargs['form'] = self.get_form() File "C:\Users\E.Musonda\AppData\Local\Programs\Python\Python310\lib\site-packages\django\views\generic\edit.py", line 35, in get_form return form_class(**self.get_form_kwargs()) File "C:\Users\E.Musonda\Desktop\workspace\Python\Python web\Authentication-and-Validation\Authentication-and-Validation\multipleselect\forms.py", line 9, in __init __ get_query_data = self.request.job_title AttributeError: 'WSGIRequest' object has no attribute 'job_title' Views.py: class ApplicationForm(CreateView): model = Requirements form_class = ApplicationForm template_name = 'requirements/job_specs.html' # Passes the request object to forms def get_form_kwargs(self): kwargs = super(ApplicationForm, self).get_form_kwargs() kwargs['request'] = self.request return kwargs Any Help will be highly appreciated thanks. -
DRF Cannot assign must be instance error while testing
I am very new to Django and especially to testing. I am trying to test a view which retrieves a resource object and creates a game round and gamesession object (in the get request). This is what my tests look like: test_views.py class GameViewTests(APITestCase): def setUp(self): self.client = APIClient() self.resource = {'hash_id': '1404cc769fa538fab1b65b9cad201eca'} self.user = CustomUser.objects.create(username="carina") self.gametype = Gametype.objects.create(name="labeler", rounds=5, round_duration=60, enabled=True), self.gamesession = Gamesession.objects.create(user=self.user, gametype=self.gametype, created=datetime.now()) self.gameround = Gameround.objects.create(user=self.user, gamesession=self.gamesession, created=datetime.now(), score=0) self.game_data = {'gametype': self.gametype, 'gamesession': self.gamesession, 'gameround': self.gameround, 'resource': self.resource} self.response = self.client.get('http://localhost:8000/api/game/', self.game_data, format="json") def test_get(self): self.client = APIClient() response = self.client.get('http://localhost:8000/api/game/') self.assertEqual(response.status_code, 200) When I run my test, I get the ValueError: Cannot assign "(<Gametype: imageLabeler>,)": "Gamesession.gametype" must be a "Gametype" instance. How can I make my test pass? -
django authentication with username and face_image
I'm trying to authenticate a user without a username and face_image. I can't figure out where is the problem. I have read this article Authentication without a passwrod Django to solve my problem. Can anyone give me a hint or advice? Thank you authenticate.py from django.contrib.auth.models import User from django.contrib.auth.backends import ModelBackend import face_recognition from django.db.models import Q from django_two_factor_face_auth.models import UserFaceImage class FaceIdAuthBackend(ModelBackend): def authenticate(self, username=None, face_id=None, **kwargs): try: user_T = User.objects.get(Q(username=username)) if self.check_face_id(face_id=user_T.userfaceimage.image, uploaded_face_id=face_id): return user_T except User.DoesNotExist: return None def check_face_id(self, face_id=None, uploaded_face_id=None): confirmed_image = face_recognition.load_image_file(face_id) uploaded_image = face_recognition.load_image_file(uploaded_face_id) face_locations = face_recognition.face_locations(uploaded_image) if len(face_locations) == 0: return False confirmed_encoding = face_recognition.face_encodings(confirmed_image)[0] unknown_encoding = face_recognition.face_encodings(uploaded_image)[0] results = face_recognition.compare_faces([confirmed_encoding], unknown_encoding) if results[0] == True: return True return False view.py def face_login(request): if request.method == 'POST': form = AuthenticationForm(request, request.POST) if form.is_valid(): username = form.cleaned_data['username'] face_image = prepare_image(form.cleaned_data['image']) face_ide = FaceIdAuthBackend() user = face_ide.authenticate(request,username=username,face_id=face_image) if user is not None: login(request, user) return redirect(settings.LOGIN_REDIRECT_URL) else: form.add_error(None, "Username, password or face id didn't match.") else: form = AuthenticationForm() context = {'form': form} return render(request, 'django_two_factor_face_auth/login.html', context) model.py class UserFaceImage(models.Model): user = models.OneToOneField(User, on_delete=models.CASCADE) image = models.ImageField(upload_to=content_file_name, blank=False) -
Error in Django channels: ValueError: No application configured for scope type 'websocket'
I am going to develop chat application using Django Channelsby following tutorials: https://channels.readthedocs.io/en/stable/tutorial/part_2.html My Project level routing.py import os from channels.auth import AuthMiddlewareStack from channels.routing import ProtocolTypeRouter, URLRouter from django.core.asgi import get_asgi_application import chat.routing application = ProtocolTypeRouter({ "http": get_asgi_application(), "websocket": AuthMiddlewareStack( URLRouter( chat.routing.websocket_urlpatterns ) ), }) App level routing.py file from django.urls import re_path from . import consumers websocket_urlpatterns = [ re_path(r'^ws/chat/(?P<room_name>[^/]+)/$', consumers.ChatConsumer) ] asgi.py file import os from channels.routing import ProtocolTypeRouter from django.core.asgi import get_asgi_application os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'core.settings') application = ProtocolTypeRouter({ "http": get_asgi_application(), # Just HTTP for now. (We can add other protocols later.) }) -
Connecting to MSSQL with Django
I am using PyCharm and Django to build up a accounting software. There fore, I would like to connect to an external server with MSSQL. I am using the following settings.py 'default': { 'ENGINE': 'django.db.backends.sqlite3', 'NAME': BASE_DIR / 'db.sqlite3', }, 'bnt': { 'ENGINE': 'sql_server.pyodbc', 'NAME': 'POS', 'USER': 'l.bamberg', 'PASSWORD': '*******', 'HOST': '10.171.215.1', # BNTS20005\\SQL17STD 'PORT': '1433', 'OPTIONS': { 'driver': 'ODBC Driver 17 for SQL Server', }, } } If I type in: python manage.py check --database bnt I get: Traceback (most recent call last): File "/Users/georghuber/Desktop/Waschhalle/venv/lib/python3.8/site-packages/django/db/backends/base/base.py", line 230, in ensure_connection self.connect() File "/Users/georghuber/Desktop/Waschhalle/venv/lib/python3.8/site-packages/django/utils/asyncio.py", line 25, in inner return func(*args, **kwargs) File "/Users/georghuber/Desktop/Waschhalle/venv/lib/python3.8/site-packages/django/db/backends/base/base.py", line 211, in connect self.connection = self.get_new_connection(conn_params) File "/Users/georghuber/Desktop/Waschhalle/venv/lib/python3.8/site-packages/sql_server/pyodbc/base.py", line 312, in get_new_connection conn = Database.connect(connstr, pyodbc.OperationalError: ('08001', '[08001] [Microsoft][ODBC Driver 17 for SQL Server]Client unable to establish connection (0) (SQLDriverConnect)') However, if I use View | Tool Windows | Database in Pycharm and set up a connection with the same credentials. I can see the databases. Screenshot of Database Screenshot of Database Properties Any Idea. Should I switch the driver or what am I doing wrong? Regards Georg -
Django M2M to self
I wan't to add songs that at versions of the same song. I've created a model like this: class Song(models.Model): name = models.CharField('Name', max_length=255, blank=True) songVersions = models.ManyToManyField("self", verbose_name = 'Other versions of this song', blank=True) and in Admin I want to add the songs like this: class SongVersionsInline(admin.TabularInline): model = Song.songVersions.through fields = ['name'] class SongAdmin(admin.ModelAdmin): list_display = ['name'] exclude = ('songVersions',) inlines = [ SongVersionsInline, ] But I get the following error: (admin.E202) 'core.Song_songVersions' has more than one ForeignKey to 'core.Song'. You must specify a 'fk_name' attribute. Any ideas how to get this working? -
Using redirect in Django (return redirect(f'payment_details', foo='bar'))
I would understand how to use redirect in Django. Specifically, what's the meaning of the letter "f" in: redirect(f' ...? and what's the difference between use it or not. -
Django : Invalid block tag on line 121: 'popular_products', expected 'endblock'. Did you forget to register or load this tag?
I have a custom template tag in my project and every thing looks fine but when i want to use this template tag i got this error: Invalid block tag on line 122: 'popular_products', expected 'endblock'. Did you forget to register or load this tag? base_tags.py: from django import template from django.db.models import Count, Q from datetime import datetime, timedelta from shop.models import Product register = template.Library() @register.inclusion_tag('shared/partials/popular_product_slider.html') def popular_products(): last_week = datetime.today() - timedelta(days=7) return { "popular_products": Product.objects.filter(available=True).annotate( count=Count('hits', filter=Q(producthit__date__gt=last_week))).order_by( '-count', '-created')[:3] } home_page.html template: {% extends 'shared/_base.html' %} {% load base_tags %} {% load i18n %} {% load render_partial %} {% load static %} {% load ratings %} {% load thumbnail %} <div class="row"> <div class="col-lg-12"> <div class="tab-content"> <div id="recent" class="tab-pane fade show active"> <div class="row product-slider"> {% popular_products %} </div> </div> </div> </div> popular_product_slider.html {% for product in popular_products %} {{product.image}} {{product.detail}} {{product.title}} {% endfor %} views.py def home_page(request): context = {} return render(request, 'Home_page.html', context) -
Is there any Email Client Frameworks(Python & Django) which supports sending emails on high priority (delivery) emails
I am trying to build a service which send emails in the real time using django framework Which sends emails to users, a case arises where email related to system bug appears, where it needs to be sent out immediately by prioritizing the delivery to the system admin. (So that they can try to resolve the problem immediately) How to prioritize immediate delivery of these emails in the big chunk of emails. Is there any email client which supports this functionality in django python.? -
Search Box results within Modal
I am trying to build some search functionality within a modal. When a user clicks a button it will open a modal with a search box. I then want the results of the search to be shown within the same modal? <div class="modal" id="select2modal"> <div class="modal-dialog" role="document"> <div class="modal-content modal-content-demo"> <div class="modal-header"> <h6 class="modal-title">Search for product to add</h6><button aria-label="Close" class="close" data-dismiss="modal" type="button"><span aria-hidden="true">&times;</span></button> </div> <div class="modal-body"> <h6>product Search</h6> <div class="card-body pb-2"> <form method=POST action="{% url 'searchproduct' %}"> {% csrf_token %} <div class="input-group mb-2"> <input type="text" class="form-control border-right-0 pl-3" name="search" placeholder="Enter product Name" value=""> <span class="input-group-append"> <button class="btn ripple btn-primary" type="submit"><i class="fa fa-search"></i></button> </span> </div> </form> </div> </div> <div class="modal-footer"> <button class="btn ripple btn-primary" type="button">Add product</button> <button class="btn ripple btn-secondary" data-dismiss="modal" type="button">Close</button> </div> </div> </div> </div> view def search_product(request): searched = request.POST['searched'] return render(request, 'index.html',{'searched':searched}) I don't think i should be doing return render(request, 'index.html',{'searched':searched}) think I should just be returning searched The problem is this relies on the page being refreshed that closes the modal. So what is the correct way - Do I need to use JavaScript or something -
Django: making field form readonly (not working since I use django-crispy helper)
I try to customize my forms fields using django-crispy. But I can make my fields 'readonly'. Before using django-crispy FormHelper, I used disabled form field attribute and it works well. Now, I want to use django-cripy helper to render option buttons horizntally but disabled atribute do not works. I have tried using whidget attribute readonly but neither works. I also tried https://github.com/django-crispy-forms/django-crispy-forms/issues/47 solution but got an error Could not parse the remainder: ' form.pat readonly True' from 'crispy_field form.pat readonly True' When I display the template, eli_dat field is correctly disabled (readonly) but not eli_oui_ebo radio buttons... forms.py class EligibiliteForm(forms.ModelForm): def __init__(self, *args, **kwargs): self.IDE = kwargs.pop("ide", None) self.PATIENT = kwargs.pop("patient", None) self.USER = kwargs.pop("user", None) super(EligibiliteForm,self).__init__(*args, **kwargs) self.helper = FormHelper() self.helper.form_class = 'form-horizontal' self.helper.label_class = 'col-lg-7' self.helper.layout = Layout( 'pat', Field( AppendedText( 'eli_dat', mark_safe('<span data-feather="calendar"></span>'), ) ), InlineRadios('eli_oui_ebo'), ) if self.PATIENT == None: FORM_LOCK = Eligibilite.objects.get(ide = self.IDE).ver else: FORM_LOCK = False # Form can not be locked at creation **DISABLED = False** INITIAL = None if self.PATIENT != None: print("form - create") FORM_LOCK = False **DISABLED = False** INITIAL = Patient.objects.get(ide=self.PATIENT.ide) elif self.PATIENT == None and not FORM_LOCK: print("form - update not locked") **DISABLED = False** INITIAL = … -
I tried to use FileSystemStorage in django. I have a folder named "media". I am able to get single file url with typing name. help to get all files
from django.core.files.storage import FileSystemStorage #myCode def testHome(request): fs = FileSystemStorage() fileurl = fs.url('SnagItDebug.log') print(fileurl) context = { 'filelink':fileurl } return render(request, 'home.html', context) -
Django exported csv rows values changed with commas
I have a website that has some radio buttons that depending on which one you click it downloads one database table or another. I have made a Django view and then an Ajax function in Javascript. For some reason when I select one of the radio buttons and hit the download button, all the values of the csv are changed with something like ",,,,,". Does anyone know why this happens? My views.py: def download_db(request, mode): #data = JSONParser().parse(request) #serializer = WordsTableSerializer(data=data) response = HttpResponse(content_type='text/csv') writer = csv.writer(response) if mode == 1: writer.writerow(['session_id', 'word1', 'word2', 'word3','distance_to_word12','distance_to_word13', 'distance_to_word23']) for word in WordDifferentTable.objects.all().values_list('session_id', 'word1', 'word2', 'word3', 'distance_to_word12', 'distance_to_word13', 'distance_to_word23'): writer.writerow(word) response['Content-Disposition'] = 'attachment; filename="WordsDifferent.csv"' return response elif mode == 2: writer.writerow(['session_id', 'word1', 'word2', 'word3', 'distance_to_word12', 'distance_to_word13', 'distance_to_word23']) for word in LogicAnaloguiesTable.objects.all().values_list('session_id', 'word1', 'word2', 'word3', 'distance_to_word12', 'distance_to_word13', 'distance_to_word23'): writer.writerow(word) response['Content-Disposition'] = 'attachment; filename="ForLogicAnalogies.csv"' return response elif mode == 3: writer.writerow(['session_id', 'word1', 'word2', 'word3', 'distance_to_word12', 'distance_to_word13', 'distance_to_word23']) for word in SimilarWInContextTable.objects.all().values_list('session_id', 'word1', 'word2', 'word3', 'distance_to_word12', 'distance_to_word13', 'distance_to_word23'): writer.writerow(word) response['Content-Disposition'] = 'attachment; filename="ForSimilarWordInContext.csv"' return response elif mode == 0: writer.writerow(['session_id', 'word1', 'word2', 'word3']) for word in WordsTable.objects.all().values_list('session_id', 'word1', 'word2', 'word3'): writer.writerow(word) response['Content-Disposition'] = 'attachment; filename="WordsTable.csv"' return response return JsonResponse({}, status=304) The Ajax function: $( "#downloadbtn" ).click(function() … -
PermissionError: [WinError 32] The process cannot access the file because it is being used by another process (Python/Django)
I know this question has been asked quite a bit on here, however after trying a number of solutions I am unable to figure out how to fix this issue. I am downloading images from the Google Maps API to generate maps with and without markers. I am using django-cleanup to remove files when deleted from database however the old versions wont delete. Weirdly, django-cleanup works correctly and deletes the associated image when deleting from the Django Admin page but not when deleting the file directly i.e. in file explorer and says it is open in Python. It also deletes correctly when my local server is terminated as you would expect. Traceback is as follows: Traceback (most recent call last): File "C:\Users\Ricki.Demmery\Desktop\dev\acl_acousticapp\env\lib\site-packages\django_cleanup\handlers.py", line 97, in run_on_commit file_.delete(save=False) File "C:\Users\Ricki.Demmery\Desktop\dev\acl_acousticapp\env\lib\site-packages\django\db\models\fields\files.py", line 373, in delete super().delete(save) File "C:\Users\Ricki.Demmery\Desktop\dev\acl_acousticapp\env\lib\site-packages\django\db\models\fields\files.py", line 105, in delete self.storage.delete(self.name) File "C:\Users\Ricki.Demmery\Desktop\dev\acl_acousticapp\env\lib\site-packages\django\core\files\storage.py", line 304, in delete os.remove(name) PermissionError: [WinError 32] The process cannot access the file because it is being used by another process: 'C:\\Users\\Ricki.Demmery\\Desktop\\dev\\acl_acousticapp\\src\\acl_ac ousticapp\\media\\projects\\9335\\gmaps_markers_5xDqMnc.png' The call in views.py is as follows: gmaps = GoogleMapsAPI() gmaps.location_img(prjID) My Google Maps class def create_styled_marker(style_options={},mkr_lat=0,mkr_lng=0): opts = ["%s:%s" % (k, v) for k, v in style_options.items()] return '|'.join(opts) + '|{mkr_lat},{mkr_lng}|'.format(mkr_lat=mkr_lat, mkr_lng=mkr_lng) … -
Django app on Google App Engine slows down after 15 requests
I deployed a Django app on Google App Engine Standard with a F4 machine. The API is doing some machine learning and the processing has a duration of around 4s in local (between 3.5 and 4s). For my use case, it would be ok to have also 4-5s delays with the deployed app. However, when I test the deployed app doing the same request multiple times, I saw that the first requests take 3-4 seconds, but after 10-15 iterations, they take around 8s. Here is the code I used to test my app: session = requests.Session() all_times = [] for i in range(50): try: t0 = time.time() resp = session.post(url_api, headers=headers, json=data) t1 = time.time() print(t1 - t0) all_times.append(t1 - t0) except Exception as e: print("Err", e) The results of the request durations are as follows: I wonder why there is this gap after 15 requests and why some points are way above the average 7-8s (e.g. 10s). I get the same pattern looking at the latency in the Google Cloud Console: What I tried I tried to change the autoscaling parameters, thinking that it could be because of the creation of instances. But I got the same pattern when … -
Python virtual environment interpreter not working on VPS
I have Django project migrated using git migration. I managed to push my work to a VPS project directory (Ubuntu 20.04) following this guide: user@host:/var/www/project.com I have installed the database, up and running, and established a NGINX server block. Now the only thing is to start to run the manage.py Now I can't figure out why python command isn't working: (env) user@host:/var/www/project.com$ python manage.py runserver Error: -bash: env/bin/python: No such file or directory -bash: env/bin/python3: No such file or directory which python returns: /usr/bin/python which python3 returns: /usr/bin/python3 using ls -l env/bin shows: python -> python3.10 python3 -> python3.10 python3.10 -> /Library/Frameworks/Python.framework/Versions/3.10/bin/python3.10