Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
UpdateView in django
i can update email and others using the generic edit view "UpdateView" by giving the attribute name of my html inputs the corresponding field name so name="email" and so on. But the same thing doesn't work with field "user_permissions" model = User fields = [ "email", "is_superuser", "is_active", "is_staff", "user_permissions", ] // options are added with a js event handler -
What Price Plan of Heroku should I buy for hosting my Django App?
I have made my web-based app using Django Framework, and it's all done. Now I want to upload it using Heroku, but we should buy heroku plan to start use it, so What is the best price plan to host it (based on actual Heroku Pricing Plan 2024)? I have seen all the Price plan but a little bit confusing for me to choose which one is the best price plan for my web-app -
Django One UpdateView for different models
There are several models in my Django project with one similar field - "comment". I want to create an UpdateView for updating only this one field. I can do it by writing an UpdateView for each model. But I am wondering if can I write one UpdateView class for each of these models if the functionality of the class is the same, the model name needs to be only changed. -
Django middleware can record request log, but django async view somethings was not executed
request will be recorded by the middleware and executed in async view, but in some cases, it will not be executed in view. Settings: Python: 3.10.12 Django: 4.2.1 middleware settings: MIDDLEWARE = [ "django.middleware.security.SecurityMiddleware", "django.contrib.sessions.middleware.SessionMiddleware", "corsheaders.middleware.CorsMiddleware", "django.middleware.common.CommonMiddleware", "django.contrib.auth.middleware.AuthenticationMiddleware", "django.contrib.messages.middleware.MessageMiddleware", "django.middleware.clickjacking.XFrameOptionsMiddleware", ... "utils.middleware.RequestMiddleware", ] RequestMiddleware: class RequestMiddleware(MiddlewareMixin): def process_view(self, request, view_func, view_args, view_kwargs): req_str = "reqeust user:{} request method:{} request path:{} request body:{}".format( request.user, request.META["REQUEST_METHOD"], request.path, request.body ) logger.info(req_str) return None def process_response(self, request, response): data = response.content data = data.decode("utf-8") logger.info("response status code:{} data:{}".format(response.status_code, data)) return response def process_exception(self, request, exception): logger.error(traceback.format_exc()) views.py: async def report(request): my_views.delay() # celery task return send_message({"result": 0}) -
Django: Upload File to Firebase and Save File Metadata to Sqlite3
I have a Django app, I am trying to upload the document to firebase. It uploads properly but the metadata does not upload to my sqlite3 database. def uploadProject(request): print("INSIDE UPLOAD VIEW") #Prints if request.method == 'POST': print("INSIDE POST REQUEST") #Does not print form = UploadProjectForm(request.POST, request.FILES) if form.is_valid(): file = request.FILES['file'] file_url = upload_to_firebase(file) metadata = form.save(commit=False) metadata.file_url = file_url model metadata.save() return redirect('upload-project') else: form = UploadProjectForm() return render(request, 'base/upload_project.html', {'form': form}) This is my upload.js file that handles the form submission import { ref, uploadBytesResumable, getDownloadURL } from "https://www.gstatic.com/firebasejs/9.6.1/firebase-storage.js"; import { storage } from "./firebase-config.js"; document.querySelector('form').addEventListener('submit', async (e) => { e.preventDefault(); const fileInput = document.querySelector('input[type="file"]'); if (fileInput.files.length === 0) { alert('No file selected.'); return; } const file = fileInput.files[0]; const storageRef = ref(storage, `uploads/${file.name}`); const uploadTask = uploadBytesResumable(storageRef, file); uploadTask.on('state_changed', (snapshot) => { // Observe state change events such as progress, pause, and resume const progress = (snapshot.bytesTransferred / snapshot.totalBytes) * 100; console.log('Upload is ' + progress + '% done'); }, (error) => { // Handle unsuccessful uploads console.error('Upload failed:', error); }, async () => { // Handle successful uploads on complete const downloadURL = await getDownloadURL(uploadTask.snapshot.ref); console.log('File available at', downloadURL); } ); }); This is my … -
ModuleNotFoundError: No module named 'django' . Have tried most solutions including reinstalling
I'm currently trying to setup django for a website that rates music. Django is installed but when i run the code, the output says `File "c:\Users\nguye\Desktop\django_project\mymusicapp\mymusicapp\urls.py", line 17, in from django.contrib import admin ModuleNotFoundError: No module named 'django'`` I can run and visit the devlopment server but when i add /music/search to the end, it tells me "Using the URLconf defined in mymusicapp.urls, Django tried these URL patterns, in this order: admin/ The current path, music/search, didn’t match any of these. You’re seeing this error because you have DEBUG = True in your Django settings file. Change that to False, and Django will display a standard 404 page." and in the terminal, it says "Not Found: /music/search. This is what I have in the urls.py `# mymusicapp/urls.py from django.contrib import admin from django.urls import path, include urlpatterns = [ path('admin/', admin.site.urls), path('music/', include('music.urls')), How could I fix this? I cant seem to figure out whats wrong. I tried reinstalling django, tested the whole process on another device, so there must be something wrong in my process or code. -
Handling K8s forcefull kill of celery pods before completing running tasks
I am deploying a Django app with Celery workers on AWS EKS. I have everything running as expected, except that K8s proceeds to stopping Celery workers replicas before finishing ongoing tasks, I also have the same behavior when making a new deployment or pushing new code to the master branch. What I have tried: Setting a very large grace period, this solution didn't work, because we've got tasks that runs for hours. Setting a preStop hook, this solution didn't also work since K8s doesn't wait for the hook to finish if it exceeds the grace period. I have also tried fixed replicas count, but it's obviously not a solution. more information: I have celery setup with Redis as a messaging broker and a result backend. After some research I started considering using Keda, but upon reading the docs, seems like it will only allow me to scale Celery pods based on queues length but doesn't give the kill mechanism I am looking for. Is there any workaround to solve this issue? -
Data doesn't show on template - django
I have a chat app but it seems that i have a few mistakes which i don't know what is. Users can not see their chat history and their messages in the app. When Users write their messages on a specific form, I can see their messages on Django admin and that means the messages send successfully. But the problem starts in views.py, I tried a lot to address the template on chat history feed but when you run the app there is no response except: No chat history available. How can I fix this? We have models on models.py: # Main Imports # Django Imports from django.db import models from django.contrib.auth.models import User from django.utils import timezone # My Module Imports from authentication.models import BasicUserProfile # Chat # --------- class Chat(models.Model): creation_date = models.DateField(default=timezone.now) id = models.AutoField(primary_key=True) content = models.TextField() sender = models.ForeignKey( BasicUserProfile, on_delete=models.CASCADE, blank=True, null=True, related_name="sender" ) reciever = models.ForeignKey( BasicUserProfile, on_delete=models.CASCADE, blank=True, null=True, related_name="reciever" ) def __str__(self): return "chat: " + str(self.sender) ` and views.py: \`def chat_single(request, username): """ in this page users can chat with each other """ # admin user session pop # admin user session pop # Deleting any sessions regarding top-tier type … -
celery worker with sqs to consume arbitrary messages from outside
does anyone know if a celery worker can receive and consume messages from a sqs where the messages are pushed to the sqs by outside applications? I cannot find any resources on this. Another pointers would be appreciated. There are a lot of resources of connecting celery to sqs and then pushing tasks onto the queue and processing them but I want to push arbitrary messages (of different format) into the queue and have celery receive and process these in a task. Most resources online related to celery sending and receiving messages to sqs. -
Django: django.core.exceptions.SynchronousOnlyOperation while running scrapy script in django
I am trying to implement scrapy in django. For that this topic helped me. In my script I just return a simple object in order to see if everything work in order to be added in my model. I don't scrap any website. Issue myspider.py: from scrapers.items import ScrapersItem class ErascraperSpider(scrapy.Spider): name = "erascraper" allowed_domains = ["example.com"] start_urls = ["https://example.com"] def parse(self, response): return ScrapersItem(name="Argus") mypipeline.py: class ScrapersPipeline(object): def process_item(self, item, spider): item.save() print("pipeline ok") return item Also, I use Scrapy_DjangoItem in my items.py. Howerver I get this error: 2024-05-21 22:01:37 [scrapy.core.engine] DEBUG: Crawled (200) <GET https://example.com> (referer: None) 2024-05-21 22:01:37 [scrapy.core.scraper] ERROR: Error processing {'name': 'Argus'} Traceback (most recent call last): File "/Users/kevingoncalves/Desktop/Folders/Coding/glsapi/myenv/lib/python3.12/site-packages/twisted/internet/defer.py", line 1078, in _runCallbacks current.result = callback( # type: ignore[misc] File "/Users/kevingoncalves/Desktop/Folders/Coding/glsapi/myenv/lib/python3.12/site-packages/scrapy/utils/defer.py", line 340, in f return deferred_from_coro(coro_f(*coro_args, **coro_kwargs)) File "/Users/kevingoncalves/Desktop/Folders/Coding/glsapi/scrapers/scrapers/pipelines.py", line 14, in process_item item.save() File "/Users/kevingoncalves/Desktop/Folders/Coding/glsapi/myenv/lib/python3.12/site-packages/scrapy_djangoitem/__init__.py", line 35, in save self.instance.save() File "/Users/kevingoncalves/Desktop/Folders/Coding/glsapi/myenv/lib/python3.12/site-packages/django/db/models/base.py", line 822, in save self.save_base( File "/Users/kevingoncalves/Desktop/Folders/Coding/glsapi/myenv/lib/python3.12/site-packages/django/db/models/base.py", line 909, in save_base updated = self._save_table( File "/Users/kevingoncalves/Desktop/Folders/Coding/glsapi/myenv/lib/python3.12/site-packages/django/db/models/base.py", line 1071, in _save_table results = self._do_insert( File "/Users/kevingoncalves/Desktop/Folders/Coding/glsapi/myenv/lib/python3.12/site-packages/django/db/models/base.py", line 1112, in _do_insert return manager._insert( File "/Users/kevingoncalves/Desktop/Folders/Coding/glsapi/myenv/lib/python3.12/site-packages/django/db/models/manager.py", line 87, in manager_method return getattr(self.get_queryset(), name)(*args, **kwargs) File "/Users/kevingoncalves/Desktop/Folders/Coding/glsapi/myenv/lib/python3.12/site-packages/django/db/models/query.py", line 1847, in _insert return query.get_compiler(using=using).execute_sql(returning_fields) File "/Users/kevingoncalves/Desktop/Folders/Coding/glsapi/myenv/lib/python3.12/site-packages/django/db/models/sql/compiler.py", … -
Django doesn't see relation in workflow tests
In normal tests running locally, but if I try to run them through workflows I get an error: Run chmod +x tests/test.sh Traceback (most recent call last): File "/opt/hostedtoolcache/Python/3.10.12/x64/lib/python3.10/site-packages/django/db/backends/utils.py", line 89, in _execute return self.cursor.execute(sql, params) psycopg2.errors.UndefinedTable: relation "tours_data.city" does not exist LINE 1: ...ntry_id", "tours_data"."city"."point"::bytea FROM "tours_dat... ^ The above exception was the direct cause of the following exception: Traceback (most recent call last): File "/home/runner/work/tours_manager/tours_manager/manage.py", line 22, in <module> main() File "/home/runner/work/tours_manager/tours_manager/manage.py", line 18, in main execute_from_command_line(sys.argv) File "/opt/hostedtoolcache/Python/3.10.12/x64/lib/python3.10/site-packages/django/core/management/__init__.py", line 446, in execute_from_command_line utility.execute() File "/opt/hostedtoolcache/Python/3.10.12/x64/lib/python3.10/site-packages/django/core/management/__init__.py", line 420, in execute django.setup() File "/opt/hostedtoolcache/Python/3.10.12/x64/lib/python3.10/site-packages/django/__init__.py", line 24, in setup apps.populate(settings.INSTALLED_APPS) File "/opt/hostedtoolcache/Python/3.10.12/x64/lib/python3.10/site-packages/django/apps/registry.py", line 124, in populate app_config.ready() File "/opt/hostedtoolcache/Python/3.10.12/x64/lib/python3.10/site-packages/django/contrib/admin/apps.py", line 27, in ready self.module.autodiscover() File "/opt/hostedtoolcache/Python/3.10.12/x64/lib/python3.10/site-packages/django/contrib/admin/__init__.py", line 50, in autodiscover autodiscover_modules("admin", register_to=site) File "/opt/hostedtoolcache/Python/3.10.12/x64/lib/python3.10/site-packages/django/utils/module_loading.py", line 58, in autodiscover_modules import_module("%s.%s" % (app_config.name, module_to_search)) File "/opt/hostedtoolcache/Python/3.10.12/x64/lib/python3.10/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 1006, in _find_and_load_unlocked File "<frozen importlib._bootstrap>", line 688, in _load_unlocked File "<frozen importlib._bootstrap_external>", line 883, in exec_module File "<frozen importlib._bootstrap>", line 241, in _call_with_frames_removed File "/home/runner/work/tours_manager/tours_manager/manager/admin.py", line 5, in <module> from .forms import AddressForm, ReviewForm File "/home/runner/work/tours_manager/tours_manager/manager/forms.py", line 40, in … -
Auth0 callback does not work on production
I have a React & Django application that works locally but not when deployed on Heroku. Long story short, on local env after login it makes a request to /authorize and after redirect to /callback?code=xxx&state=yyy and server respond with 200 OK. On prod, from the other hand, after calling /callback server gives 302 with Location to main page - “/”. No matter what page I will access, every time it gives 302 and falls into infinite loop. There are absolutely no difference between local and prod. Also, all necessary URLs are set up in env paths and Auth0 dashboard. This is my code for callback/index.tsx import { PageLoader } from "../../components/page-loader"; import { useEffect } from 'react'; import { useAuth0 } from '@auth0/auth0-react'; export default function Callback() { const { isAuthenticated, isLoading, error, loginWithRedirect } = useAuth0(); useEffect(() => { if (!isLoading && !isAuthenticated) { console.log("User is not authenticated. Redirecting to login..."); loginWithRedirect(); } }, [isLoading, isAuthenticated, loginWithRedirect]); if (isLoading) { return ( <div className="page-layout"> <PageLoader /> </div> ); } if (error) { return <div>Error: {error.message}</div>; } return ( <div className="page-layout"> <PageLoader /> </div> ); } I added it to App.js <Route path="/callback" element={<Callback />} /> providers/auth.tsx import { AppState, … -
How to deliver Django+ NextJs+ Postgresql project to client
I have my backend built on django and frontend on nextjs. I have to deliver it to client but I don't know how to do it. I have env folder in my django root directory which is virtual environment and I have made a requirements.txt file in the root of django project as well with .env file for secret keys. Also I have a folder named backend which contains tha next js project. It has package-json file in it. Do I have to make gitignore files in both directories if I am making the github push. And how can I deliver the project to the client I am a beginner. I tried transferring my virtual environment folder along with my project of django but the virtual environment didn't work correctly because it had directories with paths of my personal computer. What should I do... -
Azure Web App blocking AJAX requests to django application
I have a django (4.2.13 + python 3.10) application that at certain point makes AJAX requests to display progress to user while processing data from uploaded file. When I try this locally on my computer (linux) it works well and progress bar is updated from data received in response of AJAX calls. Similarly it also works on a test server (linux + nginx + gunicorn) and displays progress without hassle. On the browser side I use jQuery .post command to make calls. When I deploy same app to the Azure Web App it doesn't allow any of the calls to go through, all remain in Pending state in the browser and there is absolutely no trace anywhere in the Azure logs. Any hints? -
Best Download for Music [closed]
What is the best downloader like Spotify-DL or YT-DLP? Or even a Tidal downloader? I am just wondering because I am building my own music downloader because I am a DJ. I need good quality. I've used a Yt-dl once, and let me tell you it was bad. Which one do you recommend? -
Helm on Minikube showing an NGINX frontpage instead of a Django application
When I type minikube svc announcements-helm --url I get a URL that points me to a default NGINX page. I'm not sure why it is not showing me the actual Django application that is supposed to be there. I used kubectl exec to ls the pod, and it shows the application is inside the pod. I have the code for the Helm setup at this github repository: https://github.com/UCF/UCF-Announcements-Django/tree/helm/helm I'm fairly new to helm and kubernetes so any advice would be very appreciated -
Django, stripe and webhook : {"error": "Missing stripe signature"}
I need your help. I'm trying to set up a striped payment system in the django app. However, I can't seem to connect the webhook to my logic. In addition, the handle_checkout_session function which should send a message after the success of each payment does not send any message. def stripe_config(request): if request.method == 'GET': stripe_config = {'publicKey': settings.STRIPE_PUBLIC_KEY} return JsonResponse(stripe_config, safe=False) login_required(login_url="login") def stripe_payment(request): if request.method == 'GET': domain_url = getattr(settings, 'DOMAIN_URL') success_url = domain_url + reverse('stripe_success') + '?session_id={CHECKOUT_SESSION_ID}' cancel_url = domain_url + reverse('stripe_cancel') stripe.api_key = settings.STRIPE_SECRET_KEY order_id = request.GET.get('order_id') try: order = Order.objects.get(user=request.user, is_ordered=False, order_number=order_id) checkout_session = stripe.checkout.Session.create( client_reference_id=request.user.id if request.user.is_authenticated else None, success_url=success_url, cancel_url=cancel_url, payment_method_types=['card'], mode='payment', line_items=[ { 'price_data': { 'currency': 'eur', 'unit_amount': int(order.order_total * 100), 'product_data': { 'name': "Buy now", }, }, 'quantity': 1, } ] ) return JsonResponse({ 'sessionId': checkout_session['id'] }) except Order.DoesNotExist: return JsonResponse({ 'error': 'Order does not exist or has already been processed.' }, status=404) except stripe.error.StripeError as e: return JsonResponse({ 'error': str(e) }, status=500) return JsonResponse({'error': 'Invalid request method.'}, status=400) @csrf_exempt def stripe_webhook(request): stripe.api_key = settings.STRIPE_SECRET_KEY endpoint_secret = settings.STRIPE_WEBHOOK_SECRET payload = request.body sig_header = request.META.get('HTTP_STRIPE_SIGNATURE') print(sig_header) if sig_header is None: return JsonResponse({'error': 'Missing stripe signature'}, status=400) try: event = stripe.Webhook.construct_event( payload, sig_header, … -
cookies are not being set on browser Django
I'm making a webapp in Django and Electron using websockets and I wanted to insert one of the socket responses into the user's cookies, but unfortunately I don't know why but they are not being inserted, here is an example of what I am doing: in the response.cookies printout something like this appears: Cookies defined in the response: Set-Cookie: image_data="pls work"; expires=Tue, 21 May 2024 16:22:33 GMT; Max-Age=3600; Path=/ here is my code if you have any ideas or need any part of the code I will provide it, thank you. code: @csrf_exempt def process_screenshot(request): call = identificador_unico(request) print("call:", call) if request.method == 'POST': image_content = request.POST.get('image_content') if image_content: print("String em base64 recebida com sucesso.") try: # Decodifica a string em base64 para obter os dados binários da imagem image_data = base64.b64decode(image_content) print("base64", image_data[:20]) # Salva os dados binários da imagem em um arquivo file_path = 'frames/screenshot.jpg' with open(file_path, 'wb') as f: f.write(image_data) image_content = "pls work" # Salva image_data nos cookies response = JsonResponse({'message': 'Imagem processada com sucesso'}) response.set_cookie('image_data', image_content, max_age=3600,secure=False,samesite=None) # Expira em 1 hora print("Cookies definidos na resposta:", response.cookies) return response except Exception as e: # Se ocorrer algum erro ao decodificar a string em base64 ou … -
Value Error while storing data into models in Django
This is my "models.py": class PostData(models.Model): #image = models.ImageField(upload_to="") title_name = models.CharField(max_length=255) description = models.CharField(max_length=10000) author = models.ForeignKey(User, on_delete=models.CASCADE) date_created = models.DateTimeField(auto_now_add=True) date_updated = models.DateTimeField(auto_now=True) This is my "views.py": def createPost(request): if request.method == "POST": form = PostForm(request.POST) print(form.is_valid()) if form.is_valid(): # To extarct data from web page title = form.cleaned_data['title_name'] description = form.cleaned_data['description'] # To get username which is stored in session author = request.session.get("username") print(author) print(title) # To store Data PostData.objects.create(title_name=title, description=description, author=author) And I am getting the following error: ValueError at /create/ Cannot assign "'dhruv123'": "PostData.author" must be a "User" instance. So how to solve this error? -
You are not authorized to view this object, Django + Cloudflare R2
im trying to use CloudFlare R2 to server static files from my django project, but im having "This object could not be viewed". I added custom domains, and allowed public view. I cant understand what is wrong. Any help? Thank you! -
assertRedirects in django view test not working
I have created a test case to test my custom login_required decorator. This is my decorator: def login_required(view_func): @wraps(view_func) def wrapped_view(request, *args, **kwargs): # Check if the user is logged in if request.user.is_authenticated: return view_func(request, *args, **kwargs) else: return redirect('/auth/login') return wrapped_view This is my test case: class RegisterViewTests(TestCase): def setUp(self): self.client = Client() def test_register_view_get_not_authenticated(self): response = self.client.get(reverse('register')) print(response.url) self.assertRedirects(response, '/auth/login') Here when I print response.url I get '/auth/login' but when I use the same to check the redirect I get this error: FAIL: test_register_view_get_not_authenticated (authentication.tests.test_views.RegisterViewTests.test_register_view_get_not_authenticated) Traceback (most recent call last): File "F:\Ayush\CODE\DJANGO\final\project\CBBB Group 1\final_repo\authentication\tests\test_views.py", line 61, in test_register_view_get_not_authenticated self.assertRedirects(response, reverse('login_view')) File "F:\Ayush\CODE\DJANGO\final\project\CBBB Group 1\final_repo\venv\Lib\site-packages\django\test\testcases.py", line 432, in assertRedirects self.assertEqual( AssertionError: 301 != 200 : Couldn't retrieve redirection page '/auth/login': response code was 301 (expected 200) Ran 1 test in 0.033s FAILED (failures=1) I tried using reverse('login') inside the assertRedirects but it still gave the same error. -
Django Internationalization - Translation from Javascript handled pop up not picked up
I am using Django Internationalization in my django project. On one of my page I have some text, which gets translated just fine, and a pop up window which stubornly does not seem to pick up the translation proposed in the po file. However the translation is present in the po. Because this pop up window has created problems in the past, I am assuming this is because of the javascript that manages the window to open and close. I started following this post How to solve the translation/localisation of JavaScript external files since Django does not allow built-it tags in other files?, but I think I am missing something: how do I connect my locale file to the javascript catalog? project: mysite app: main url (project level) urlpatterns += i18n_patterns( path('', include("main.urls")), #add for i18n translation for javascript content path("jsi18n/", JavaScriptCatalog.as_view(), name="javascript-catalog"), ) base.html <script src="{% url 'javascript-catalog' %}"></script> template (app level) with script <div class="form-popup" id="myForm{{ model.id }}"> <form action="{% url 'url' %}" class="show-venue-popup-container" method="post"> {% csrf_token %} <h5 class="show-venue-popup-title">{% translate 'text to be translated_0!' %}</h5> <p class="show-venue-popup-text">{% translate 'text to be translated_1' %}</p> <button type="submit" class="btn">{% translate 'text to be translated_2' %}</button> <button type="button" class="btn cancel" onclick="closeForm('{{ … -
Django hosting as begginer
Free Django hosting platforms do not support the latest Python versions. My Django app is made with Python 3.12.2. What should I do? Should I downgrade my project version to match the hosting platforms? Will this ruin my project? I am a beginner, and this is my first time doing all of this. I tried Heroku which is now paid, pythonanywhere is upto python 3.10 -
Django stripe and stripe webhook error : {"error": "Missing stripe signature"}
please, I need your help. I'm trying to set up a striped payment system in the django app. However, I can't seem to connect the webhook to my logic. In addition, the handle_checkout_session function which should send a message after the success of each payment does not send any message. However, when I make a payment it works fine. But, Webhook and handle_checkout_session doesn't work. Your help will be welcome... Here is my code. def stripe_config(request): if request.method == 'GET': stripe_config = {'publicKey': settings.STRIPE_PUBLIC_KEY} return JsonResponse(stripe_config, safe=False) login_required(login_url="login") def stripe_payment(request): if request.method == 'GET': domain_url = getattr(settings, 'DOMAIN_URL') success_url = domain_url + reverse('stripe_success') + '?session_id={CHECKOUT_SESSION_ID}' cancel_url = domain_url + reverse('stripe_cancel') stripe.api_key = settings.STRIPE_SECRET_KEY order_id = request.GET.get('order_id') try: order = Order.objects.get(user=request.user, is_ordered=False, order_number=order_id) checkout_session = stripe.checkout.Session.create( client_reference_id=request.user.id if request.user.is_authenticated else None, success_url=success_url, cancel_url=cancel_url, payment_method_types=['card'], mode='payment', line_items=[ { 'price_data': { 'currency': 'eur', 'unit_amount': int(order.order_total * 100), 'product_data': { 'name': "Buy now", }, }, 'quantity': 1, } ] ) return JsonResponse({ 'sessionId': checkout_session['id'] }) except Order.DoesNotExist: return JsonResponse({ 'error': 'Order does not exist or has already been processed.' }, status=404) except stripe.error.StripeError as e: return JsonResponse({ 'error': str(e) }, status=500) return JsonResponse({'error': 'Invalid request method.'}, status=400) @csrf_exempt def stripe_webhook(request): stripe.api_key = settings.STRIPE_SECRET_KEY endpoint_secret … -
Reverse for 'service' not found . template base.html, error at line 0 why i am getting this error?
i have created services.html in templates and also defined a view for it and url in urls.py but then i decided to simply remove it because i don't need it i deleted my template services.html and also view and url from urls.py but i am getting this error even i don't have any veiw name services or url in my urls.py but still i am getting this error during template rendering error at line 0. This is views.py: from django.shortcuts import render def home(request): return render(request,'webapp/home.html') urls.py from django.urls import path from . import views urlpatterns = [ path('',views.home,name='home'), ] urls.py Project from django.contrib import admin from django.urls import path,include urlpatterns = [ path('admin/', admin.site.urls), path('',include('webapp.urls')), ] project structure: