Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
how to implement Applepay for django ecommerce website?
I want to implement applepay for django ecommerce website. How to implement applepay with django framework? -
Encoding issue when opening text file with Django url
I have a simple text file with accents in django media. The file is encoded in UTF8. When I open it with my browser (/home/xxx/my_django_app/media/changelog.txt), the accents are displayed. On the other hand, when I open it via django directly with the url (localhost:8000/media/changelog.txt), the accents are not displayed, as if the file was not in UTF 8. How to solve this problem ? -
replace 'Null' with zero in python
I'm replacing Null or None with zero when there is a value I want to show the value in Django Even when there is a value for the 'Requester' in SQL it still showing as zero. In SQL, I'm getting 'Requester' value as 5 but still it's showing as 0. I don't know where I'm going wrong Here, what I tried @apiview(['GET']) def GetCurrentRunningActivityAudit(UserID): if request.method == 'GET': cursor = connection.cursor() cursor.execute('EXEC [dbo].[sp_GetCurrentRunningActivityAudit] @UserId=%s',(UserID,)) result_set =cursor.fetchall() IsActive = 'true' data = [] for row in result_set: TaskId = row[0] data.append({ 'TaskId':row[0], 'TaskName' : row[1], 'Source' : row[2], 'Requester' : 0 if row[3] == 'NULL' or 'NONE' else row[3], 'type' : row[4], }) return Response(data[0], status=status.HTTP_200_OK) return Response(data) -
Import model methods in other model
I'm using Django Rest Framework for API where I need to use methods from one model into another. But, this results in ImportError: cannot import name '...' from partially initialized module '...' (most likely due to circular import) My models samples are as follows: Model A from ..B.models import B Class A: @classmethod def foo(): b = B() b.bar() Model B from ..A.models import A Class B: @classmethod def bar(): a = A() a.foo() I understand the error is being caused to due to ciruclar import. Is there any way to import methods in each other's model? -
Can't Upload Image to ImageField through csv file
My Django application: In my model, I use ImageField to allow the upload of images. In my csv file I have an image path for an image like this: C:/Users/blah/DjangoProject/abc/abc/csvs/photos/product_1/product-1_1.jpg In my csv's view I got: Product.objects.create(product_name=row[0], slug=row[0].lower().replace(' ', '-'), product_description=row[1], price=row[7], image_1=ImageFile(open(row[8], 'rb'))) The row[8] contains the image's path. When I'm going to my csv.html using Django's FileField to upload csv file which contain the image's path and product's info, after uploading the product should be created in my database which image should also be uploaded to a filesystem - not storing in database. Instead, I got this error: OSError at /csvs/ [WinError 123] The filename, directory name, or volume label syntax is incorrect: 'C:\Users\blah\DjangoProject\abc\abc\media\photos\products\C:' When I removed the image_1 row in Product.objects.create(), the product was uploaded and added to the database successfully. If I restore the image_1 row in the object creation, I got the same error again. Does anyone know why? -
Set JWT access token
which one is better and why : set JWT token in request headers by frontend developers or set in cookie by backend developers ? -
Django, save only resized image, not the original
So I have this model in my Django project: class Image(models.Model): image = ... def save(self, *args, **kwargs): super().save(*args, **kwargs) ... # resizing and saving the image Just a simple model with ImageField. I wonder how to save only resized images. As I know "super().save(*args, **kwargs)" saves the original image with its original sizes. But it takes too long to save for example 10-15 MB photo. In my resizing logic the image is compressed and resized to about 1-3 MBs. And I want to save in my MEDIA root only this resized image and not the original one. I don't want the original image even appear in my project (it takes way too long to process this image while saving). How to avoid "super().save(*args, **kwargs)"? Hope you got it, thanks in advance! Any suggestions are appreciated! -
Django set a connection proxy
I have long time seeking for a solution to set a proxy for my Django application. 1st I am using Django==2.0 and I run it in Windows Server 2016 in a local network that uses a Proxy to connect 10.37.235.99 and Port 80. and I'm deploying the application using nginx-1.20.1 I have to scrape a data as http_proxy = "10.37.235.99:80" https_proxy = "10.37.235.99:80" ftp_proxy = "10.37.235.99:80" proxyDict = { "http" : http_proxy, "https" : https_proxy, "ftp" : ftp_proxy } import socket if socket.gethostname() == "localhost": os.environ["PROXIES"] = proxyDict else: os.environ["PROXIES"] = {} URL='my_site.com' page = requests.get(URL) print(page) I tried many solutions on the internet but no way! Working with django : Proxy setup when I remove the proxy configuration and I use Psiphon3(with proxy) everything works perfectly. is there any solution? -
manage.py runworker: error: the following arguments are required: channels
we have a chat application with daphne and Redis servers. web socket is working when there are few requests but as requests increase we start to get 503 error and the connection closed out. We are trying to run daphne on workers with the below command. (venv) expert@expert-X542UQ:~/PycharmProjects/Asktalos/asktalos$ python manage.py runworker but we are getting an error message saying it requires channels parameter. usage: manage.py runworker [-h] [--layer LAYER] [--version] [-v {0,1,2,3}] [--settings SETTINGS] [--pythonpath PYTHONPATH] [--traceback] [--no-color] [--force-color] [--skip-checks] channels [channels ...] manage.py runworker: error: the following arguments are required: channels can anyone help with what channels parameter needs to pass here? below is our docker-compose file for Redis and daphne images. version: "3" services: redis: image: redis:alpine ports: - "6379:6379" networks: - backend daphne: build: . image: "channel_prod:latest" working_dir: /code/ command: bash -c "daphne -b 0.0.0.0 -p 9542 Bot.asgi:application" networks: - backend ports: - "9542:9542" environment: - DJANGO_SETTINGS_MODULE=Bot.settings depends_on: - redis links: - redis worker: build: . command: python3 manage.py runworker channel_layer links: - redis depends_on: - redis networks: backend: driver: bridge -
How to pass variable into Django block in url?
Context I am trying to loop through a list of objects, then call on the name and id attribute and pass it into the Url block as regex to be captured in the urls.py later. Problem {%if people_found%} {%for the_people in people_found%} <a href="{% url 'Search4Bday:profile' '{{the_people.firstname}}/ {{the_people.id}}' %}">{{the_people.firstname}}</a> {%endfor%} {%endif%} Urls.py app_name = 'Search4Bday' urlpatterns= [path("search/profile/<str:firstname>/<int:id>", views.profile, name = "profile")] Question I'm not sure how I can pass the variables into the urls.py file if I can't call on the variable the_people with double curly braces. I'm also not sure if this is the correct way to pass in the variables into the regular expression capture portion of the urls.py. Any ideas? -
django.db.utils.ProgrammingError: relation "#" does not exist
Hi I made some changes to my Django app, and migrating them gives the error message-- django.db.utils.ProgrammingError: relation "#" does not exist Changing my database server works, but I have a lot of data on my original server which I can't lose. Is there any way around it? I have been on this for hours without any solution. -
Is there a way to disable throttling while using Pytest in Django?
Problem: I want to figure out a way to disable throttling when running my tests with pytest -vv Details: I have this default throttling policy in my settings.py file: 'DEFAULT_THROTTLE_RATES': { 'anon': '100/day', 'user': '1000/day' } I also have this fixture in my confest.py which returns an error whenever I exceed the limit of requests: def get_token(user, client): response = client.post( "/email-login", {"email":user.email, "password": "B9vX95phJDi3C4"}, ) return { "HTTP_AUTHORIZATION": f"Bearer {response.json()['token']['access']}" } What I have tried: I have attempted to use the solution in this GitHub Issue: https://github.com/encode/django-rest-framework/issues/1336, but it doesn't work in my case. -
Javascript/Django: change icon on dynamically created element based on query value or click
I have tried couple of ways to get icon to change on a button, that has been created with for loop on page load. Here is my element: {% for i in data %} <div class="accordion"> <div style="margin-left: -10px;"> <a href="#collapse{{ i }}", class="btn", role="button", data-bs-toggle="collapse" id="btn-collapse_{{ i }}"> <i class="material-icons" style="vertical-align: middle;">expand_more</i> <label style="vertical-align: middle;">{{ i }}</label> </a> </div> </div> {% endfor %} Here is my function to change the icon: <script> $(document).ready(function(){ $('#btn-collapse_{{ i }}').on('click', function () { var thisElement = $(this); var anchorElement = thisElement.find("i"); if(anchorElement.text() === "expand_less"){ anchorElement.text('expand_more'); } else { thisElement.find("i").text("expand_less"); } }); }); </script> I've also tried changing the color in in another instance. Heres the element: <tbody> {% for i in data %} <tr style="vertical-align: middle;"> <td><a href="#">{{ i }}</a></td> <td>{{ i.data1 }}</td> <td><a href="#">{{ i.data1 }}</a></td> <td style="text-align: center;"> <button class="btn", id="btn-{{ i.data2 }}"> <i class="far fa-check-circle"></i> </button> </td> <td style="text-align: center;"> <button class="btn", id="btn-{{ i.data3 }"> <i class="far fa-check-circle"></i> </button> </td> </tr> {% endfor %} </tbody> And here is the function: <script> $(document).ready(function(){ var data_button = document.getElementById("btn-{{ i.data2 }}"); if({{ i.data2 }} == 'None'){ data_button.style.color = "#858796"; } else { data_button.style.color = "#1cc88a"; } }); </script> Data that is being queried … -
Using foreignkey in a select form element pulls data but in the database it is null
I am building an app in Django. I have a couple of models as defined below id = HashidAutoField(primary_key=True, salt='ClientBgColor' + settings.HASHID_FIELD_SALT) color = models.CharField(max_length=10, blank=True, null=True) def __str__(self): return self.color class Client(models.Model): id = HashidAutoField(primary_key=True, salt='Client' + settings.HASHID_FIELD_SALT) company_name = models.CharField(max_length=100, blank=True, null=True) contact_name = models.CharField(max_length=100, blank=True, null=True) contact_email = models.EmailField(max_length=100, blank=True, null=True) phone = models.CharField(max_length=100, blank=True, null=True) address = models.CharField(max_length=100, blank=True, null=True) country = models.CharField(max_length=100, null=True, blank=True) city = models.CharField(max_length=100, null=True, blank=True) logo = models.ImageField(upload_to='clients/logo/', blank=True, null=True) created_on = models.DateTimeField(auto_now_add=True) created_by = models.ForeignKey(User, on_delete=models.CASCADE, blank=True, null=True) def __str__(self): template = '{0.company_name}' return template.format(self) class ProjectType(models.Model): id = HashidAutoField(primary_key=True, salt='ProjectType' + settings.HASHID_FIELD_SALT) name = models.CharField(max_length=100, blank=True, null=True) def __str__(self): template = '{0.name}' return template.format(self) class Project(models.Model): id = HashidAutoField(primary_key=True, salt='Project' + settings.HASHID_FIELD_SALT) project_name = models.CharField(max_length=100, blank=True, null=True) client = models.ForeignKey('Client', on_delete=models.CASCADE, related_name='clientProjects') created_on = models.DateTimeField(auto_now_add=True) description = models.TextField(null=True, blank=True) project_type = models.ForeignKey('ProjectType', on_delete=models.CASCADE, related_name='typeOfProject', blank=True, null=True) last_updated = models.DateTimeField(auto_now_add=True) created_by = models.ForeignKey(User, on_delete=models.CASCADE, blank=True, null=True) def __str__(self): return self.project_name in the forms.py file, from dataclasses import fields from django import forms from app.models import * class NewProjectForm(forms.ModelForm): project_name = forms.CharField( label = '', widget=forms.TextInput(attrs={ 'id' : '', 'class' : 'form-control form-control-lg', 'placeholder' : 'Project name' }) ) client = … -
Django: How to order by model field name, then by its reverse queryset's first entry and field?
I'm using Postgres as the db backend. I have a Load that has multiple Stops, which each Load assigned to a Carrier. Each Stop has an appointment through a DateTimeField. I'm trying to sort all Loads by Carrier's company_name, then by the Stop's appointment. Table to illustrate Shipment # | Carrier | 1st Appointment Time 10001 | ABC Freight | 01/01/2023 17:00 10002 | ABC Freight | 01/01/2023 20:00 90001 | XYZ Freight | 01/01/2023 08:00 90002 | XYZ Freight | 01/01/2023 11:00 First solution from the shell: from app.models import Load Load.objects.all().order_by('carrier__company_name', 'stops__appointment') Problem: It returns duplicate entries of the Loads queryset. When I try to add .distinct('id') the following error occurs SELECT DISTINCT ON expressions must match initial ORDER BY expressions LINE 1: SELECT DISTINCT ON ("app_load"."id") "app_load"."id", "app_l... What query functions would I need to combine to get this result? models.py class Load(models.Model) shipment = models.CharField(max_length=100, blank=True) carrier = models.ForeignKey(Carrier, blank=True) class Carrier(models.Model): company_name = models.CharField(max_length=100) class Stop(models.Model): load = models.ForeignKey(Load, on_delete=models.CASCADE, related_name='stops') appointment = models.DateTimeField(blank=True, null=True) -
DRF's not calling post() method when receiving POST request
I have a viewset like this: class MyViewSet(CreateAPIView, RetrieveModelMixin, ListModelMixin, GenericViewSet): queryset = MyModel.objects.all() serializer_class = MySerializer def post(self, request, *args, **kwargs): import pdb; pdb.set_trace() class MySerializer(serializers.HyperlinkedModelSerializer): class Meta: model = MyModel fields = ['id', 'field1', 'field2'] #only field1 is required in the model The GET requests for list, and retrieve works perfectly. When I make a POST request, sending the field1 I get a status 201 and a new record is added to the database, so it works too. But my method MyViewSet.post() that should overwrite the same one from generics.CreateAPIView never gets called. Not only that, but I've tried to add the pdb.set_trace(), literally inside the generics.CreateAPIView.post() and in the CreateModelMixin.create() functions and neither stopped once I made the POST request. So something else is handling this POST request and inserting into the DB, I just don't know what. And how can I overwrite it, so I can customize what should be done with a post request? PS.: Also, I don't think it's a routing problem, my urls.py: from rest_framework import routers from myapp.views import MyViewSet, AnotherViewSet router = routers.DefaultRouter() router.register(r'route_one', MyViewSet) router.register(r'route_two', AnotherViewSet) -
django error (no such column: projects_review.project_id)
i cant open my review table here's the models code class Project(models.Model): title = models.CharField(max_length=200) description = models.TextField(null=True, blank=True) demo_link = models.CharField(max_length=2000, null=True, blank=True) source_link = models.CharField(max_length=2000, null=True, blank=True) tags = models.ManyToManyField('Tag', blank=True) vote_total = models.IntegerField(default=0, null=True, blank=True) vote_ratio = models.IntegerField(default=0, null=True, blank=True) created = models.DateTimeField(auto_now_add=True) id = models.UUIDField(default=uuid.uuid4, unique=True, primary_key=True, editable=False) def __str__(self): return self.title and this is the review model class Review(models.Model): VOTE_TYPE = ( ('up', 'Up Vote'), ('down', 'Down Vote'), ) project = models.ForeignKey(Project, on_delete=models.CASCADE) body = models.TextField(null=True, blank=True) value = models.CharField(max_length=200, choices=VOTE_TYPE) created = models.DateTimeField(auto_now_add=True) id = models.UUIDField(default=uuid.uuid4, unique=True,primary_key=True, editable=False) def __str__(self): return self.title but i cant open my review table on admin table (OperationalError at /admin/projects/review/) -
Is there a way to save an image using cv2.imwrite() function in django models?
I am trying to save the resized images from the views.py in django using opencv but I could not save the image from views.py. I want to generate images using cv2.imwrite() inside the views and save it directly from the views instead of saving it from django admin dashboard. Code to create image in views.py models.py -
Troubles with django ORM, when i filter a model instance, the filter apparently isn't work like have to be
My environment Django version = 4.0.4 Python == 3.9.12 os = osx I'm confused when I'm trying to make a filter on a model using a customized template tag in this way @register.filter def cart_item_count(user): if user.is_authenticated: qs = Order.objects.filter(user=user, ordered=False) print(qs.ordered) if qs.exists(): return qs[0].items.count() else: return 0 return 0 but even when i say in the filter that i just want the ordered=False, i make a print to ensure what value have my queryset and its prints to me True, why of this behavior? It's always returning to me a true ordered order, but I want to just take that have the ordered false, because I want to show in my cart an empty cart after making the checkout POST for redirect to home o other view and update for me to an empty new cart, pls if someone can help me even with an article post about it and explain to me what I'm doing wrong, thanks! -
Django Middleware: RecursionError when accessing `self.request.user` in database query wrapper
I'm testing my database query middleware (Django docs here) on a sample django app with a Postgres db. The app is the cookiecutter boilerplate. My goal with the middleware is simply to log the user ID for all database queries. Using Python3.9 and Django3.2.13. My middleware code is below: # Middleware code import logging import django from django.db import connection django_version = django.get_version() logger = logging.getLogger(__name__) class Logger: def __init__(self, get_response): self.get_response = get_response def __call__(self, request): with connection.execute_wrapper(QueryWrapper(request)): return self.get_response(request) class QueryWrapper: def __init__(self, request): self.request = request def __call__(self, execute, sql, params, many, context): # print(self.request.user) return execute(sql, params, many, context) If print(self.request.user.id) is commented out, everything works fine. However, I've found that uncommenting it, or any type of interaction with the user field in the self.request object, causes a Recursion Error: RecursionError at /about/ maximum recursion depth exceeded Request Method: GET Request URL: http://127.0.0.1:8000/about/ Django Version: 3.2.13 Exception Type: RecursionError Exception Value: maximum recursion depth exceeded Exception Location: /opt/homebrew/lib/python3.9/site-packages/django/db/models/sql/query.py, line 192, in __init__ Python Executable: /opt/homebrew/opt/python@3.9/bin/python3.9 Python Version: 3.9.13 In the error page, that is followed by many repetitions of the below error: During handling of the above exception ('SessionStore' object has no attribute '_session_cache'), another exception … -
NoReverseMatch at / Reverse for 'homepage' not found. 'homepage' is not a valid view function or pattern name - django
i was tried to upload data but suddenly got error message : i was already makemigrations and migrate it. here's my code views.py : def homepage(request): form = AudioForm() audio = Audio_store.objects.all() if request.method == "POST": form = AudioForm(request.POST, request.FILES) if form.is_valid(): form.save() return redirect("homepage") context={'form':form, 'audio':audio} return render(request, "homepage.html", context=context) urls.py : urlpatterns = [ url(r'^admin/', admin.site.urls), url(r'^decode/$', views.decode), url(r'^$', views.homepage), path('audio', views.Audio_store), ] i dont't know how it fix it. please help me -
Print Django model data as JavaScript Array
I have printed a for loop as below in my HTML Template: {% for athlete in booking.athlete.all %} {{ athlete.id }} {% endfor %} The Output in HTML is as below. <td> 1 2 3 </td> Is it possible to get the output to appear as [ "1", "2", "3" ], so we can then use this as a JS array or object? I have tried a few things from the Django Template but it does not remove the additional white space. -
how to conntect this python file to django file ? Please tell me what shoud i do next ? im creating face recognition using opencv in django
import cv2 from time import sleep def capturewebcam(image): key = cv2. waitKey(1) webcam = cv2.VideoCapture(0) sleep(2) while True: try: check, frame = webcam.read() print(check) # prints true as long as the webcam is running print(frame) # prints matrix values of each framecd cv2.imshow("Capturing", frame) key = cv2.waitKey(1) if key == ord('s'): cv2.imwrite(filename='studnet_images/saved_img.jpg', img=frame) webcam.release() print("Processing image...") img_ = cv2.imread('saved_img.jpg', cv2.IMREAD_ANYCOLOR) print("Image saved!") break elif key == ord('q'): webcam.release() cv2.destroyAllWindows() break except(KeyboardInterrupt): print("Turning off camera.") webcam.release() print("Camera off.") print("Program ended.") cv2.destroyAllWindows() break i tried so many times bt i cant understand. Please help me to reslove the problem. -
How to get field value in django Model?
I have this code class Book(models.Model): name = models.CharField(max_length=70) author = models.CharField(max_length=70) rating = models.IntegerField(default=None) volume = models.IntegerField(null=True, default=None) annotation = models.TextField(default=None) year = models.IntegerField() I want to get a value from field right in class. For example, "Harry Potter" for name. I don't find method to do it. -
selenium: Max retries exceeded with url
Full traceback: Traceback (most recent call last): File "/home/webadmin/dev.taracares.com/src/app_payroll_reports/tests.py", line 134, in test_mstnla_sums_incentives_tennessee_sum int(quince_amount_cell.text.replace(',', '')) + File "/home/webadmin/dev.taracares.com/dev/lib/python3.8/site-packages/selenium/webdriver/remote/webelement.py", line 77, in text return self._execute(Command.GET_ELEMENT_TEXT)['value'] File "/home/webadmin/dev.taracares.com/dev/lib/python3.8/site-packages/selenium/webdriver/remote/webelement.py", line 710, in _execute return self._parent.execute(command, params) File "/home/webadmin/dev.taracares.com/dev/lib/python3.8/site-packages/selenium/webdriver/remote/webdriver.py", line 423, in execute response = self.command_executor.execute(driver_command, params) File "/home/webadmin/dev.taracares.com/dev/lib/python3.8/site-packages/selenium/webdriver/remote/remote_connection.py", line 333, in execute return self._request(command_info[0], url, body=data) File "/home/webadmin/dev.taracares.com/dev/lib/python3.8/site-packages/selenium/webdriver/remote/remote_connection.py", line 355, in _request resp = self._conn.request(method, url, body=body, headers=headers) File "/home/webadmin/dev.taracares.com/dev/lib/python3.8/site-packages/urllib3/request.py", line 74, in request return self.request_encode_url( File "/home/webadmin/dev.taracares.com/dev/lib/python3.8/site-packages/urllib3/request.py", line 96, in request_encode_url return self.urlopen(method, url, **extra_kw) File "/home/webadmin/dev.taracares.com/dev/lib/python3.8/site-packages/urllib3/poolmanager.py", line 375, in urlopen response = conn.urlopen(method, u.request_uri, **kw) File "/home/webadmin/dev.taracares.com/dev/lib/python3.8/site-packages/urllib3/connectionpool.py", line 783, in urlopen return self.urlopen( File "/home/webadmin/dev.taracares.com/dev/lib/python3.8/site-packages/urllib3/connectionpool.py", line 783, in urlopen return self.urlopen( File "/home/webadmin/dev.taracares.com/dev/lib/python3.8/site-packages/urllib3/connectionpool.py", line 783, in urlopen return self.urlopen( File "/home/webadmin/dev.taracares.com/dev/lib/python3.8/site-packages/urllib3/connectionpool.py", line 755, in urlopen retries = retries.increment( File "/home/webadmin/dev.taracares.com/dev/lib/python3.8/site-packages/urllib3/util/retry.py", line 574, in increment raise MaxRetryError(_pool, url, error or ResponseError(cause)) urllib3.exceptions.MaxRetryError: HTTPConnectionPool(host='localhost', port=58331): Max retries exceeded with url: /session/0f8192d1-c39f-49d1-9a99-7f91dfe95481/element/a5dd2645-6c15-44dc-b000-04bf6b7ea6cb/text (Caused by NewConnectionError('<urllib3.connection.HTTPConnection object at 0x7fd9dcde24f0>: Failed to establish a new connection: [Errno 111] Connection refused')) This is code being run in tests for a django application. The tests used to run fine, now the last 4 tests (which use selenium) have errors, which started after I added driver.quit() after each test. …