Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
timedata does not match format even though they are identical
Issue: ValueError: time data '2024-05-26 18:00' does not match format 'YYYY-MM-DD HH:mm' I use DRF to fetch POST for api/reservations/. But Django complained that str cannot be passed to DateTimeField. So I tried to format str into proper datetime. But even though the string and format are exactly identical, various method still complain about something unknown by me. Code: def create(self, validated_data): validated_data.update({ 'reservation_time': datetime.datetime.strptime(validated_data.get('reservation_time'), 'YYYY-MM-DD HH:mm').date() }) return self.Meta.model(**validated_data) I was trying to change datetime format via JS to "YYYY-MM-DDThh:mm[:ss[.uuuuuu]][+HH:MM|-HH:MM|Z]." (point a the end is a part of format and not a typo) and do so in Python, no progress. Tried django.utils.dateparse.parse_date as well, as datetime.datetime.strptime. parse_date returned None, meaning, something is wrong with format and strptime raises ValueError above. What am I missing? -
Django app 404 error not recognizing new apps url and views
Hi I am trying to create my first Django project and having issues getting an app to work inside my Django project. I simply am trying to map the url code 8000/home1/hello/ to display the basic text "hello world" but failing to do so. I keep getting this error code: Using the URLconf defined in web3.urls, Django tried these URL patterns, in this order: admin/ The current path, home1/hello, didn’t match any of these. but still can not figure out why my code is not working.... Here is what I have done: created a django project named web3 created an app called home1 and added a urls.py file to this app updated the settings.py folder INSTALLE_APPS to have 'home1.apps.Home1Config', home1 > urls.py includes this code: from django.urls import path from . import views `urlpatterns = [ path('hello/', views.hello_world, name="hello_world"), ] ` home1>views.py includes this code: ` from django.shortcuts import render from django.http import HttpResponse def hello_world(request): return HttpResponse("you finally did it justin")` 6.web3> urls.py includes this code: `from django.contrib import admin from django.urls import path, include from home1.views import hello_world # Import the hello_world view function urlpatterns = [ path('admin/', admin.site.urls), path('', include('home1.urls')), ] ` I am pretty confident my … -
No DATABASE_URL environment variable set, and so no databases setup
While Deploying Django website on AWS EC2 server i am getting error No DATABASE_URL environment variable set, and so no databases setup. I Created a gunicon.service file on my server location /home/ubuntu/lighthousemedia/LightHouseMediaAgency and set EnvironmentFile=/home/ubuntu/lighthousemedia/LightHouseMediaAgency/.env to get the environment variables and in the same location i created a .env file which contain the DATABASE_URL = postgresql://postgres:password@lighthousemediadb.crte3456.ap-south-1.rds.amazonaws.com:5432/dbname. I believe that .env file is in the correct location. Also check my DATABASE is set correctly. production.py DATABASES = { 'default': { 'ENGINE': 'django.db.backends.postgresql_psycopg2', 'NAME': 'lighthousemediadb', 'USER': "postgres", 'PASSWORD': os.environ.get('DB_PASSWORD'), # dont keep it hardcoded in production 'HOST': os.environ.get('DB_HOST'), 'PORT': '5432', # add these too it improve performance slightly 'client_encoding': 'UTF8', 'default_transaction_isolation': 'read committed', 'timezone': 'UTC' } } import dj_database_url db_from_env = dj_database_url.config() DATABASES['default'].update(db_from_env) DATABASES['default']['CONN_MAX_AGE'] = 500 gunicorn.service [Unit] Description=gunicorn daemon Requires=gunicorn.socket After=network.target [Service] User=ubuntu Group=www-data EnvironmentFile=/home/ubuntu/lighthousemedia/LightHouseMediaAgency/.env WorkingDirectory=/home/ubuntu/lighthousemedia/LightHouseMediaAgency ExecStart=/home/ubuntu/lighthousemedia/.venv/bin/gunicorn \ --access-logfile - \ --workers 3 \ --bind unix:/run/gunicorn.sock \ BE.wsgi:application [Install] WantedBy=multi-user.target .env SECRET_KEY = 'epmxxxxxxxxxxxxu$0' DEBUG = True ALLOWED_HOSTS = '3.196.58.181', 'abc.com', 'localhost', '127.0.0.1' DB_PASSWORD = 'password' DB_HOST = 'lighthousemediadb.crte3456.ap-south-1.rds.amazonaws.com' DATABASE_URL = postgresql://postgres:password@lighthousemediadb.crte3456.ap-south-1.rds.amazonaws.com:5432/dbname -
Order Django QuerySet by where a term appears in results
I'm trying to implement an autocomplete for an input field using Django and jQuery (user searches for a food from a menu). The problem is figuring out how to order the results. If, for example, the user types "Fish", I want the autocomplete to be ordered like this: "Fish and Chips" "Fish fry" "Fried fish" "Fried catfish" So results would be ordered primarily by where the search term appears in the name, then in alphabetical order after that. My QuerySet is currently retrieved in Django with views.py def load_menu(request): term = request.GET['term'] # the search term typed by user menu = Menu.objects.filter(item__icontains=term).order_by('item', 'id') # item = name of food # constructing JSON response data = [] for item in menu: item = { 'label': item.item, 'value': item.id, } data.append(item) return JsonResponse({'data': data}) # received by jQuery function to display autocomplete menu but that orders results alphabetically only, which I don't want. How can I order like I specified in the example above? -
Error while digitally Singing on multiple pages in a pdf using python endesive
I'm trying to digitally sign the pdf document using Class 3 USB token by searching a specific text 'Authorised Signatory' in the page, it works perfectly fine when i have to sign a pdf once. But in one of my scenario i came across multiple page document and in which i have to sign each page, After signing the pdf when i tried to validate the signatures in the Adobe pdf reader it has only validated my first signature as shown in the below screenshot And I was not able to see the annotations of the second and third page. Here is my code, def post(self, request): serializer = PDFSignSerializer(data=request.data) if serializer.is_valid(): data = serializer.validated_data.get('pdf_base64') try: pdf_data = base64.b64decode(data) except Exception as e: return Response({'error': f'Failed to decode base64 PDF data: {e}'}, status=status.HTTP_400_BAD_REQUEST) # Search for text in the PDF and retrieve coordinates text_to_find = 'Authorised Signatory' # Text to search for (modify as needed) text_positions = self.find_text_in_pdf(pdf_data, text_to_find) if not text_positions: return Response({'error': 'No position found for signature'}, status=status.HTTP_400_BAD_REQUEST) # Get the current UTC time using timezone-aware objects current_utc_time = datetime.datetime.now(datetime.timezone.utc) # Calculate the Indian time by adding the UTC offset of +5:30 indian_time = current_utc_time + datetime.timedelta(hours=5, minutes=30) … -
Adding a 24-hour timer for each item added to a cart
I'm trying to add a 24-hour time limit for each item added to a cart. I want the items removed from the cart after the time expires. const isExpired = (timestamp) => { const now = new Date().getTime(); const oneDay = 24 * 60 * 60 * 1000; return now - timestamp > oneDay; }; const removeExpiredItems = () => { for (let productId in cart) { if (isExpired(cart[productId].addedAt)) { delete cart[productId]; } } }; -
Conditional Caching when Looping Through Blocks in Django
On our site, we are looping through wagtail blocks for many of our webpages. Some of those blocks contain webforms or dynamic/personalized data, and thus cannot be cached. We want to provide maximum flexibility for the editors to update webpages without needing to touch the code, but also to provide good performance and load times. In the below code, the field page.body is a wagtail streamfield where the editors can add any number of content blocks and in any order. Here is the desired solution, with simplified code, which fails: {% load cache wagtailcore_tags %} <!-- Start the page cache --> {% cache timeout url_path %} {% for block in page.body %} <!-- disable the cache before an excluded block --> {% if block.disable_cache %} {% endcache %} <!-- template engine throws an error at this "endcache" tag --> {% endif %} {% include_block block %} <!-- reenable the cache after an excluded block is rendered --> {% if block.disable_cache %} {% cache timeout block.uuid %} {% endif %} {% endfor %} <!-- end the page cache --> {% endcache %} Let's say a page has 15 blocks, with a single block in the middle having a form that should … -
DRF test user sign-in, error inactive user
I have view for authentfication: class UserViewSet(viewsets.ViewSet): @method_decorator(sensitive_variables("password")) @action(url_path="sign-in", detail=False, methods=["POST"]) def sign_in(self, request: HttpRequest) -> Response: if not request.user.is_anonymous: return Response({"status": "forbidden"}, status=403) form = AuthenticationForm(data=request.data) print(form.data) if form.is_valid(): user = authenticate(request, **form.cleaned_data) login(request, user) return Response({"status": "ok"}, status=200) print(form.error_messages) raise ValidationError(form.errors) I write the test: class UserTest(TestCase): @classmethod def setUpClass(cls): User.objects.create(username="admin", password="Qwerty1234", is_active=True) super().setUpClass() cls.client = Client() @classmethod def tearDownClass(cls): return super().tearDownClass() def test_sign_in(self): url = "/api/sign-in/" print(User.objects.get(username="admin").is_active) response = self.client.post( url, data={"username": "admin", "password": "Qwerty1234"}, content_type="application/json", ) But, I receive the errors from form form_validator: {'invalid_login': 'Please enter a correct %(username)s and password. Note that both fields may be case-sensitive.', 'inactive': 'This account is inactive.'} What can be a problem? P.S. At that case, is there any sense to use sensitive_variables? Thx! -
Reading query string in Wagtail
I am new to Wagtail and I am trying to work out how to extract the query string as part of the FormPage model. In models.py I tried: def get_context(self, request): context = super().get_context(request) context['embed'] = request.GET.get('embed') return context But I'm not 100% how to call this in my FormPage model to include this in the email that will be sent when a form is submitted. I've tried to add the following to the FormPage model: def get_context(self, request): context = super().get_context(request) context['embed'] = request.GET.get('embed') return context -
django firebase-admin 403 Received http2 header with status: 403
I am facing a problem creating firebase notifications with firebase-admin in django. After initiating with credentials server responses with code 403. This problem occurs only in production (Ubuntu 22.04, django 3.2.4, firebase-admin 6.5.0), but in my local machine everything works fine. Which permissions should I use for server account? This is my code try: app = firebase_admin.get_app() except: cred = credentials.Certificate('static/service-key.json') firebase_admin.initialize_app(cred) try: if to_user: db = firestore.client() doc_ref = db.collection('Users').document(to_user) doc = doc_ref.get() if doc.exists: message = messaging.Message( notification=messaging.Notification( title='title', body='body' ), data={ 'type': 'message' }, token=doc.to_dict()['token'] ) messaging.send(message) except Exception as e: print(e) -
How to access token from headers django/react
In my backend I use set_cookie to set a access token that i need to access in my frontend. but im not able to My backend using django # Authentication successful access_token = AccessToken.for_user(user) refresh_token = RefreshToken.for_user(user) response = JsonResponse({'message': 'Login successful', 'tire_stock': tire_stock_data}) # Set HTTP-only flag for both access and refresh tokens response.set_cookie('access_token', str(access_token), secure=True) response.set_cookie('refresh_token', str(refresh_token), httponly=True, secure=True) return response my frontend using react const response = await axios.post( `${import.meta.env.VITE_URL}auth/login/`, { username: username, password: password }, { headers: { "Content-Type": "application/json" }, withCredentials: true, } ); the response header enter image description here i have tried response.headers['access_token'] which returned undefined i also tried document.cookie which didnt work. i read online that i need to expose header to access it? not sure how to do that on django. ChatGPT said i dont need to expose header. I was thinking to pass token in body which would solve it but thats not industry standard since tokens should usually be in headers. so im not sure how to go about it ? i showed the sameSite issue incase its relevent which i dont think since when going on Chrome devtools application/cookies i see the tokens there so theyre being set … -
Django mysql queries slow, direct mysql client queries usually fast
I'm having an issue with slowness in my Django project caused by slow mysql queries. Cut and paste the query from the Django log, execute it via the mysql client (to the same database, from same server project is on) and usually they are quite fast. So say regularly 5 secs from DJango .20 seconds via mysql client (again to same db, from same server) typical result. Sometimes I will see it slow from mysql client, usually the first time it's tried if it's going to happen. I can try it again even 20 minutes later and it will still be fast typically. Say it just executed fast via mysql client, if I immediately execute it via the problem Django http request, it will still be slow. Debug is off for Django. I can reproduce this problem across mysql server versions. Production server and database are under very light use and have good resources available. I've tried totally recreating the database same issue. I tried using django-db-connection-pool with no effect. I've tried profiling and stepping into the code to make sure it's the query, it is. Slow query log is not showing these problem queries, though I'm not sure how … -
Why doesn't 'profile/<int:pk>' work in django
I'm new to django. I have a problem with profiles. When I open the main page or others I get knocked out in error: NoReverseMatch at / Reverse for 'profile' with arguments '('',)' not found. 1 pattern(s) tried: ['registration/profile/(?P<pk>[0-9]+)\\Z'] I do not know what to do with it. Boom is very grateful for the help! here is the code: models.py: import os.path from PIL import Image from django.contrib.auth.models import User from django.db import models from django.conf import settings from django.db.models.signals import post_save from django.dispatch import receiver class reg(models.Model): email = models.CharField('email', max_length=50) password1 = models.CharField('password1', max_length=20) password2 = models.TextField('password2') def __str__(self): return self.email class Meta: verbose_name = 'registration' verbose_name_plural = 'registration' class UserProfile(models.Model): user = models.OneToOneField(User, primary_key=True, verbose_name='user', related_name='profile', on_delete=models.CASCADE) name = models.CharField(max_length=20, blank=True, null=True) bio = models.TextField(max_length=500, blank=True, null=True) birth_date = models.DateField(null=True, blank=True) location = models.CharField(max_length=100, blank=True, null=True) picture = models.ImageField(upload_to='media/images', default='media/default.jpg', blank=True) urls.py: from django.contrib.auth import views as auth_views from django.urls import path from . import views from .views import ProfileView from django.conf.urls.static import static from django.conf import settings urlpatterns = [ path('register/', views.register, name='register'), # Remove leading slash from '/register' path('login/', auth_views.LoginView.as_view(), name='login'), path('logout/', auth_views.LogoutView.as_view(), name='logout'), path('profile/<int:pk>', ProfileView.as_view(), name='profile'), ] if settings.DEBUG: urlpatterns += static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT) views.py: … -
Is it good practice to modify a session with a GET request?
I am trying to implement an invitation system in Django, compatible with django-allauth. It is similar to django-invitations, but I have some requirements that require a custom implementation. After researching ways to do it, the only thing I have come up with so far is sending an invite link that, when accessed, adds a flag to the current session to tell django-allauth that signups are open for that session. I think doing something like this is what allauth's docs recommend, although it does not go much into details. However, I have read in multiple places that a GET request should not cause side effects (here's one of many sources). Since django sessions are by default backed by a database, I think that modifying the session on a GET request (i.e. clicking the invitation link) would mean causing side-effects. The problem is, I cannot think of another way to do it, except heavily modifying django-allauth's views, which would be a lot more work, and possibly unsafe for an unexperienced developer like me. So, is it the case that I should not modify the session on a GET request? If so, what other alternatives do I have? -
Create a custom user after allauth logged in with django
this is my project urls urlpatterns = [ path('admin/', admin.site.urls), path('accounts/', include('allauth.urls')), path('', include('users.urls')) ] and also this is my app URLs urlpatterns = [ path("", views.home), path("logout", views.logout_view) ] I have this model (very simplified) from django.db import models class Author(models.Model): user = models.CharField() def __str__(self): return self.user.first_name + ' ' + self.user.last_name I am using the allauth authentication and I want to do some more things other than creating the user when the user logged in from google, for example. -
Django MongoEngine Unit Test
I'm trying to use unit tests in a Django application that uses MongoDB as the database and MongoEngine to interact with the database. Using examples from this answer, here's a simple test: from django.test import TestCase from mongoengine import connect, disconnect class MongoEngineTestCase(TestCase): def _fixture_setup(self): pass def _fixture_teardown(self): pass class CustomTestCase(MongoEngineTestCase): def setUp(self): connect( db="test_db", host="mongomock://localhost:27017/", alias="test_db", ) def tearDown(self): disconnect(alias="test_db") def test_one(self): self.assertEqual(1, 1) And I'm using a custom test runner to avoid connecting to the default database defined in settings.py. test_runner.py: from django.test.runner import DiscoverRunner class CustomTestRunner(DiscoverRunner): def setup_databases(self, **kwargs): pass def teardown_databases(self, old_config, **kwargs): pass settings.py: TEST_RUNNER = "AppName.test_runner.CustomTestRunner" However, when I run python manage.py test AppName.tests.CustomTestCase.test_one, I get this error, indicating that Django's attempting to connect to the default database mentioned in settings.py: django.db.utils.OperationalError: (2003, "Can't connect to MySQL server on '127.0.0.1:3306' (111)") How can I fix this? -
Replicate plotly-dash functionality with Django + TBC chart package
I have a plotly dash app which some tables, charts and a map. You click on a marker on a map and a chart and a few tables are updated on the web page, based on the data read from the map marker. How easy - difficult would it be to replicate existing logic in Django? I know there is django-plotly-dash but integration seems quite cumbersome.Should I go that route or is there a more "native" way to do it in Django? Basic functinality of the app is to get input from user via an input box, display stuff on the map, user clicks on the map, other charts and tables get updated. Hover over data points in chart brings additional information. Choosing Django as I need some form of authentication for the app which seems to come out of the box. Thank you Googling, youtube, earching stackoverflow, chatgpt -
how do i setup gunicorn conf in amazon EC2 ubuntu?
I am trying to deploy my django project on EC2 ubuntu instance: i have configured conf/gunicorn_config.py: command = "/home/ubuntu/venv/bin/gunicorn" pythonpath = "/home/ubuntu/my_project" bind = "13.232.32.207:8000" workers = 1 then i run : gunicorn -c conf/gunicorn_config.py myproject.wsgi it gives error: [2024-05-25 14:38:27 +0000] [8359] [INFO] Starting gunicorn 22.0.0 [2024-05-25 14:38:27 +0000] [8359] [ERROR] Invalid address: ('13.232.32.207', 8000) [2024-05-25 14:38:27 +0000] [8359] [ERROR] Retrying in 1 second. [2024-05-25 14:38:28 +0000] [8359] [ERROR] Invalid address: ('13.232.32.207', 8000) [2024-05-25 14:38:28 +0000] [8359] [ERROR] Retrying in 1 second. [2024-05-25 14:38:29 +0000] [8359] [ERROR] Invalid address: ('13.232.32.207', 8000) [2024-05-25 14:38:29 +0000] [8359] [ERROR] Retrying in 1 second. [2024-05-25 14:38:30 +0000] [8359] [ERROR] Invalid address: ('13.232.32.207', 8000) [2024-05-25 14:38:30 +0000] [8359] [ERROR] Retrying in 1 second. [2024-05-25 14:38:31 +0000] [8359] [ERROR] Invalid address: ('13.232.32.207', 8000) [2024-05-25 14:38:31 +0000] [8359] [ERROR] Retrying in 1 second. [2024-05-25 14:38:32 +0000] [8359] [ERROR] Can't connect to ('13.232.32.207', 8000) -
How to make `ModelSerializer` in `DRF` to don't ignore `id` field
I have a problem in nested ModelSerialzier in DRF. My code models.py class ModelA(models.Model): name = models.CharField(max_length=50) class ModelB(models.Model): some = models.CharField(max_length=50, blank=True, null=True) model_a = models.ForeignKey(ModelA, on_delete=models.CASCADE) views.py class CreateModelA(GenericAPIView): serializer_class = ModelASeri def post(self, request): serializer = ModelASeri(data=request.data) if serializer.is_valid(): serializer.create(serializer.data) return Response({"status": "OK"}) return Response({"status": "error", "error": serializer.errors}) serializers.py class ModelBSeri(serializers.ModelSerializer): class Meta: model = ModelB fields = ("id", "some") class ModelASeri(serializers.ModelSerializer): model_b = ModelBSeri(many=True, required=False) class Meta: model = ModelA fields = ("__all__") def create(self, validated_data): model_b = validated_data.pop("model_b", None) model_a = super().create(validated_data) print(model_b) if model_b: for model in model_b: obj = ModelB.objects.get(model["id"]) obj.model_a = model_a obj.save() return model_a My problem is when I try to access model["id"], I get KeyError. The print function will give me this: [OrderedDict([('some', None)])] the id field is ignored here What I try to do is I want to have a view that creates ModelA and relate the needed fields that are related to created ModelA instance. My input Example: { "name": "test name", "model_b": [ { "id": 1 }, { "id": 2 } ] } Here I want to create a ModelA with name=test name and relate ModelB instances with ids: [1, 2] to the ModelA created instance. -
Development Issue need help PLZ
I am a beginner in Django, recently I made a Django project and wanted to deploy it. I watched a lot of tutorials that utilized Heroku to deploy, and I thought it was easy so I wanted to try that. But, I found out that Heroku has been charging for a while. I also looked for many alternatives like Render, Vercel, and so on..., but they have many limitations like 100 requests/month or charging for databases. Some of them have stopped offering free-tier services just like Heroku. I know that Heroku free-tier had limitations too, but what I mean the limitations are: You can limit my network speed and database storage but make them available permanently, I want my project to stay online as long as possible. Can you give me some recommendations? -
for loop is not working in my django template
When I use for loop in my Django blog template, the post section goes off. What is the problem? I don't know which part of my editor I have to show you. Another problem, I am unable to see my django-admin panel after runserver. -
drf-spectacular hide Schemas from components in Swagger UI
In my Swagger UI, I'm trying to hide the Schemas section from components: I'm using drf-spectacular and I didn't find anything relating to Schemas in the Swagger Configuration. I tried removing schemas from the JSON response: from drf_spectacular.views import SpectacularJSONAPIView class CustomJSONAPIView(SpectacularJSONAPIView): def get(self, request, *args, **kwargs): response = super().get(request, *args, **kwargs) del response.data["components"]["schemas"] return response Which works, but corrupts rest of the Swagger functionality. Is it possible to simply hide this Schemas component without breaking rest of Swagger? -
Static files are not accessible on my website
I just deployed a website on a VPS but the static files are not being loaded. This is my settings.py file: # SECURITY WARNING: don't run with debug turned on in production! DEBUG = False ALLOWED_HOSTS = ['founderslooking.com'] CORS_ALLOWED_ORIGINS = [ "http://localhost:8080", "http://127.0.0.1:8080", "http://localhost:file", ] CORS_ALLOW_CREDENTIALS = True SESSION_COOKIE_SAMESITE = None SESSION_COOKIE_SECURE = False CSRF_TRUSTED_ORIGINS = ["founderslooking.com"] INTERNAL_IPS = [ "127.0.0.1", ] # Static files (CSS, JavaScript, Images) # https://docs.djangoproject.com/en/3.2/howto/static-files/ STATIC_URL = "static/" STATICFILES_DIRS = (os.path.join(BASE_DIR, "static/"),) STATIC_ROOT = os.path.join(BASE_DIR, "staticfiles/") MEDIA_ROOT = os.path.join(BASE_DIR, "storage").replace("\\", "/") MEDIA_URL = "/storage/" # Default primary key field type # https://docs.djangoproject.com/en/4.1/ref/settings/#default-auto-field DEFAULT_AUTO_FIELD = "django.db.models.BigAutoField" CACHES = { "default": { "BACKEND": "django.core.cache.backends.memcached.PyMemcacheCache", "LOCATION": "127.0.0.1:11211", } } What, if anything, is wrong here? How should I change the values for the production server? -
API Stripe. Why I have ERROR 400 to confirm payment?
the site API STRIPE tells me there is an error in LOGS: For what exact reason do I get a 400 error when entering the test card numbers and clicking the "Confirm" button? This message contains all the details of my error. I have attached the code in which the payment is made. Processing tokens, etc. POST /v1/charges Status 400 ERR ID req_GKbBUprcIuSQ0X Time 5/25/24, 1:09:58 PM IP address 151.249.163.206 API version 2024-04-10 Source Stripe/v1 PythonBindings/2.37.2 Idempotency Key — badc22f3-4989-46e8-aec6-35347aa48d10 resource_missing - source No such token: 'tok_1PKHY1IRI3YGNQKDocTdMkPu' Was this useful? Yes No { "source": "tok_1PKHY1IRI3YGNQKDocTdMkPu", "amount": "4400", "currency": "usd" } Response body { "error": { "code": "resource_missing", "doc_url": "https://stripe.com/docs/error-codes/resource-missing", "message": "No such token: 'tok_1PKHY1IRI3YGNQKDocTdMkPu'", "param": "source", "request_log_url": "https://dashboard.stripe.com/test/logs/req_GKbBUprcIuSQ0X?t=1716631798", "type": "invalid_request_error" } } Request POST body { "source": "tok_1PKHY1IRI3YGNQKDocTdMkPu", "amount": "4400", "currency": "usd" } My API tokens STRIPE_SECRET_KEY=sk_test_51PKFiB03rDhpU9syC7RuPemfhPC6Z5IZvxaKWRR5MajKEE3tvE58VrbZjxp3y56VoGrC2QLkARr95QVuDpmmu8uv00TP46EZQM STRIPE_PUBLISHABLE_KEY=pk_test_51PKFiB03rDhpU9syvWsl9Mvlt0XLdWaDI9a8fdolFlN9SXcUSxPhd9rtolZSUKIbBikfuWoeYZkPrdxFvf1T3Pmw00DGaQtOPA VIEWS.PY class PaymentView(LoginRequiredMixin, View): def get(self, *args, **kwargs): order = Order.objects.filter(user=self.request.user, ordered=False).first() return render(self.request, 'checkout/payment.html', {'order': order}) def post(self, *args, **kwargs): order = Order.objects.filter(user=self.request.user, ordered=False).first() token = self.request.POST.get('stripeToken') try: charge = stripe.Charge.create( amount=round(float(order.get_total_amount() * 100)), currency="usd", source=token ) except stripe.error.CardError: messages.error(self.request, 'Payment could not be made') return redirect('products:home-page') except Exception: messages.error(self.request, 'Internal server error') return redirect('products:home-page') payment = Payment( user=self.request.user, stripe_id=charge.id, amount=order.get_total_amount() … -
I am unable to transfer the object to display_item.html page, from index page in Djanog page
I have been trying for a very long time to transfer item, which is obtained via a for loop in Django templating language. An item is an object. I have tried a lot of different arrangements, but nothing is working so far. It's the index file. {% extends "auctions/layout.html" %} {% block body %} <h2>Active Listings</h2> {% for item in listings %} <a href="{% url 'display_item' entry=item %}"> <img src="/media/{{ item.image_url }}" width="300" height="400" alt="Picture of the item."> <h3>{{ item.title }}</h3> </a> <p>{{ item.description }}</p> <h5>Starting bid: {{ item.starting_bid }}</h5> {% empty %} <h4>No listings to display!</h4> {% endfor %} {% endblock %} Its the file that is suppose to display the object. {% extends 'auctions/layout.html' %} {% block body %} <img src="/media/{{ item.image_url }}" width="400" alt="Picture of item here."> <p>{{ item.category }}</p> <h3>{{ item.title }}</h3> <p>{{ item.description }}</p> <br> <br> <h5>Created by {{ item.created_by }}</h5> <p>{{ item.created_at }}</p> {% endblock %} It's the URLS.py file. from django.conf import settings from django.conf.urls.static import static from django.urls import path from . import views urlpatterns = [ path("", views.index, name="index"), path("login", views.login_view, name="login"), path("logout", views.logout_view, name="logout"), path("register", views.register, name="register"), path("new_listing", views.new_listing, name="new_listing"), path("display_item/<str:entry>/", views.display_item , name="display_item") ] if settings.DEBUG: urlpatterns += static(settings.MEDIA_URL, …