Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Issue with connecting postgresql in django
i made a project on django. i work in virtualenv, i installed psycopg2-binary, tried to connect postgresql instead of sqlite3. rewrite code in settings.py DATABASES = { 'default': { 'ENGINE': 'django.db.backends.postgresql', 'NAME': 'database', 'USER': 'user', 'PASSWORD': 'mypassword', 'HOST': 'localhost', 'PORT': '5432', } } and when enter python manage.py runserver, i get this Watching for file changes with StatReloader Performing system checks... conn = _connect(dsn, connection_factory=connection_factory, **kwasync) psycopg2.OperationalError: connection to server at "localhost" (127.0.0.1), port 5432 failed: FATAL: password authentication failed for user "user" connection to server at "localhost" (127.0.0.1), port 5432 failed: FATAL: password authentication failed for user "user" The above exception was the direct cause of the following exception: Traceback (most recent call last): File "/usr/lib/python3.10/threading.py", line 1016, in _bootstrap_inner self.run() File "/usr/lib/python3.10/threading.py", line 953, in run self._target(*self._args, **self._kwargs) File "/home/user/Desktop/project/venv/lib/python3.10/site-packages/django/utils/autoreload.py", line 64, in wrapper fn(*args, **kwargs) File "/home/user/Desktop/project/venv/lib/python3.10/site-packages/django/core/management/commands/runserver.py", line 136, in inner_run self.check_migrations() File "/home/user/Desktop/project/venv/lib/python3.10/site-packages/django/core/management/base.py", line 574, in check_migrations executor = MigrationExecutor(connections[DEFAULT_DB_ALIAS]) File "/home/user/Desktop/project/venv/lib/python3.10/site-packages/django/db/migrations/executor.py", line 18, in __init__ self.loader = MigrationLoader(self.connection) File "/home/user/Desktop/project/venv/lib/python3.10/site-packages/django/db/migrations/loader.py", line 58, in __init__ self.build_graph() File "/home/user/Desktop/project/venv/lib/python3.10/site-packages/django/db/migrations/loader.py", line 235, in build_graph self.applied_migrations = recorder.applied_migrations() File "/home/user/Desktop/project/venv/lib/python3.10/site-packages/django/db/migrations/recorder.py", line 81, in applied_migrations if self.has_table(): File "/home/user/Desktop/project/venv/lib/python3.10/site-packages/django/db/migrations/recorder.py", line 57, in has_table with self.connection.cursor() as cursor: File "/home/user/Desktop/project/venv/lib/python3.10/site-packages/django/utils/asyncio.py", line … -
POST http://127.0.0.1:8000/customRegisterForm/UploadImageViewSet/ 415 (Unsupported Media Type)
While Posting the image from react JS using fetch operation getting the error 415 (Unsupported Media Type) and for backend used django Error in console: enter image description here Here is React JS code: UploadImages.js `import React from "react" export default function UploadImages() { const [picture, setPicture] = React.useState({}) function data(event) { setPicture((prevPicture) => { return { ...prevPicture, [event.target.name]: [event.target.value] } }) } console.log(picture) function handleChange(event) { event.preventDefault() fetch("http://127.0.0.1:8000/customRegisterForm/UploadImageViewSet/", { method: "POST", body: JSON.stringify({ upload_name: picture.upload_name, image_upload: picture.image_upload, }), header: { "Content-Type": "application/json" }, }); } return ( <div> <form onSubmit={handleChange}> Name: <input type="text" name="picture.upload_name" onChange={data} placeholder="Name" value={picture.upload_name} /><br /> <input type="file" name="picture.image_upload" onChange={data} accept="image/jpeg, image/png" value={picture.image_upload} /><br /> <button>Submit</button> </form> </div> ) } ` Models.py `class UploadImage(models.Model): upload_name = models.TextField(max_length=50, blank=False) image_upload = models.ImageField(upload_to="UserUploadImage/", blank=True, null=True) Serializers.py class UploadImageSerializer(serializers.ModelSerializer): class Meta: model = UploadImage fields = ('id', 'upload_name', 'image_upload') ` Url.py router.register("UploadImageViewSet", UploadImageViewSet) Views.py class UploadImageViewSet(viewsets.ModelViewSet): queryset = UploadImage.objects.all() serializer_class = UploadImageSerializer I tried all the possibilities but did not got solution, please help to get solution. Thanks! Need solution for POST http://127.0.0.1:8000/customRegisterForm/UploadImageViewSet/ 415 (Unsupported Media Type) -
Django rest api and axios post request doesn't add new instance
am trying to make a simple api where a user writes something in a field, presses a button and a new instance is added in the database. To do this I am using react and django rest framework. App.js const [name,setName] = useState('') const handleChange = (e) => { setName(e.target.value) } function handleClick(e) { axios.defaults.xsrfCookieName = 'csrftoken' axios.defaults.xsrfHeaderName = "X-CSRFTOKEN" axios.post('http://127.0.0.1:8000/post/', { headers: { "Content-Type": "application/x-www-form-urlencoded", 'X-CSRFToken': 'csrftoken' }, data:{ title: name, name: name } }) } return ( <> <form> <input type='text' value={name} onChange={handleChange} /> <button onClick={handleClick}>OK</button> </form> </> ); views.py @api_view(['POST']) def home2(request): serializer = ItemSerializer(data=request.data) if serializer.is_valid(): serializer.save() return Response(serializer.data) urls.py from django.urls import path from . import views urlpatterns = [ path('api/',views.home,name='home'), path('post/',views.home2,name='home2'), path('a/',views.home3,name='home3') ] settings.py INSTALLED_APPS = [ 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'rest_framework', 'main', 'corsheaders' ] CORS_ORIGIN_ALLOW_ALL = True CORS_ALLOW_CREDENTIALS = True But when I press the button I get manifest.json:1 GET http://127.0.0.1:8000/manifest.json 404 (Not Found) and manifest.json:1 Manifest: Line: 1, column: 1, Syntax error. in javascript. In django I get "POST /post/ HTTP/1.1" 200 0 Also I am using npm run build for javascript and manifest.json is in public folder. React is inside django and the structure looks like this: mysite frontend … -
Django 4.2 : `receiver` Decorator Does Not Receive Signal
I am experimenting with Django Signals. In the documentation, it is written that there are two ways to connect a receiver to a signal. Using Signal.connect method Using receiver decorator Here's what I have implemented: # models.py from django.db import models from django.dispatch import receiver from .signals import demo_signal class Demo(models.Model): demo = models.CharField("demo", max_length=50) def send_signal(self): demo_signal.send(self) print('signal sent') def connect_receiver(self): demo_signal.connect(signal_handler, sender=self) @receiver(demo_signal, sender=Demo) def signal_handler(**kwargs): print('signal handled') # signals.py from django.dispatch import Signal demo_signal = Signal() However, when I call send_signal method, I don't get signal handled printed out unless I call connect_receiver method first. In [1]: demo = Demo.objects.get(pk=2) In [2]: demo Out[2]: <Demo: Demo object (2)> In [3]: demo.send_signal() signal sent In [4]: And Interestingly enough, after implementing pre_delete_handler as follows, without connecting, calling delete method does call pre_delete_handler @receiver(pre_delete, sender=Demo) def pre_delete_handler(instance, **kwargs): print(instance, kwargs) print('pre delete') Receiver does receive the signal without sender argument: @receiver(pre_delete) def pre_delete_handler(instance, **kwargs): print(instance, kwargs) print('pre delete') But how can I make it listen to a specific Model? Why does sending signal does not call its receiver(decorated signal_handler) in my case? -
How to configure APscheduler to use it with django_tenants
I am using django and django rest framework with multi teancy system. For multitenancy I am using django_tenants package, If I add "apscheduler" to TENANT_APPS and run migrate_schemas command I get this error Error getting due jobs from job store 'default': relation "rest_apscheduler_djangojob" does not exist LINE 1: ...d", "rest_apscheduler_djangojob"."job_state" FROM "rest_apsc... -
In Azure i wanto run a worker like heroku
Previously I have hosted my web application in heroku there I have two dyno in procflie i have this two line of code web: gunicorn project.wsgi worker: python manage.py fetch_data worker is custom script that fetch data and store it in postgresql.. i can run scrip locally and push data in azure from local pc but i want to host this in azure like heroku where custom script named fech_data works automatically. many tutorial says about webjob. but there is no webjob option in my web application. it is hosted in linux environment. -
Sending Email via Django Backend for forgeting Password
Hello I'm working with Django for sending Email for forgeting password. I'm trying to use Django class based views to handle this forget password but, It was not worked properly. here is my code : settings.py EMAIL_BACKEND = 'django.core.mail.backends.smtp.EmailBackend' EMAIL_HOST = 'smtp.gmail.com' EMAIL_USE_SSL = False EMAIL_USE_TLS = True EMAIL_PORT = 587 EMAIL_HOST_USER = config("EHU") # set my email EMAIL_HOST_PASSWORD =config("EHP") # set my app password views.py from django.urls import reverse_lazy from django.views.generic import FormView from django.contrib.auth.views import ( LoginView, LogoutView, PasswordResetView, PasswordResetConfirmView, PasswordResetCompleteView ) from .models import UserAccount from .forms import RegisterForm class LoginPageView(LoginView): template_name = "login.html" def get(self, request, *args, **kwargs): if request.user.is_authenticated: return reverse_lazy("/") return super().get(request, *args, **kwargs) class LogoutPageView(LogoutView): template_name = "logout.html" class SignupPageView(FormView): template_name = "register.html" form_class = RegisterForm success_url = reverse_lazy("/") def get(self, request, *args, **kwargs): if request.user.is_authenticated: return reverse_lazy("/") return super().get(request, *args, **kwargs) def form_valid(self, form): new_user = UserAccount.objects.create_user( email=form.cleaned_data['email'], username=form.cleaned_data['username'], password=form.cleaned_data['password'], first_name=form.cleaned_data['first_name'], last_name=form.cleaned_data['last_name'], pic=form.cleaned_data['pic'], description=form.cleaned_data['description'], # TODO : If you add other fields to your model, include them here ) return super().form_valid(form) class PasswordChangePageView(PasswordResetView): template_name ="pass_change.html" email_template_name = "pass_change_email.html" subject_template_name = "password_reset_subject.txt" success_message =""" We've emailed you instructions for setting your password, if an account exists with the email you entered. You should … -
how to implement foreign key popup to add django admin panel functionality on django app
I want implement popup to add like django admin panel in my django app. please guide me. -
Redis connection scheduled to be closed ASAP for overcoming of output buffer limits
I have some celery tasks that run on VMs to run some web crawling tasks. Python 3.6, Celery 4.2.1 with broker as Redis (self-managed). The same Redis server is used for caching and locks. There are two relevant tasks: 1. job_executor: This celery worker runs on a VM and listens to the queue crawl_job_{job_id}. This worker will execute the web crawling tasks. Only a single job_executor worker with concurrency = 1 runs on 1 VM. Each Crawl Job can have 1-20,000 URLs. Each Crawl Job can have anywhere between 1 to 100 VMs running in a GCP Managed Instance Group. The number of VMs to be run are defined in a configuration for each crawl job. Each task can take from 15 seconds to 120 minutes. 2. crawl_job_initiator: This celery worker runs on a separate VM and listens to the queue crawl_job_initiator_queue. One task creates the required MIG and the VMs using terraform for a single Crawl Job ID and adds the job_executor tasks to the crawl_job_{job_id} queue. The task takes about 70 seconds to complete. The concurrency for this worker was set to 1 so only 1 Crawl Job could be started at once. To reduce the time it … -
Django project ModuleNotFoundError: No module named '_sqlite3'
OS bsd 13.2 on dedicated rental server csh terminal python3.9.17 system and venv Django 4.2.2 wanting to learn django, I set up a venv and installed django there. all good but at (django) pyweb@os3-286-32838:~/django/eigoweb % python3 manage.py runserver things seem to be loading but it stalls at the end with... File "/usr/local/lib/python3.9/importlib/init.py", line 127, in import_module return _bootstrap._gcd_import(name[level:], package, level) File "/home/pyweb/django/lib/python3.9/site-packages/django/db/backends/sqlite3/base.py", line 9, in from sqlite3 import dbapi2 as Database File "/usr/local/lib/python3.9/sqlite3/init.py", line 57, in from sqlite3.dbapi2 import * File "/usr/local/lib/python3.9/sqlite3/dbapi2.py", line 27, in from _sqlite3 import * ModuleNotFoundError: No module named '_sqlite3' while the venv is activated I tried to import sqlite3 from python3 import sqlite3 Traceback (most recent call last): File "", line 1, in File "/usr/local/lib/python3.9/sqlite3/init.py", line 57, in from sqlite3.dbapi2 import * File "/usr/local/lib/python3.9/sqlite3/dbapi2.py", line 27, in from _sqlite3 import * ModuleNotFoundError: No module named '_sqlite3' I get the same message with the system python. so.. the module is not there it seems After reading several posts here I added PYTHONPATH in the venv to where there appeared to be sqlite3 module but it was not _sqlite3 so I guess that is the problem? pyweb@os3-286-32838:~/django/lib/python3.9/site-packages % ls Django-4.2.2.dist-info dbrelmgr.py pycache distutils-precedence.pth _distutils_hack django antiorm-1.2.1.dist-info pip … -
how to write select_for_update test?
def db_lock_on_resource(self, resource_id): list(Models.objects.select_for_update().filter(id=resource_id)) I have this storage function call and I want to write a test for it using Py-Test. How can I write it? What should I assert? -
htmx not working on newly added form in django inline_formset
I have a form for my Purchase Order in which the items are presented in tabular format using django inline_formset. Within the form of the inline_formset, a search icon is placed beside the product select-form such that when the user will click on it, a modal will popup providing a functionality to the user to be able to search a product. And when the user will click a product on the search page, the corresponding product select-form in the main PO form will be updated/changed with the searched product. There is also an "Add more items" button which will add new form to the inline_formset, thereby providing a functionality to the user to dynamically add more PO items (using javascript). All the abovementioned features work fine except that in the newly added, the search icon failed to execute the hx-get embedded within the icon, like so: In pod_form.html, td> <div class="input-group"> {{ field }}{% if field.name == 'product' %} <i class="fa-solid fa-magnifying-glass ms-1 d-flex align-items-center fa-icon" hx-get="{% url 'product_search_popup' %}" hx-target="#dialog"></i> {% endif %} </div> <!-- dispaly field errors if there's any --> {% for error in field.errors %} <span style="color: red">{{ error }}</span> {% endfor %} </td> this html … -
Is this the right way to use python maigret module?
I am using "maigret" module in Django application to search usernames in social medias. Maigret can only be used through cli so i had to use subprocess to run and get the output. But is this the best way to do it? I couldn't find any other solution. Below is the function that i have created. def SearchNames(request): if request.method == 'POST': try: data = json.loads(request.body) name = data.get('name', '') network = data.get('network', '') output = subprocess.run('maigret {} --site {}'.format(name, network), shell=True, capture_output=True).stdout outputs = output.decode("utf-8").split("\n") matching = [s for s in outputs if "Search by username" in s][0] total_account_found = [int(s) for s in matching.split() if s.isdigit()][0] print({"accountsFound":total_account_found, "network":network}) return JsonResponse({"accountsFound":total_account_found, "network":network}, safe=False) except: return JsonResponse({'error': 'Error occurred while searching for username'}, status=400) return JsonResponse({'error': 'Invalid request'}, status=400) I wanted to know if there is better way to use maigret other than subprocess. -
Django - Pre-fetching ForeignKeys for M2M set
I see this thread which is the reverse (pre-fetching M2M set for foreignkey) - but how can I prefetch the ForeignKeys for a M2M set (as well pre-fetching the initial M2M set)? E.g. I have the following objects: Genre, Book, and Author. A Book can only have one Author. A Genre can have many Books (and vice versa) On my Genre Detail page, I would like to prefetch and list all the Books (M2M set) as well as prefetch all the Authors for each Book (ForeignKey). None of the following seem to work: Genre.objects.all().prefetch_related("book_set", "book_set__author") Genre.objects.all().prefetch_related("book_set").select_related("book_set__author") Genre.objects.all().prefetch_related("book_set").select_related("author") -
How can I make 'submit' in html delete a variable in python? (I am using Flask)
I am trying to make {{password}} change to a different password each time 'submit' is pressed. I am using Flask with html to do this. The function that creates the password is written in python. I have tried making password an empty string in the Flask file expecting it to be empty each time 'Submit' is pressed. However, it did not change the password. I am trying to change {{password}} to a new {{password}} each time submit is pressed. from flask import Blueprint,render_template, request, g from gen import main #This is where the different website pages will be implemented with python views = Blueprint(__name__,'views') @views.route('/') def home(): return render_template('home.html') @views.route('/index.html') def generator(): return render_template('index.html', password = '') @views.route("/result", methods=['POST', 'GET']) def result(): password = '' return render_template("result.html",password = password + main()) def main(): pword ='' while True: x = randint(randint(20,30),randint(30,40)) randoml = [] while len(password) < x: lettersL = letters(alphabet) numbersL = numbers(alphabet) symbolsL = symbols(alphabet) randoml.append((random.choice(lettersL))) randoml.append((random.choice(numbersL))) randoml.append((random.choice(symbolsL))) if len(randoml) > 10000: password.append(random.choice(randoml)) pword = ''.join(password) return pword <html> <head>Generated Password</head> <body> <form class = "password" action = "/result" method = "POST"> <center> {% if password%} <h3 style="color: rgb(216, 44, 216)">Your password is {{password}}</h3> {% endif%} </center> </form> <form … -
Calculate Pyton Enum each time when evaluated with datetime?
Is there a way to create an Enum in Python that calculates the value each time the Enum attribute is accessed? Specifically, I'm trying to create an Enum class that stores values like TODAY, TOMORROW, etc. for a web app (in Django) that runs for many days and I want the value recalculated each time it's accessed in case the day changes. So, say, the app is launched on March 1, if the app makes the check for TODAY on March 3, it will return March 3 and not March 1 which is what it would be initialized for. from enum import Enum import datetime class MyEnum(Enum): TODAY = datetime.datetime.now() TOMORROW = datetime.datetime.now() + datetime.timedelta(days=1) -
How to return back to original page after redirect?
I'm building a webpage that needs an age-gate. For this to work I'm using Django sessions. The view checks if the age-gate has been passed and otherwise redirects the user back to the age-gate. After A user passed the age-gate I want to redirect them back to the page they came from. How do I do this? I tried using request.META.get('HTTP_REFERER') but that did not work. My view looks like this: `def main_view(request): if request.session.has_key('agegate'): random_category = random.choice(Category.objects.all()) random_picture = random.choice(CoreImages.objects.all()) context = { 'image' : random_picture, 'category' : random_category, 'bottles': Bottle.objects.all(), } return render(request,'Academy/home.html', context) else: return redirect('/preview/agegate')` The age-gate view looks like this: def age_gate_view(request): next_url = request.META.get('HTTP_REFERER') form = AgeGateForm() if request.method == 'POST': form = AgeGateForm(request.POST or None) if form.is_valid(): form.save() request.session['agegate'] = 'welcome' return HttpResponseRedirect(next_url) context = { 'form':form, } return render(request,'Academy/agegate.html', context) -
ManyToManyField not saving correctly
I have an item_option this is a ManyToManyFiled that links to an ItemOption model. In the Django panel, I can insert ItemOptions, and they are saved correctly in the database, but product.item_option.all() returns an empty array. I found that the ItemOption is being inserted but nothing is being inserted in the ManyToManyTable database_product_item_option. Manually adding the indexes to this table fixes the problem, and I can successfully retrieve ItemOptions using product.item_option.all() How can I make Django do this automatically? I feel like I'm close to the solution but I haven't been able to find what's wrong with my code or what's missing. Here's my code: Product class Product(models.Model): id = models.AutoField(primary_key=True) ... item_option = models.ManyToManyField('ItemOption', blank=True, related_name='item_option') ItemOption class ItemOption(models.Model): product = models.ForeignKey(Product, on_delete=models.CASCADE) name = models.CharField(max_length=100, blank=True, null=True) price = models.DecimalField(max_digits=10, decimal_places=2) default = models.BooleanField(default=False) Form class ItemOptionForm(forms.ModelForm): class Meta: model = ItemOption fields = ['name', 'price', 'default'] class ItemOptionInline(admin.TabularInline): model = ItemOption form = ItemOptionForm extra = 1 can_delete = True class ProductAdmin(admin.ModelAdmin): list_display = ('title', 'price', 'product_type') list_filter = ('product_type', 'brand') exclude = ('item_option',) inlines = [ItemOptionInline] admin.site.register(Product, ProductAdmin) -
Django Rest Framework Overlaying Api Root
I want to create a browsable API on url level of /api. Browsable API is working for /api/v1 and /schema separately well, when I address the url explicitly. But I would like to create a browsable API a level above to browse to /v1 and /schema directly. This is my setup: django_project/config/urls.py from django.contrib import admin from django.urls import path, include from django.contrib.auth import views as auth_views from rest_framework import generics from rest_framework.response import Response from rest_framework.reverse import reverse urlpatterns = [ path('api/', include('my_api_app.router'), name="api"), path('admin/', admin.site.urls), ] django_project/my_api_app/router.py from django.urls import include, path from rest_framework import routers from rest_framework.schemas import get_schema_view from .v1.router import router as v1_router urlpatterns = [ path('schema', get_schema_view( title="Python API", description="API for all things", version="1.0.0", public=True ), name='openapi-schema'), path('v1/', include(v1_router.urls)), path('api-auth/', include('rest_framework.urls')), ] django_project/my_api_app/v1/router.py from django.urls import include, path from rest_framework import routers from . import views router = routers.DefaultRouter() router.register(r'testtable', views.TestTableViewSet) -
chartjs-plugin-zoom plugin not functioning on django
In my django project I'm trying to add zoom functionality to my line plot using the chartjs-plugin-zoom plugin. All other options I modify apart from 'plugins' are conveyed on the chart. I want the plugin section of my 'options' part below to end up being functional in my chart, as currently it isn't. I'm getting no errors in my console. I'm using the django-chartjs to manage my charts in django. My django template html head <head> <!-- Include jQuery library --> <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.7.0/jquery.min.js" integrity="sha512-3gJwYpMe3QewGELv8k/BX9vcqhryRdzRMxVfq6ngyWXwo03GFEzjsUm8Q7RZcHPHksttq7/GFoxjCVUjkjvPdw==" crossorigin="anonymous" referrerpolicy="no-referrer"></script> <script src="https://cdn.plot.ly/plotly-latest.min.js"></script> <script src="{% static 'assets/js/plugins/chart.js' %}"></script> <script src="{% static 'assets/js/plugins/hammer.min.js' %}"></script> <script src="{% static 'assets/js/plugins/chartjs-plugin-zoom.js' %}"></script> </head> The section of html to create the plot <div class="col-md-8"> <div class="card my-card" style="max-height: 530px"> <div class="card-header"> <div class="row justify-content-between"> <div class="col-4"> <h4 class="card-title">Hourly Timeseries</h4> </div> </div> </div> <canvas id="myChartline"></canvas> </div> </div> The script to create the plot <script type="text/javascript"> ChartOptionsConfiguration = { maintainAspectRatio: true, legend: { display: true, position: 'right', textAlign: 'right', }, elements: { point: { radius: 0, }, line: { borderWidth: 1, }, }, plugins: { zoom: { zoom: { wheel: { enabled: true, }, } }, legend: { labels: { usePointStyle: true, }, } }, tooltips: { backgroundColor: '#fff', titleFontColor: '#333', bodyFontColor: … -
Can not see any table in db.sqlite in django inner project
I am new to django. I installed the sqlite extension but I see some weird thing in my db.sqlite3 file in my inner project.This is showing in my db.sqlite3 I installed the sqlite extension to see the tables directly in db.sqlite3. But it doesn't change anything -
Password reset with Javascript and Django Rest Framework
I'm trying to use the Django Rest Framework library to reset the user's password. I followed some tutorials, mainly this one: https://pypi.org/project/django-rest-passwordreset/. However, none of the tutorials showed how to make the password reset independent of the frontend-to-backend address. The process described in all the tutorials I found follows a similar procedure. The user submits their email via the frontend to the backend, and then the backend sends an email to the user containing a link for password recovery. The problem, in my case, lies here. The backend needs to know the frontend's address, meaning the frontend's address needs to be hard-coded in the backend so that the link sent in the email directs to a page on the frontend. My question is: Is there any way for the backend to discover the frontend's address during the password recovery process? Alternatively, is there an easier way to implement password recovery? -
Django 4.2.2 Deployment to AWS ElasticBeanStalk failed
I'm trying to deploy my little Django web app to AWS Elasticbeanstalk but it fails evertime. i tried everything on the net from turorials to documentations but i can't find the problem. I even tried tried deploying a basic django project but same problem. the problem is not from my aws account because i succesfully deployed a sample app that aws provides when creating a elasticbeanstalk new application. **This is the log when deploying with aws website: **enter image description here **This is the log when trying to deploy with Elastic Beanstalk Client: **enter image description here I'm using the latest version of django and python. Thanks for your help guys in advance. i'm trying to deploy a basic Django app on AWS elastic beanstalk. -
Django: TemplateSyntaxError: Could not parse the remainder with user authorization
I am using django for a project and I am trying to let the user access a page if they are authenticated and authorized to perform that action. I have a model called Post and my app is called myblog. I am currently getting the error Django:Could not parse the remainder: '('myblog.add_Post')' from 'user.has_perm('myblog.add_Post')' {% extends 'base.html' %} {% block title %} Add Post... {% endblock %} {% block content %} {% if user.is_authenticated and user.has_perm('myblog.add_Post') %} <h1>Add A Blog Post</h1> <br/><br/> <div class="form-group"> <form method="POST"> {% csrf_token %} {{form.as_p}} <button class="btn btn-outline-success">Post</button> </div> {% else %} Access Denied! {% endif %} {% endblock %} If i remove the "and user.has_perm('myblog.add_Post')" this template works; however, I need to check if the user has permissions. -
Pickling issue in Django management command but works in regular Python environment
I am facing a pickling issue specifically when using the dfi.export() function within a Django management command, while the same code works without any issues in a regular Python environment. I am using Django version 2.2.4 and Python version 3.10.0 The code involves exporting a Pandas DataFrame to an image file using the dfi.export() function from the dataframe_image library. The goal is to generate an image file from the DataFrame within the Django management command. from decimal import Decimal import dataframe_image as dfi import pandas as pd def color_negative_red(val): color = 'red' if val < 0 else 'green' return 'color: %s' % color futures_risk_table_1={'PNL ITD': {'BTCUSDT': Decimal('-366.91850000'), 'ETHUSDT': Decimal('20.11800000'), 'TOTAL': Decimal('-241.39039746')}, 'FUNDING ITD': {'BTCUSDT': Decimal('285.87113447'), 'ETHUSDT': Decimal('11.23925312'), 'TOTAL': Decimal('230.66567605')}, 'DELTA VOLUME ITD': {'BTCUSDT': Decimal('11413146.44950000'), 'ETHUSDT': Decimal('3739417.96300000'), 'TOTAL': Decimal('16904364.71747007')}, 'HEDGE VOLUME ITD': {'BTCUSDT': Decimal('5858487.37460000'), 'ETHUSDT': Decimal('2208062.55358281'), 'TOTAL': Decimal('9812329.10964750')}, 'GROSS OI': {'BTCUSDT': 1142375.5, 'ETHUSDT': 34665.484173792, 'TOTAL': 1507336.3651526954}, 'DEFICIT': {'BTCUSDT': 4126.2, 'ETHUSDT': 6105.2643768768, 'TOTAL': 14643.812931051634}, 'PNL 4HR': {'BTCUSDT': Decimal('-110.42400000'), 'ETHUSDT': Decimal('-19.04450000'), 'TOTAL': Decimal('-58.85838895')}, 'FUNDING 4HR': {'BTCUSDT': Decimal('51.78039448'), 'ETHUSDT': Decimal('-0.15025893'), 'TOTAL': Decimal('35.63325078')}, 'DELTA VOLUME 4HR': {'BTCUSDT': Decimal('2554914.73350000'), 'ETHUSDT': Decimal('1032545.61450000'), 'TOTAL': Decimal('3892830.05291726')}, 'HEDGE VOLUME 4HR': {'BTCUSDT': Decimal('1393409.78960000'), 'ETHUSDT': Decimal('332477.41883101'), 'TOTAL': Decimal('2029616.07723308')}} futures_risk_table_1=pd.DataFrame.from_dict(futures_risk_table_1) print(type(futures_risk_table_1)) futures_risk_table_1_styler = futures_risk_table_1.style.applymap(color_negative_red).set_caption("Futures Risk Monitor").format("{:20,.0f}").set_properties( subset=pd.IndexSlice[futures_risk_table_1.index[-1], :], **{'background-color': 'lightblue'} ) futures_risk_table_1_styler dfi.export(futures_risk_table_1_styler,"files/images/futures_risk_table_1_styler.png") …