Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Download image to client Django
My problem is that the download does not start when I send the form the first time I created it in a view and it worked but for order and efficiency I decided to pass part of the view to the model but it does not work class Archivo(models.Model): Archivo = models.ImageField(upload_to="Seccion1") def descarga1(archivo_nombre): # Obtén la ruta completa del archivo archivo_ruta = os.path.join(settings.BASE_DIR, "media", "Seccion1", archivo_nombre) # Crea un objeto FileResponse con la ruta del archivo response = FileResponse(open(archivo_ruta, "rb")) # Indica que el archivo debe tratarse como un adjunto para descargar response['Content-Disposition'] = 'attachment; filename="Hola.png"' return response class Jpgtopng(View): def get(self,request): return render(request,"Pngtojpg.html",{"form":Formext}) def post(self,request): Formulario = Formext(request.POST,request.FILES)#?Recibimos datos del formulario if Formulario.is_valid(): imagen = Formulario.cleaned_data["Archivo"] imagen_nombre = imagen.name if Formulario.Extension(imagen_nombre): Formulario.save() Archivo.descarga1(imagen_nombre) # Pasa el nombre del archivormulario.Extension(Imagenrn):#?Pero antes de guardarlo verifica que su extension sea valida else: return HttpResponse("Extension incorrecta") else: #? En caso de no ser valido reenviamos el formulario return render(request,"Pngtojpg.html",{"Formu":Formulario}) return HttpResponse("Hubo un error") <!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <title>Document</title> </head> <body> <!--El multipar/form-data sirve para que el formulario pueda enviar archivos--> <form action="" method="POST" enctype="multipart/form-data">{% csrf_token %} {{form}} <button type="submit"></button> </form> </body> </html> I just need … -
How can I get a comma separated list with related posts from a many-to-many field?
I am trying to learn Django and have encountered a problem I can't figure out for the life of me. In this project I have an app called projects. In this app I have one model called Projectinfo and one called Buildingtypes. Every project can have one or more building types. What I am trying to do is to write a view that lists out all the projects with a commaseparated list of related building types. Here's a simplified version of my two models: class Buildingtypes(models.Model): buildingtype = models.CharField(max_length=100) def __str__(self): return self.buildingtype class ProjectInfo(models.Model): project_number = models.CharField(max_length=12, blank=True) project_name = models.CharField(max_length=120) buildingtypes = models.ManyToManyField(Buildingtypes, default=[1]) def __str__(self): return self.project_name I made a view that looks like this: from django.http import HttpResponse from django.template import loader from .models import ProjectInfo def index(request): myProjects = ProjectInfo.objects.all() template = loader.get_template('projects/index.html') context = { 'projects': myProjects, } return HttpResponse(template.render(context, request)) And the template: {% if projects %} {% for x in projects %} {{ x.project_number }} | {{ x.project_name }} | {{ x.buildingtype }} {% endfor %} {% endif %} Which resulted in this: projectnumber | project name | building type ---------------------------------------------------------- 101010 | project 1 | projects.Buildingtypes.None 202020 | project 2 | … -
Styles didn't apply to Django Project when uploaded to Render
I tried to upload my django project to Render which contains plenty of HTML files as well CSS styles. The latter is used in a CSS file called 'styles.css' within the static folder. When I run the project, the images are shown, but it's like the styles have not been applied to everything, not even the Django Admin panel. On the console, it mentioned something about how the stylesheet wasn't loaded because of MIME type. The same happens with my main.js file, which is also within the static folder. I have heard about using gunicorn, which I have it installed, but i'm not sure if it's actually responsible for causing this since the images load fine (although their sizes are very much different). I want to know if there's a solution to this. For reference, this is how I added the urls of my media and static in the settings.py: STATIC_URL = 'static/' STATICFILES_DIRS = [BASE_DIR / 'static'] MEDIA_URL = '/media/' MEDIA_ROOT = BASE_DIR / 'media' This is my current urls.py for my main project: from django.contrib import admin from django.urls import path, include from django.conf import settings from django.conf.urls.static import static urlpatterns = [ path('admin/', admin.site.urls), path('', include('store.urls')), path('chatbot/', … -
I am trying to implement authentication in django using django_cas_ng, and also provide a option for all-auth for google login
My requirement is to have a core app to manage authentication, which should include google authentication (all-auth in django) and django_cas_ng (CAS authentication). Now I want to be able to use this authentication app for multiple projects (CAS system). I should register only for one app , and should be able to login to another app using the same username and password. (CAS auth system). path('', django_cas_ng.views.LoginView.as_view(), name='cas_ng_login'), path('accounts/logout', django_cas_ng.views.LogoutView.as_view(), name='cas_ng_logout'), I the url cas_ng_login redirects me to CAS_SERVER_URL = 'http://localhost:8000/accounts/', where I have the google authentication implemented. enter image description here -
i am geting value error while get cust id value from passing query in link which is in checkout file . I am using razorpay payment-gateway
I am using django framework and i will get the value error while i use razorpay payment gateway enter image description here **This iS models ** class Payment(models.Model): user = models.ForeignKey(User,on_delete=models.CASCADE) amount = models.FloatField() razorpay_order_id = models.CharField(max_length=100,blank = True , null = True) razorpay_payment_status = models.CharField(max_length=100,blank = True , null = True) razorpay_payment_id = models.CharField(max_length=100,blank = True , null = True) paid = models.BooleanField(default = False) class OrderPlaced(models.Model): user = models.ForeignKey(User,on_delete=models.CASCADE) #cid = models.ForeignKey(Payment,on_delete=models.CASCADE) customer = models.ForeignKey(Customer,on_delete=models.CASCADE) product = models.ForeignKey(Product,on_delete=models.CASCADE) quantity = models.PositiveIntegerField(default=1) ordered_date = models.DateField(auto_now_add = True) status = models.CharField(max_length = 50,choices = STATUS_CHOICES,default = 'Pending') payment = models.ForeignKey(Payment, on_delete=models.CASCADE,default ="") @property def total_cost(self): return self.quantity*self.product.discounted_price This is html code {% extends 'app/base.html' %} {% load static %} {% block title %} Buy Now {% endblock %} {% block main-content %} <div class="container"> {% if messages %} {% for msg in messages %} <div class="alert alert-denger" role="alert"> {{msg}} </div> {% endfor %} {% endif %} <div class="row mt-5"> <div class="col-sm-6"> <h4> Order Summery </h4> <hr> {% for item in cart_items %} <div class="card mb-2"> <div class="card-body"> <h5> Product: {{item.product.title}}</h5> <p>Quantity: {{item.quantity}} </p> <p class="fw-bold">Price: {{item.product.discounted_price}}</p> </div> </div> {% endfor %} <p class="fw-bold"> Total Cost + Rs. 40 = {{totalamount}}</p> … -
Issue Passing Size Parameter from JavaScript to Django Backend
I'm encountering an issue with passing the "size" parameter from my JavaScript function to my Django backend. Here's the relevant code snippet from my Django view: def get_product(request, slug): try: product = Product.objects.get(slug=slug) if request.GET.get('size'): size = request.GET.get('size') print(size) return render(request, "core/product_detail.html") except Exception as e: print(e) And here's the JavaScript function: function get_correct_price(size) { console.log(size); window.location.href = window.location.pathname + `?size=${size}`; } In my HTML template, I'm calling the JavaScript function with the size parameter: <button onclick="get_correct_price('{{ s.name }}')">{{ s.name }}</button> However, when I click the button, the size parameter doesn't seem to be passed to the backend. I've verified that the JavaScript function is being called, and the size parameter is logged correctly in the console. Could you please help me identify why the size parameter is not being received in the backend? Any insights or suggestions would be greatly appreciated. Thank you! -
Items are being added in the cart in multiples of 3 in Django
I am creating a ecommerce website on Django but the problem is that when I add a item in the cart the quantity is set to 3 instead of 1. and when I increase the quantity by clicking one more time. It's quantity becomes 6 instead of 2 and so on. Below is the code from cart.html to add and remove items from the cart. <div class="li-cartstyle cartbodyinformation-quantity"> <p class="quantity-input">{{item.quantity}}</p> <div class="cartquantity-buttons"> <i data-product={{item.product.id}} data-action="add" class="update-cart change-quantity fa-solid fa-angle-up"></i> <i data-product={{item.product.id}} data-action="remove" class="update-cart change-quantity fa-solid fa-angle-down"></i> </div> </div> and below is the code from cart.js var updateBtns = document.getElementsByClassName('update-cart') var user = isAuthenticated ? 'AuthenticatedUser' : 'AnonymousUser'; for(var i=0; i < updateBtns.length; i++){ updateBtns[i].addEventListener('click', function(){ var productId = this.dataset.product var action = this.dataset.action console.log('productId:', productId, '\naction: ', action) console.log('USER: ',user) if(user === 'AnonymousUser'){ addCookieItem(productId, action) } else{ updateUserOrder(productId, action) } }) } function addCookieItem(productId, action){ console.log('Not Logged in') if (action == 'add'){ if (cart[productId] == undefined){ cart[productId] = {'quantity': 1} } else { cart[productId]['quantity'] += 1 } } if (action == 'remove'){ cart[productId]['quantity'] -= 1 if (cart[productId]['quantity'] <= 0){ console.log('Remove Item') delete cart[productId] } } console.log('Cart:', cart) document.cookie = 'cart=' + JSON.stringify(cart) + ";domain=;path=/" location.reload() } function updateUserOrder(productId, action){ console.log('User … -
Django Not Sending Tasks to Celery in Production
I am a deployer and delpoys django applications using gunicorn & nginx. Recently, I setup a celery project and here are my services: Gunicorn Project Service [Unit] Description=gunicorn daemon for my project After=network.target [Service] User=user Group=www-data WorkingDirectory=/home/user/myproject ExecStart=/home/user/myproject/myenv/bin/gunicorn --access-logfile - --workers 3 --bind unix:/home/user/myproject/project.sock project.wsgi:application [Install] WantedBy=multi-user.target Celery Service [Unit] Description=Celery Worker Service for my project After=network.target [Service] Type=simple User=user Group=www-data WorkingDirectory=/home/user/myproject ExecStart=/home/user/myproject/myenv/bin/celery -A project worker -l info Restart=always [Install] WantedBy=multi-user.target Celery Logs are stuck at: celery@server ready. But When I run python3 manage.py runserver in production celery logs updates & my task works but not when I use direct service... I tried changing celery to solo worker --pool=solo -l info [celery service] but that didn't work. My Server RAM & CPU is not being fuly utilized so that's not an issue. Thank You! -
Django miss static files after packaging with pyinstaller
I packaged my django project with pyinstaller, my project tree is like below: I did all bellow steps: Copy all static file into static/ with python manage.py collectstatic Add all static file in .spec file like this: datas=[ ('remotescope/templates/remotescope/', 'remotescope/templates/remotescope'), ('static/', 'static'), ('remotescope/logging.conf', '.'),], Update setting.py like this: STATIC_URL = '/static/' STATIC_ROOT = os.path.join(BASE_DIR, 'static') But when I try to run my executable file with command of ./RemoteScope runserver 0.0.0.0:8000 --noreload, it info that all static files not found like bellow: 2024-03-30 09:35:51,125 - 139621882558208 - django.request - WARNING - Not Found: /static/admin/css/base.css [30/Mar/2024 09:35:51] "GET /static/admin/css/nav_sidebar.css HTTP/1.1" 404 2288 ... 2024-03-30 09:35:51,134 - 139621795096320 - django.request - WARNING - Not Found: /static/admin/css/login.css [30/Mar/2024 09:35:51] "GET /static/admin/css/login.css HTTP/1.1" 404 2270 BTW: Everything is good in debug mode wiht cmd of "python manage.py runserver 0.0.0.0:8000"(Need modify the setting.py) Anybody has some advice? Thank u very much~ -
SSL/DNS Connection Issue: Too Many Redirections
I have a problem connecting to my VPS server using domain name. I installed SSL certificate on my Debian 10 Docker server and https works only with IP address, when I try to connect with domain name it says 503 Backend Not Found. I tried to do it without nginx and now I configured it with nginx and I am at the moment when it says "Too many redirects". I tried a lot of solutions but I haven't found anything similar to this. Here is my nginx.conf script: events { worker_connections 1024; } http { upstream web { server web:8000; } server { listen 80; listen [::]:80; server_name domain.com; return 301 https://$server_name$request_uri; } server { listen 443 ssl http2; listen [::]:443 ssl http2; server_name domain.com; ssl_certificate /etc/letsencrypt/live/domain.com/fullchain.pem; ssl_certificate_key /etc/letsencrypt/live/domain.com/privkey.pem; location / { proxy_pass http://web; proxy_set_header Host $host; proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for; proxy_set_header X-Forwarded-Proto https; proxy_buffering off; proxy_redirect off; } } } and here is my docker-compose.yml: version: '3' services: web: build: . ports: - "8000:8000" volumes: - .:/app command: python3 manage.py runserver 0.0.0.0:8000 nginx: image: nginx:alpine ports: - "80:80" - "443:443" volumes: - /etc/nginx/nginx.conf:/etc/nginx/nginx.conf - /etc/letsencrypt:/etc/letsencrypt depends_on: - web restart: on-failure How to properly run an SSL server on a domain -
How to send Stripe session checkout parameters in subscription mode
I am quite new to stripe integration, and due to the country I am from, I cannot access the checkout session page due to account activation requirements. So, I am not able to see what all details are visible in the checkout page, and cannot debug it. (I am in test mode) I am quite confused about how I can sent the price id of the product I select. I have created two products in my dashboard, and I am displaying then on the frontend with a pay button that calls the checkout-session endpoint. this is my checkoutSession view class CreateCheckoutSession(APIView): def post(self, request): if request.method == 'POST': try: if request.user.is_authenticated: print(request.user) print(request.user.id) checkout_session = stripe.checkout.Session.create( client_reference_id=request.user.id, payment_method_types=['card'], line_items=[ { 'price': "", 'quantity': 1, }, ], mode='subscription', success_url=os.environ['DOMAIN_URL']+'/dashboard', cancel_url=os.environ['DOMAIN_URL'], ) return Response({'sessionId': checkout_session.id}) else: return Response({'message': 'You need to register first.'}, status=403) except InvalidRequestError as e: error_message = str(e) return Response({'error': error_message}, status=400) else: return Response({'error': 'Method not allowed'}, status=405) I think I should only send the price id or product id (which one am I supposed to send?) of the subscription I want to buy. I am not sure how can I do that. Could anyone please help me … -
Log out view in Django not working. It says method not allow
I tried using Django built in views to create a log out route But it doesn't work. It says method not allow I expected it to log out a user but it doesn't. Always getting error with that. But I imported the login view from Django views and it's working but the log out says method not allowed .Wish someone could help me -
Django parameter stops printing when it reaches the first question mark symbol
I have been learning the weird set-ups of Django! Its very good for web development! I have the following view inside views.py: def callerview(request,paramm): text="this is what was sent : %s"%paramm return HttpResponse(text) the url for this this view at urls.py is as follows: urlpatterns = [ path('callerview/<str:paramm>/', views.callerview, name='callerview'), ] Now, I am sending a word problem to it as the 'paramm'. It works and prints the word problem at localhost. But if the word problem has a question mark it stops printing when it gets to the first ? . so if the url looks like: callerview/why are roses red? why is the sky blue? Then, in the localhost output i will get: why are roses red AND no more! I need to be able to get all the symbols and letters in the word problem! in order to send to OpenAi assistants API. Any advice on how I can keep the ? symbol in the printout of the word problem? thank you -
Difficulty with hosting Multilingual Wagtail site on alwaysdata
my wagtail site has two languages English and German Facing some issues when deploying on alwaysdata.net I'm using these two apps for the multilingual feature in the INSTALLED_APPS list: "wagtail.locales", "wagtail.contrib.simple_translation", This is the middleware: "django.middleware.locale.LocaleMiddleware", these are the settings in settings.py: LANGUAGE_CODE = "en-us" TIME_ZONE = "UTC" USE_I18N = True WAGTAIL_I18N_ENABLED = True USE_L10N = True USE_TZ = True WAGTAIL_CONTENT_LANGUAGES = LANGUAGES = [ ('en', "English"), ('de', "German") ] WAGTAIL_CONTENT_LANGUAGES_FALLBACK = {'default': 'en',} I have the following code in the main urls.py file: urlpatterns += i18n_patterns ( path("", include(wagtail_urls)), prefix_default_language=True, ) The project is running fine locally and also running fine in production server (with DEBUG=TRUE) My problem is, In Production server when I set DEBUG to False the multilingual features gets messed up. I have to manually add /en/ or /de/ at the end of the url to see the pages in the browser for example if I click on the logo (from nav) which has the url set to '/' , it redirects to mydomain.com , but it should be mydomain.com/en/ or mydomain.com/de/ depending on which language currently selected. with DEBUG=True it redirects to mydomain.com/en/ or mydomain.com/de/ when clicking on the logo(you can say homepage) perfectly. What … -
Django deployment with GTK3
I have cretaed a django app, which uses weasyprint to convert html to pdf. This needed GTK3 to be installed on my local system. Now I'm not able to deploy on FL0. I checked the docs which said problems with deployment might be because the code couldn't be run properly. When I first used weasyprint, I was not able to run the app until I installed GTK3 on my laptop. So, I guess this is the issue. Is there any way to do this other than using docker. Or are there any libraries that does not use GTK3. I'll provide any details required. If anyone needs. Thanks. I have an option of containerizing the application. But I'm not able to do so at the moment for some other reasons. That's why I'm asking this -
How to start a download and render a response without hitting disk?
So I have a scientific data Excel file validation form in django that works well. It works iteratively. Users can upload files as they accumulate new data that they add to their study. The DataValidationView inspects the files each time and presents the user with an error report that lists issues in their data that they must fix. We realized recently that a number of errors (but not all) can be fixed automatically, so I've been working on a way to generate a copy of the file with a number of fixes. So we rebranded the "validation" form page as a "build a submission page". Each time they upload a new set of files, the intention is for them to still get the error report, but also automatically receive a downloaded file with a number of fixes in it. I learned just today that there's no way to both render a template and kick off a download at the same time, which makes sense. However, I had been planning to not let the generated file with fixes hit the disk. Is there a way to present the template with the errors and automatically trigger the download without previously saving the … -
why meta class giving error for abstract?
customUser(AbstractBaseUser,PermissionsMixin): id = models.autofield(primary_key = True) class Meta: verbose_name = 'User' verbose_name_plural = 'Users' abstract = True when I wrote abstract = True its giving error like django.core.exceptions.ImproperlyConfigured: AUTH_USER_MODEL refers to model 'core.CustomUser' that has not been installed but settings.py is properly set. run my project properly -
Adding and Annotated Field in Django Queryset
I have a Django application. I have 3 Django models like this: //Model 1: class ModelAOrders(models.Model): id = models.CharField(primary_key=True, max_length=16) plant_num = models.ForeignKey(Plant, db_column='plant_num', db_index=True, on_delete=models.CASCADE) purchase_order_num = models.CharField(max_length=10) purchase_order_item_num = models.CharField(max_length=5) material_num = models.ForeignKey(Material, db_column='material_num', db_index=True, on_delete=models.CASCADE) current_delivery_dt = models.DateField(null=True) lastest_delivery_dt_modification_dt = models.DateField(null=True) ..... [Other Fields] class Meta: db_table = 'modelA_po' //Model 2: class ModelBFlags(models.Model): purchase_order = models.ForeignKey(ModelAOrders, null=True, on_delete=models.CASCADE) purchase_order_num = models.CharField(max_length=10) purchase_order_item_num = models.CharField(max_length=5) shipped_flg = models.BooleanField(default=False) delivered_flg = models.BooleanField(default=False) expedite_flg = models.BooleanField(default=False) class Meta: db_table = 'modelB_flags' //Model 3: class ModelCBackorders(models.Model): bo_id = models.CharField(max_length=255, blank=True, null=True) bo_start_date = models.DateField(blank=True, null=True) bo_end_date = models.DateField(blank=True, null=True) material_num = models.ForeignKey(Material, db_column='material_num', db_index=True, on_delete=models.CASCADE) mrpcn = models.CharField(max_length=3, blank=True, null=True) mrpcn_mapping = models.ForeignKey(MrpcnMapping, null=True, on_delete=models.CASCADE) planned_delivery_time_value = models.FloatField(null=True) .... [Other Fields] class Meta: db_table = 'modelC_backorders' How can I add an annotated field to my backorder query set based on the SQL code below: SQL Equivalent: SELECT SUM(distinct(opo.outstanding_qty)) FROM apple.modelC_backorders kb LEFT JOIN apple.modelA_po opo ON kb.material_num = opo.material_num LEFT JOIN apple.modelB_flags iof ON opo.id = iof.purchase_order_id WHERE iof.shipped_flg=1 AND opo.outstanding_qty>0 GROUP BY kb.material_num, opo.purchase_order_num, opo.purchase_order_item_num; This is what I have so far but it retuns null for all values. backorders_queryset = ModelCBackorders.objects.annotate( inbound_shipped_qty=Subquery( ModelAOrders.objects.filter( material_num=OuterRef('material_num'), modelbflags__shipped_flg=True, outstanding_qty__gt=0 ).annotate( total_outstanding_qty=Sum('outstanding_qty', distinct=True) … -
Problems with automatic pagination in Django, how to fix duplicate posts?
The problem is that duplicated posts appear during automatic pagination. If the loop {% for post in post_lists %} in the home.html template specifies the output of 5 published posts, then during automatic pagination, duplicates of these 5 published posts are added from the home_list.html template, which is incorrect. Automatic pagination works correctly and displays all published posts properly. The issue only lies with the duplication of the first five published posts; the rest of the posts are not duplicated and are displayed correctly. How to fix this? home.html: {% for post in post_lists %} <div class="post_content" id="post_content"> <!----code for displaying posts goes here----> </div> {% endfor %} <div id="pagination-loader" class="pagination_pages" data-page="1"></div> </div> <script> $(document).ready(function(){ var loadedPage = 1; // Variable to store the loaded page number // Function to load the next batch of posts function loadNextPage() { // Perform an AJAX request to the server var nextPageUrl = '/load-posts/?page=' + loadedPage; console.log("Next page URL:", nextPageUrl); $.ajax({ url: nextPageUrl, type: 'GET', dataType: 'json', success: function(response) { console.log("Response from server:", response); // Check for post data in the JSON response if (response.posts) { // Add HTML with posts to the end of the container $('#post_contenter').append(response.html_posts); // Check if there are … -
django migrate from CIEmailField to collation
I did upgrade from django version to 4.2.8 and then the CIEmailField() is deprecated. I used this CIEmailField on the email field of an user. So I had to change to: email = models.EmailField(unique=True, db_collation="case_insensitive") So the migration is like this: operations = [ CreateCollation( "case_insensitive", provider="icu", locale="und-u-ks-level2", deterministic=True, ), migrations.AlterField( model_name="user", name="email", field=models.EmailField(db_collation="case_insensitive", max_length=254), ), ] But before this changement, with CIEmailField I would .get() an user with this email "test@test.com" or "TEST@test.com". With the case_insensitive collation I made it work only by setting "deterministic=False". But with that, the SQL's LIKE is not working. So every Viewset with "email" in "search_fields" wont work. To make it work, I only found this solution: class UserAdmin(BaseUserAdmin): search_fields = ("email_deterministic", ...) ... def get_queryset(self, request: HttpRequest) -> QuerySet[User]: return ( super() .get_queryset(request) .annotate( email_deterministic=Collate("email", "und-x-icu"), ) ) So I have to do that EVERYWHERE on the App when I have an user to search by his email. But the App is big. Is there any other solution for this? -
Creating Azure B2B login system with Vue.js frontend & Python Django backend
I'm working on a full stack application using Vue.js for the frontend and Python Django for the backend. Now I want to set up my login system based on Microsoft Entra for my tenant (B2B). As my website is a SPA, my initial thought was to set it up with MS docs for public client. See also here. I've got it working. However, as I have a webapp with backend, this approach would be more suitable and safe (right!?). I'm trying to implement this logic, but as this logic is rendering the frontend from the python files I'm confused (as i'm rendering and organizing my front-end logic from the Vue.js side). My question is, what would be the best approach for my application, and how to proceed? I'm aware that my question is broad, but I'm really stuck... Implemented this logic successfully, but this approach is probably more safe/suitable. -
Sending emails in django using smtp
on my site i am trying to reset my password by e-mail using smtp but when i send a password change request i get this error: here is my settings.py : EMAIL_BACKEND = 'django.core.mail.backends.smtp.EmailBackend' EMAIL_HOST = 'smtp.gmail.com' EMAIL_PORT = 587 EMAIL_HOST_USER = 'expresstest177@gmail.com' EMAIL_HOST_PASSWORD = "ibuc pvmq fkgb acah" EMAIL_USE_TLS = True EMAIL_USE_SSL = False DEFAULT_FROM_EMAIL = EMAIL_HOST_USER SERVER_EMAIL = EMAIL_HOST_USER EMAIL_ADMIN = EMAIL_HOST_USER and urls.py if needed: urlpatterns = [ path('password-reset/', auth_views.PasswordResetView.as_view( template_name='main/password_reset_form.html', email_template_name='main/password_reset_email.html', success_url=reverse_lazy('user:password_reset_done')), name='password_reset'), path('password-reset/done/', auth_views.PasswordResetDoneView.as_view(template_name='main/password_reset_done.html'), name='password_reset_done'), path('password-reset/confirm/<uidb64>/<token>/', auth_views.PasswordResetConfirmView.as_view( template_name='main/password_reset_confirm.html', success_url=reverse_lazy('user:password_reset_complete')), name='password_reset_confirm'), path('password-reset/complete/', auth_views.PasswordResetCompleteView.as_view(template_name='main/password_reset_complete.html'), name='password_reset_complete'), ] what could be the problem? -
Import CSV file from React front end to Django/Python backend proving unreliable
I am trying to get data from a csv file that is uploaded via a ReactJs front end and then import it into a sqlite database in a Django/Python backend. I am trying to use the same code for several different imports and I have at least two cases that work but when I try to replicate the code, it is not working. It does seem that a csv generated from Excel or from another system does work but I have a mac and if I try to edit the csv either using my VS Code editor or using Numbers (but exporting as a csv) the file then doesn't work. If I inspect the file in VS code though, I can't see any difference between the ones that work and the ones that do not. All are in utf. Is this a problem with the csv? And is there code I can add to diagnose that... and maybe rectify? FRONTEND: import axios from 'axios' import { formatTimeDate } from '../../lib/helpers' class CSVDataLoader extends Component { constructor() { super() this.state = { loading: false, updated: '' } this.handleSubmitData = this.handleSubmitData.bind(this) this.handleFile = this.handleFile.bind(this) } handleFile (e) { e.preventDefault() const fileToUpload = … -
Issue with Django --> Apache WSGI deployment
I have a django app running in VS Code 1.86.2 on a Debian 12 machine using Python 3.11.2. I'm working on a test deployment to Apache 2.4.57 and mod_wsgi 4.9.4. I've been working through docs from Apache and Django. At this point I am able to load html documents from the deployed site, but the Django template tags are not being processed. For example I see the below text in the browser. {% extends "base.html" %} {% block title %}my app{% endblock %} {% block content %} {% csrf_token %} Record Lookup Search Key: {% endblock %} I'm new to the Django and Apache world so hoping for some guidance on where to start diagnosing this issue. Any guidance is much appreciated! -
Should i use GET or POST for request with body in DRF?
I am relatively new to the web development and I am writing backend for webapp for practicing chemical elements and compounds and their formulas in our school. I am using Django and Django Rest Framework. I have encountered a dilemma where I can't decide whether to use GET method or POST method. In frontend it requests compounds and elements from the server with specific criteria. In this view, it recieves request with body (criteria), where are values requested_count, used_ids (to exclude already used compounds/elements), requested_groups, requested_elements (to exclude elements which may students don't know). Then, it filters the database to return the response. I have tested this many times and it is working correctly. My only question is, which method to use in this view. I know that POST should be used when I want to change something in the database and GET to just get query from the database. According to this I should use GET. But I want to send body with that request and that is something what POST typically does. What do you suggest? Thanks Here is the view code: class RequestCompoundsView(views.APIView): serializer_class = RequestCompoundsSerializer def get(self, request): serializer = self.serializer_class(data=request.data) if serializer.is_valid(): # Get the …