Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Problems serving staticfiles(css and javascripts) on django project using digital ocean spaces
i built a project using django 4.2 and i configured django storage and digital ocean spaces on it. the project is also hosted on digital ocean using droplets. the problem i'm having now is that i'm able to collect static and all files are uploaded to digital ocean space, the images are displaying but it doesn't serve the css and javascript. i've been on this for over 2 weeks checking many suggestions online but none of them solved my problem. Below is my current configuration for django 4.2. please kindly help if you come across this. This is my current configuration. my media folder resides in my static folder as well. AWS_ACCESS_KEY_ID = env('aws_s3_access_key') AWS_SECRET_ACCESS_KEY = env('aws_s3_secret_key') AWS_S3_REGION_NAME = env('aws_s3_region_name') AWS_STORAGE_BUCKET_NAME = env('aws_storage_bucket_name') AWS_S3_ENDPOINT_URL = "https://mogdynamics.nyc3.digitaloceanspaces.com" AWS_STATIC_LOCATION = 'static' AWS_DEFAULT_ACL = "public-read" AWS_S3_OBJECT_PARAMETERS = {'CacheControl': 'max-age=86400'} # DIGITIALOCEAN SPACES CONFIGURATION STORAGES = { "default": {"BACKEND": "storages.backends.s3boto3.S3Boto3Storage"}, "staticfiles": {"BACKEND": "storages.backends.s3boto3.S3Boto3Storage"}, "OPTIONS": { "bucket_name": AWS_STORAGE_BUCKET_NAME, "region_name": AWS_S3_REGION_NAME, "default_acl": AWS_DEFAULT_ACL }, } STATICFILES_DIRS = [os.path.join(BASE_DIR, 'static'),] STATIC_URL = f'https://{AWS_S3_ENDPOINT_URL}/{AWS_STATIC_LOCATION}/' -
render a page in Django from a model from another page which uses the same model
I am working on a project and I displayed an html page from a model that I created in models.py. Suppose this page has short information regarding every projects in the model (a title, short description and 1 out of 4 images). page_1 when I click on one of these project I want it to render a page with a complete description of that specific project, like the image below inner_page models.py class projects(models.Model): title = models.CharField(max_length = 100, null=False, primary_key=True) short_description = models.TextField(max_length=250, null=False, default='none') description = models.TextField(null=False) img1 = models.ImageField(upload_to='project/images/',blank=True) img2 = models.ImageField(upload_to='project/images/',blank=True) img3 = models.ImageField(upload_to='project/images/',blank=True) img4 = models.ImageField(upload_to='project/images/',blank=True) objects = models.Manager() views.py projs = projects.objects.all() def project_view(request, *args, **kwargs): prj = projects.objects.all() context = { 'projects': prj, } return render(request, 'projects.html', context=context) for proj in projs: def project_details(request, *args, **kwargs): context = { 'project': proj, } return render(request, 'project_detail.html', context=context) the above views.py is what I have tried in the end but it only renders one project details every time does not matter what I choose it renders the same thing. project.html <div class="row"> {% for proj in projects %} <div class="col-lg-4 col-md-6 d-flex align-items-stretch mt-4" data-aos="zoom-in" data-aos-delay="100"> <div class="icon-box" style="border-radius: 10px 50px 10px 50px;width:100%;"> {% if … -
SMTPRecipientsRefused django error | Sender address rejected
An error is occuring while I am subimtting a pasword reset form in my Django app. "Sender address rejected: not owned by user" I have configured settings.py file as follows. EMAIL_BACKEND = 'django.core.mail.backends.smtp.EmailBackend' EMAIL_HOST = 'smtp.hostinger.com' EMAIL_PORT = 587 EMAIL_HOST_USER = 'my-email@rajatgupta.me' EMAIL_HOST_PASSWORD = 'MyPassWord' EMAIL_USE_TLS = True ADMIN_EMAIL = 'my-email@rajatgupta.me' SERVER_EMAIL = 'my-email@rajatgupta.me' I am using a hostinger email acoount -
how to handle pagination of a dynamic table in django rest framework
I have a table which stores user's favorites: When user X marked an item Y as his favourites, a new record will be added to this table: id user_id item_id is_active ... X Y true When user X canceled his favorite on item Y, the is_active field will be set to false id user_id item_id is_active ... X Y false When user X re-favorite item Y, the is_active field will be set to true. Actually this is done by django create_or_update() method. So the table is like: id user_id item_id is_active 1 1001 201 true 2 1001 202 true 3 1001 203 true 4 1001 204 true 5 1001 205 true 6 1001 206 false 7 1002 201 true 8 1002 202 true 9 1003 201 true When user 1001 requests his favorites list, the queryset will be: queryset = Favorite.Objects.filter(user=1001, is_active=true) the response will be (I only list the record id): [1, 2, 3, 4, 5] if the pagination size is set to 2, user 1001 will get a response: { next: ...?page=2, previous: null, data:[1, 2] } but if user 1001 canceled his favorite on item 202 now, then, when he requests his favorites list of page 2, … -
elastic beanstalk django app CORS_ALLOWED_ORIGINS is missing scheme or netloc
i have a django app that previously was able to deploy to elastic beanstalk, but after making changes to add django-cors-headers and deploying i receive the below error in cfn-init-cmd.log: 2023-12-17 04:45:04,829 P24040 [INFO] 2023-12-17 04:45:04,829 P24040 [INFO] ERRORS: 2023-12-17 04:45:04,829 P24040 [INFO] ?: (corsheaders.E013) Origin 'clothing-calculator-env.eba-qnfpfgsz.us-west-2.elasticbeanstalk.com' in CORS_ALLOWED_ORIGINS is missing scheme or netloc 2023-12-17 04:45:04,829 P24040 [INFO] HINT: Add a scheme (e.g. https://) or netloc (e.g. example.com). 2023-12-17 04:45:04,829 P24040 [INFO] These are some snippets from my settings.py INSTALLED_APPS = [ "django.contrib.admin", "django.contrib.auth", "django.contrib.contenttypes", "django.contrib.sessions", "django.contrib.messages", "django.contrib.staticfiles", "main.apps.MainConfig", "storages", 'corsheaders' ] MIDDLEWARE = [ "django.middleware.security.SecurityMiddleware", "django.contrib.sessions.middleware.SessionMiddleware", 'corsheaders.middleware.CorsMiddleware', "django.middleware.common.CommonMiddleware", "django.middleware.csrf.CsrfViewMiddleware", "django.contrib.auth.middleware.AuthenticationMiddleware", "django.contrib.messages.middleware.MessageMiddleware", "django.middleware.clickjacking.XFrameOptionsMiddleware", ] CORS_ORIGIN_ALLOW_ALL = True CORS_ALLOWED_ORIGINS = [ 'http://localhost:8000', 'http://127.0.0.1:8000', 'http://clothing-calculator-env.eba-qnfpfgsz.us-west-2.elasticbeanstalk.com', '*', ] The wierd thing is that the first time i got this error, i didnt have the http://. After i added it, the error didnt change at all. I even went to elastic beanstalk to deploy a older version of the app before any of these changes and still get the same error, which is strange because in that version CORS_ALLOWED_ORIGINS didnt even exist in settings.py -
heroku migrate: django.db.utils.OperationalError: connection to server failed
I am a student learning on full-stack web development. I am very new to coding and would need help with following. I am trying to deploy my Django app to Heroku. Previously was using sqlite3 - then I did migration to postgre. Now I am trying to run the code heroku run python manage.py migrate but I am having error or django.db.utils.OperationError: connection to server, port 5433 failed. I went to pgadmin4, looked at properties of my Postgre server and port is 5433 - so I changed to 5433. I believed it's due to my installation of previous version of postgre which took up default 5432 port. Anyway, I have no issues when i py manage.py runserver. Everything works properly. So I did heroku create - after that, there's application error when i try to access the website. Not sure if it's supposed to be error at this point of stage. Next step should be heroku run python manage.py migrate where the error occurs. Below is my code for settings.py: """ Django settings for recipe_project project. Generated by 'django-admin startproject' using Django 4.2.7. For more information on this file, see https://docs.djangoproject.com/en/4.2/topics/settings/ For the full list of settings and their values, … -
how to stop posts from shrinking?
I made this blog but when I post on it the more the posts get when I scroll down the posts keep shrinking until they get completely out of shape specially when the screen is mobile sized how can I stop the posts from shrinking and fix this? I do not know which part of the code is associated with this problem so I post my base.html and post.html please let me know if something else is needed Thanks in advance base.html {% load static %} <!DOCTYPE html> <html> <head> <title> {% block title %}{% endblock %} </title> <link href="https://stackpath.bootstrapcdn.com/bootstrap/4.5.0/css/bootstrap.min.css" rel="stylesheet" integrity="sha384-9aIt2nRpC12Uk9gS9baDl411NQApFmC26EwAOH8WgZl5MYYxFfc+NcPb1dKGj7Sk" crossorigin="anonymous"> <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.3/jquery.min.js"></script> <script src="https://stackpath.bootstrapcdn.com/bootstrap/4.5.0/js/bootstrap.min.js" integrity="sha384-OgVRvuATP1z7JjHLkuOU7Xw704+h835Lr+6QL9UvYjZE3Ipu6Tp75j7Bh/kR0JKI" crossorigin="anonymous"></script> <link href="https://stackpath.bootstrapcdn.com/font-awesome/4.7.0/css/font-awesome.min.css" rel="stylesheet" integrity="sha384-wvfXpqpZZVQGK6TAh5PVlGOfQNHSoD2xbE+QkPxCAFlNEevoEH3Sl0sibVcOQVnN" crossorigin="anonymous"> <link rel="shortcut icon" href="{% static 'website/favicon.ico' %}" /> </head> <body> {% include 'top-menu.html'%} <div class="container"> {% if messages %} {% for message in messages %} <div class="alert alert-{{message.tags}} alert-dismissible fade show" role="alert"> <strong>{{ message }}</strong> <button type="button" class="close" data-dismiss="alert" aria-label="Close"> <span aria-hidden="true">&times;</span> </button> </div> {% endfor %} {% endif %} {% block content %} </div> {% endblock %} </body> </html> post.html <div class="container"> <div style="margin-top: 25px"></div> <div class="card-deck mb-3 text-center"> <div class="card mb-4 box-shadow"> <div class="card-header" id="linkilink"> <h4 class="my-0 font-weight-normal">{{post.title}}</h4> </div> <div class="card-body"> {{ post.body|truncatewords_html:30 }} … -
django implement a product specifications feature
I am trying to to implement a product specifications feature where a product can have multiple specifications and specifications are grouped into groups which help in retrieving the correct specification for a given product but I am struggling to figure out how to link the models. Here is a copy of my models. from django.db import models from io import BytesIO from PIL import Image # Create your models here. from django.contrib.auth.models import User from django.utils import timezone from django.core.files import File #from django.core.urlresolvers import reverse_lazy # Category model class Category(models.Model): category_name = models.CharField(max_length=255, primary_key=True) parent_category = models.ForeignKey('self', on_delete=models.CASCADE, null=True, blank=True) def __str__(self): return self.category_name # Subcategory model class Subcategory(models.Model): subcategory_name = models.CharField(max_length=255, primary_key=True) category = models.ForeignKey(Category, on_delete=models.CASCADE) def __str__(self): return self.subcategory_name class ShippingDetails(models.Model): shipping_cost = models.DecimalField(max_digits=10, decimal_places=2) delivery_region = models.CharField(max_length=255) estimated_delivery_time = models.DateField() def __str__(self): return f"Delivery to {self.delivery_region}: {self.estimated_delivery_time} days" # Specification model (revised) class Specification(models.Model): key = models.CharField(max_length=255, unique=True) description = models.TextField(blank=True) is_shared = models.BooleanField(default=False) def __str__(self): return self.key # SpecificationValue model (revised) class SpecificationValue(models.Model): specification_product = models.ForeignKey("Product", on_delete=models.CASCADE) specification = models.ForeignKey("Specification", on_delete=models.CASCADE) value = models.CharField(max_length=525, blank=True) class Meta: unique_together = (('specification_product', 'specification'),) def __str__(self): return f"{self.specification_product.product_name}: {self.specification.key} - {self.value}" # SubcategorySpecification model (new) class SubcategorySpecification(models.Model): subcategory … -
Got 403 error in accessing all files in media directory which have dynamic generated subdirectory users, and maindalali
I am using Django + react, all are deployed on the same EC2 server, IAM USING Daphne as ASGI server and nginx as reverse proxy... The problem is only on access and not on serving media like Images, problem show in browser even with commands that access to ... .jpg or .txt is denied with error 403 I tried to access user profile for example..no problem but image within user profile not load and console.log that 403 permission error, i expected image to be visible like in local development .... my nginx for media is nginx conf for media -
django upload csv file, add content the into database
I created a form to upload a csv file and want to put the data into my models Here's my models.py. It is a simple questionnaire with basic info about a person. There is a second model to record the upload time of the file: class Upload(CreatedUpdatedModel): uploaded_at = models.DateTimeField(auto_now_add=True, unique=True) class Submission(CreatedUpdatedModel): upload = models.ForeignKey(Upload, on_delete=models.CASCADE) managed_people_answers = models.ManyToManyField('ManagedPeople') political_affiliation_answers = models.ManyToManyField('PoliticalAffiliation') religion_answers = models.ManyToManyField('Religion') veteran_status_answers = models.ManyToManyField('VeteranStatus') submission_time = models.DateTimeField() first_name = models.CharField(max_length=50, blank=True) last_name = models.CharField(max_length=50, blank=True) state = models.CharField(max_length=50, blank=True) email = models.EmailField(max_length=50, blank=True) street_address = models.CharField(max_length=50, blank=True) city = models.CharField(max_length=50, blank=True) zip_code = models.CharField(max_length=50, blank=True) telephone_number = models.CharField(max_length=50, blank=True) birthday = models.DateField(blank=True, null=True) income = models.CharField(max_length=50, choices=Income.choices) occupation_type = models.CharField(max_length=50, choices=OccupationType.choices, blank=True) highest_level_of_education = models.CharField(max_length=50, choices=Education.choices, blank=True) do_you_own_a_business = models.CharField(max_length=50, blank=True, default=False, choices=OwnBusiness.choices) gender = models.CharField(max_length=50, blank=True) Here is my forms.py Its just a simple form to upload multiple files if needed taken from the django docs: class MultipleFileInput(forms.ClearableFileInput): allow_multiple_selected = True class MultipleFileField(forms.FileField): def __init__(self, *args, **kwargs): kwargs.setdefault("widget", MultipleFileInput()) super().__init__(*args, **kwargs) def clean(self, data, initial=None): single_file_clean = super().clean if isinstance(data, (list, tuple)): result = [single_file_clean(d, initial) for d in data] else: result = single_file_clean(data, initial) return result class UploadForm(forms.Form): file = MultipleFileField() Here is … -
django-cors-headers not working when proxy set in react side
I have a very big and completely unusual problem in django cors headers. I searched a lot but did not get any results. I have a full stack Django and React project. I determined the back end of the allowed origins. When a React project without a proxy (the proxy feature in the package.json file) makes a request to the backend, if that domain is not allowed, SOP stops it, but when it is used with a proxy, it makes a request to the backend even if that domain is not allowed. It can read and display data. It means that another React project on another domain can request and read data with a proxy. It seems to bypass the SOP. On the backend side, I use the django-cors-headers==3.8.0 package and I read all its documentation, I made all the settings correctly, but I don't know why this bug appeared, please help me. -
Cant figure out where I made a mistake in the code, would appreciate help (Django unittest referencing class in test method)
I have the tests and I have a separate file with a class that keeps all the methods and what not that are used in the tests. This is done to follow DRY principle (and also because my reviewer told me to and I am to comply, lol). However, in the recent feedback I got from the reviewer I got an assignment I cannot seem to make and that is moving part of the code in that class with common inputs from a separate method into setUpTestData(cls) method (where most of the data are). I used to have 2 more methods in the code below: one was something like def one_note(cls): and another one was like def note_list(cls) and under those names the code that is now located under if cls.a==1 and if cls.a==2 was stored. The reason I cannot simply declare all the functions in the code is I need a tool to make it possible to only choose one option as they are mutually exclusive in my tests. I was thinking to add if condition with a value here in the class with the stored information and then use the value I need in test methods. But for … -
when i signup new user i am facing this error: AttributeError: Manager isn't available; 'auth.User' has been swapped for 'main.CustomUser'
I am trying to sign up new users and add them to an existing group but I am facing this error. AttributeError: Manager isn't available; 'auth.User' has been swapped for 'main.CustomUser' first, I thought this error was caused by adding a user to a default group but it seems like from the moment I changed my user model by adding a point field and made migrations the signup is not working as expected this is my models.py file class CustomUser(AbstractUser): point = models.IntegerField(default=0) class App(models.Model): appname = models.CharField(max_length=255) link = models.CharField(max_length=100) category= models.CharField(max_length=100) subcategory = models.CharField(max_length=100) points = models.IntegerField() created_at = models.DateTimeField(auto_now_add=True, null=True) appicon = models.ImageField(upload_to='icon/') def __str__(self): return self.appname this is my signup view def sign_up(request): if request.method == "POST": form = RegisterForm(request.POST) if form.is_valid(): user = form.save() user_group, created = Group.objects.get_or_create(name='user') user.groups.add(user_group) login(request, user) return redirect('/app') else: form = RegisterForm() return render(request,'registration/signup.html', {'form':form}) i have also added this to my settings.py file AUTH_USER_MODEL = 'main.CustomUser this is my full traceback Internal Server Error: /app/signup/ Traceback (most recent call last): File "D:\01 tasks\pro 2 and try outs\django main\venv\Lib\site-packages\django\core\handlers\exception.py", line 55, in inner response = get_response(request) ^^^^^^^^^^^^^^^^^^^^^ File "D:\01 tasks\pro 2 and try outs\django main\venv\Lib\site-packages\django\core\handlers\base.py", line 197, in _get_response response … -
AJAX is not working when add multiple items
I have a cart, where I can add or remove items. I'm using sessions for cart and AJAX to add/remove products without refreshing the page. It works correctly, when one item in cart, but it shows only a request status on new page and I need to refresh it if I want to see changes. It is working fine, when only one product is in cart, otherwise I need to refresh the page. cart.html <div class="quantity__row"> <form action="{% url 'remove_cart' %}" method="post" id="removeCartID"> {% csrf_token %} {{ item.update_quantity_form.quantity }} {{ item.update_quantity_form.update }} <input type="hidden" name="product_id" value="{{ item.product.id }}" id="productRemoveID"> <input type="submit" value="-" class="quantity__number-minus"> </form> <input type="number" min="1" value={{ item.quantity }} readonly="readonly" class="quantity__input" id="quantityID"/> <form action="{% url 'add_cart' %}" method="post" id="addCartID"> {% csrf_token %} {{ item.update_quantity_form.quantity }} {{ item.update_quantity_form.update }} <input type="hidden" name="product_id" value="{{ item.product.id }}" id="productAddCartID"> <input type="submit" value="+" class="quantity__number-plus"> </form> </div> views.py def add_to_cart(request): if request.method == 'POST': product_id = request.POST.get('product_id') product = Product.objects.get(id=int(product_id)-1) cart = Cart(request) cart.add(product=product) cart_quantity = cart.get_total_len() return JsonResponse({'success': True, 'cart_quantity': cart_quantity}) def cart_remove(request): if request.method == 'POST': product_id = request.POST.get('product_id') product = Product.objects.get(id=int(product_id)) cart = Cart(request) cart.remove(product) cart_quantity = cart.get_total_len() return JsonResponse({'success': True, 'cart_quantity': cart_quantity}) scripts.js $(function() { $('#addCartID').on('submit', function(e){ e.preventDefault(); $.ajax({ url: '{% … -
django why cookie not sending to client browser?
I properly setup cros. Trying to send cookie to client browser but don't know where I am doing mistake and cookie not going to client browser: setting.py CORS_ALLOWED_ORIGINS = [ "http://*", "https://*",] CORS_ORIGIN_WHITELIST = [ "http://*", "https://*",] CSRF_TRUSTED_ORIGINS = [ "http://*", "https://*", CORS_ALLOW_ALL_ORIGINS = True CORS_ALLOW_CREDENTIALS = True SESSION_COOKIE_SECURE = True my api code: from django.http import HttpResponse,JsonResponse @api_view(["POST","GET"]) def UserProfileAPI(request): if request.method == "POST": #...others code performing validation if success then allow user login login(request, user) #refresh = RefreshToken.for_user(user) #access_token = str(refresh.access_token) #refresh_token = str(refresh) serializers = AuthorProfileSerialzers(data=request.data) try: existing_profile= AuthorProfile.objects.get(author = request.user) except: existing_profile = None if not existing_profile: if serializers.is_valid(): instance = serializers.save() instance.author = request.user instance.author_pic = request.data.get("profile_image") instance.save() response = HttpResponse('Cookie set successfully') # Set a cookie named 'my_cookie' with a value 'cookie_value' response.set_cookie('my_cookie', 'cookie_value', max_age=3600, path='/',samesite=None,secure=False) return response # return Response({"detail":"sucess","jwt_token":access_token,"refresh_token":refresh_token}, status=status.HTTP_200_OK) I am receiving the 200 response from backend but don't know why cookie isn't sending to browser -
Django file creation error. Why do I get an attribute error: the 'bytes' object does not have the '_committed' attribute?
Actually, the error occurs when an entry in the database is trying to be created. It is not clear why the saved object is not perceived by the server as a File type, but if you print the type of this object, then it is a File, but the error says something else. The error occurs only on the server, everything works if I run it on my machine. The server is hosted on pythonanywhere.com. Internal Server Error: /taskTest/1 Traceback (most recent call last): File "/usr/local/lib/python3.10/site-packages/django/core/handlers/exception.py", line 55, in inner response = get_response(request) File "/usr/local/lib/python3.10/site-packages/django/core/handlers/base.py", line 197, in _get_response response = wrapped_callback(request, *callback_args, **callback_kwargs) File "/usr/local/lib/python3.10/site-packages/django/views/generic/base.py", line 84, in view return self.dispatch(request, *args, **kwargs) File "/usr/local/lib/python3.10/site-packages/django/views/generic/base.py", line 119, in dispatch return handler(request, *args, **kwargs) File "/home/Bioni/Platon/main/views/student/task/taskUpload.py", line 35, in post self.createFiles(form, user.pk, task_id) File "/home/Bioni/Platon/main/views/student/task/taskUpload.py", line 46, in createFiles StudentFile.objects.create(creator=user_id, task_id=task_id, file=File(file)) File "/usr/local/lib/python3.10/site-packages/django/db/models/manager.py", line 85, in manager_method return getattr(self.get_queryset(), name)(*args, **kwargs) File "/usr/local/lib/python3.10/site-packages/django/db/models/query.py", line 514, in create obj.save(force_insert=True, using=self.db) File "/usr/local/lib/python3.10/site-packages/django/db/models/base.py", line 806, in save self.save_base( File "/usr/local/lib/python3.10/site-packages/django/db/models/base.py", line 857, in save_base updated = self._save_table( File "/usr/local/lib/python3.10/site-packages/django/db/models/base.py", line 1000, in _save_table results = self._do_insert( File "/usr/local/lib/python3.10/site-packages/django/db/models/base.py", line 1041, in _do_insert return manager._insert( File "/usr/local/lib/python3.10/site-packages/django/db/models/manager.py", line 85, in manager_method return … -
list index out of range in Comparing two prices
I want to compare the received price with the previous prices and send a message if it was lower, but it shows this error to receive the first entry. I also tried to try and while. It didn't give the expected result. If I remove this condition and enter a number and apply this condition again. The code works correctly. IndexError at /bid/2/ list index out of range File "C:\Users\N\Desktop\my own\views.py", line 98, in bid elif bid_price <= other_off[0].bid_price : elif bid_price <= other_off[0].bid_price : messages.warning(request, "Your offer must be greater than other offers.") -
how to transfer file from server to client via json
I am trying to transfer the processed pdf file on the server to the client side so that the user can download it. Here is my code on the server - @app.task def pdf_protect(file_path, file_id, password): with open(file_path, 'rb') as file: reader = PdfReader(BytesIO(file.read())) writer = PdfWriter() writer.append_pages_from_reader(reader) writer.encrypt(password) output = io.BytesIO() writer.write(output) output.seek(0) send_notification.delay({'filename': 'result.pdf', 'content': base64.b64encode(output.read()).decode('utf-8')}, file_id) In this code I use the pypdf library and encrypt the pdf with the given password. After that, I try to convert the processed pdf file into bytes and pack it into json in order to send it to the client side via a websocket connection. On the client side I have the following code - chatSocket.onmessage = function (e) { const data = JSON.parse(e.data); var blob = new Blob([data.message.content], {type: "application/pdf"}); console.log(data.message.content) downloadLink.href = URL.createObjectURL(blob); downloadLink.download = data.message.filename; chatSocket.close(); }; In this code I get the data from the json and make a link to download the file. But after downloading and opening the pdf file, the error "Failed to load the PDF document." or just a blank page. But what happens when I send a response to the client via FileResponse and then use the same method to make … -
Django uploading PDF and mailing it
So I want to code a website using Django where anyone can apply to become agents for the company. To apply they fill out a form where they upload their resume/CV which is then mailed to the HR. Now my code doesn't seem to take the pdf since it returns none after hitting submit. Also the mail isn't being sent. How can I fix this? Thanks in advance! My html: <form method="POST" action="{% url 'apply' %}" class="row" enctype="multipart/form-data"> {% csrf_token %} <div class="mb-3 col-lg-6"> <input type="text" class="form-control" placeholder="Name" name ="name"> </div> <div class="mb-3 col-lg-6"> <input type="text" class="form-control" placeholder="Email Address" name ="email"> </div> <div class="mb-3 col-lg-6"> <input type="text" class="form-control" placeholder="Subject" name ="subject"> </div> <div class="mb-3 col-lg-6"> <input type="text" class="form-control" placeholder="Phone" name ="phone"> </div> <div class="mb-3 col-lg-6"> <input id="CV" type="file" class="form-control" placeholder="CV" name ="CV" aria-label="CV"> </div> <div class="mb-3 col-lg-6"> <input type="text" class="form-control" placeholder="Address" name ="address"> </div> <div class="mb-3 col-lg-12"> <textarea name id cols="30" rows="5" class="form-control" name ="cover_letter" placeholder="Cover Letter..."></textarea> </div> <div class="mb-3 col-lg-12"> <input type="submit" class="btn btn-primary" value="Apply"> </div> </form> My views.py: def apply(request): if request.method == "POST": name = request.POST['name'] email = request.POST['email'] subject = request.POST['subject'] phone = request.POST['phone'] CV = request.POST.get('CV') address = request.POST['address'] cover_letter = request.POST.get('cover_letter') application = "Name: … -
AttributeError: Manager isn't available; 'auth.User' has been swapped for 'main.CustomUser'
I am trying to add new users who signup to a group called user but i am facing this error. AttributeError: Manager isn't available; 'auth.User' has been swapped for 'main.CustomUser' this is my models.py file class CustomUser(AbstractUser): point = models.IntegerField(default=0) class App(models.Model): appname = models.CharField(max_length=255) link = models.CharField(max_length=100) category= models.CharField(max_length=100) subcategory = models.CharField(max_length=100) points = models.IntegerField() created_at = models.DateTimeField(auto_now_add=True, null=True) appicon = models.ImageField(upload_to='icon/') def __str__(self): return self.appname this is my signup view def sign_up(request): if request.method == "POST": form = RegisterForm(request.POST) if form.is_valid(): user = form.save() user_group, created = Group.objects.get_or_create(name='user') user.groups.add(user_group) login(request, user) return redirect('/app') else: form = RegisterForm() return render(request,'registration/signup.html', {'form':form}) i have also added this to my settings.py file AUTH_USER_MODEL = 'main.CustomUser all iam trying todo is add new users to a group please help. i tried this code in apps.py file but didnt help. class MainConfig(AppConfig): default_auto_field = 'django.db.models.BigAutoField' name = 'main' def ready(self): from django.contrib.auth.models import Group from django.db.models.signals import post_save def add_to_default_group(sender, **kwargs): user = kwargs["instance"] if kwargs['created']: group, ok = Group.objects.get_or_create(name="default") group.user_set.add(user) post_save.connect(add_to_default_group, sender=settings.AUTH_USER_MODEL) -
Firebase Auth Issue through React JS and Django Templates
I'm using React JS to create the login page. For the I used Firebase 10.7.1 npm module to create the authentication. Here is my quick code for Auth: const provider = new GoogleAuthProvider(); signInWithPopup(auth, provider) .then((result) => { // Get the ID token directly from the result object const idToken = result._tokenResponse.idToken; // Updated this line // Send the token to your backend sendTokenToBackend(idToken); // Updated this line }) .catch((error) => { console.error("Error during Google Sign In: ", error); }); Authentication works fine in react JS and when i run the build and paste the files to render them through the django templates. I can see the react code rendered perfectly. However, now when I try to sign in, halfway of the execution I get the below error doesn't matter if I allow all domains for CORS in Django: It had the same behaviour when I was creating the same code in the native Java script for signInWithPopUp. I've tried multiple browsers: Chrome, Firefox, Edge -
Building an Error-Prone OpenAI API Wrapper with Rate Limiting for Asynchronous Tasks in Python
StackOverflow community! I'm working on a Django project where I need to build a robust and efficient wrapper around the OpenAI API for asynchronous tasks. My main goals are: API Wrapper Design: To create classes that effectively wrap the OpenAI API, enabling model selection and prompt generation. Rate Limiting: Implementations to handle rate limits, specifically for both tokens per minute and requests per minute. Asynchronous Task Management: Utilize asynchronous tasks, possibly with Celery, to manage API calls without exceeding the rate limits. Here's what I've conceptualized so far: Wrapper Class: A class that handles the connection to the OpenAI API, including methods for selecting models and sending prompts. Prompt Generation: Classes or methods dedicated to constructing and managing prompt structures. Rate Limiting: Implementing a system to track and control the rate of API requests, possibly integrating with the Celery task queue. (Using Redis as Token Bucket? I have the feeling my implementation sometimes does not work correctly if somehow several worker block and write the same tokenbucket at the same time). (Celery Worker Concurrency is 1, but still I am getting on a different API "Too Many Requests" even if my TokenBucket has the right amount of it). My questions … -
Django throws an invalid input syntax error when I use foreign key
I have been setting up admin page to upload images based on different categories. I referenced categories as foreign key in the gallery model but as I submit or save the admin upload form it throws the error " invalid input syntax for type integer". screenshot before saving error screenshot models.py class Category(models.Model): name = models.CharField(max_length=100, null=False, primary_key=True) objects = models.Manager() class Gallery(models.Model): id = models.AutoField(primary_key=True) category = models.ForeignKey('Category', on_delete=models.SET_NULL, null=True) title = models.CharField(max_length=100, null=False) image = models.ImageField(upload_to='images/') by the way I'm using postgreSQL. -
auto add variable in template
I added mydata in setup function of the BaseView. class BaseView(View): def setup(self, request, *args, **kwargs): super().setup(request, *args, **kwargs) self.mydata = table.objects.all() When I print it in the get function of child class, the value is correct but I'd like this variable be added in template file automatically. def get(self, request, pk=''): print('self.active_apps in plan') print(self.active_apps) user_info = request.session.get('user_info') context = {'user_info':user_info} if pk != '': item = get_object_or_404(self.model_class, pk=pk) form = self.form_class(instance=item) context['form'] = form context['pk'] = pk else: form = self.form_class() context['form'] = form return render(request, self.template_name, context) -
Accordion through loop in Django templates
Working with Django templates. I tried to make an accordion with checkboxes inside. Now it is displayed, but since it was made through a cycle, when you click on one of the sections of the accordion, all the others open, and when you click on the checkboxes, the very first one is checked. <div class="accordion" id="accordionPanelsStayOpenExample"> {% for category, vaccines in category_vaccines.items %} <div class="accordion-item"> <h2 class="accordion-header" id="panelsStayOpen-heading{{ loop.index }}"> <button class="accordion-button" type="button" data-bs-toggle="collapse{{ loop.index }}" data-bs-target="#panelsStayOpen-collapse{{ loop.index }}" aria-expanded="true" aria-controls="panelsStayOpen-collapse{{ loop.index }}"> {{ category }} </button> </h2> {% for vaccine in vaccines %} <div id="panelsStayOpen-collapse{{ loop.index }}" class="accordion-collapse collapse" aria-labelledby="panelsStayOpen-heading{{ loop.index }}"> <div class="accordion-body"> <div> <input id="html{{ loop.index }}" type="checkbox"> <label for="html{{ loop.index }}">{{ vaccine.name }}</label> </div> </div> </div> {% endfor %} </div> {% endfor %} </div> I tried to make the elements have unique ids using loop.index, it still works the same. Tell me, what am I doing wrong?