Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
"Set the REMOTE_MONITORING_BASE_URL environment variable" when trying to run django server
I was given a directory with Django project, and my task is to fing out hot it works. Cause I'm just statrting to study Django I face some difficulties with it. When I try to run server this error message occurs --------------------------------------------------------------------------- KeyError Traceback (most recent call last) File c:\Users\xok4ge\AppData\Local\Programs\Python\Python39\lib\site-packages\environ\environ.py:275, in Env.get_value(self, var, cast, default, parse_default) 274 try: --> 275 value = self.ENVIRON[var] 276 except KeyError: File c:\Users\xok4ge\AppData\Local\Programs\Python\Python39\lib\os.py:679, in _Environ.__getitem__(self, key) 677 except KeyError: 678 # raise KeyError with the original key value --> 679 raise KeyError(key) from None 680 return self.decodevalue(value) KeyError: 'REMOTE_MONITORING_BASE_URL' During handling of the above exception, another exception occurred: ImproperlyConfigured Traceback (most recent call last) c:\Users\xok4ge\Documents\VS Code\kycbase\backend\manage.py in line 22 18 execute_from_command_line(sys.argv) 21 if __name__ == '__main__': ---> 22 main() c:\Users\xok4ge\Documents\VS Code\kycbase\backend\manage.py in line 18, in main() 12 except ImportError as exc: 13 raise ImportError( 14 "Couldn't import Django. Are you sure it's installed and " 15 "available on your PYTHONPATH environment variable? Did you " 16 "forget to activate a virtual environment?" 17 ) from exc ---> 18 execute_from_command_line(sys.argv) File c:\Users\xok4ge\AppData\Local\Programs\Python\Python39\lib\site-packages\django\core\management\__init__.py:442, in execute_from_command_line(argv) 440 """Run a ManagementUtility.""" 441 utility = ManagementUtility(argv) --> 442 utility.execute() File c:\Users\xok4ge\AppData\Local\Programs\Python\Python39\lib\site-packages\django\core\management\__init__.py:436, in ManagementUtility.execute(self) 434 sys.stdout.write(self.main_help_text() + "\n") 435 else: --> … -
GeneratedField() ValueError("Cannot force an update in save() with no primary key.")
In my Employee model, I defined a field called "full_name" declared as a models.GeneratedField like so: class Employee(models.Model): first_name = models.CharField(max_length=100) mid_name = models.CharField('Middle name', max_length=75) last_name = models.CharField(max_length=75) full_name = models.GeneratedField( expression=Concat( "last_name", Value(", "), "first_name", Value(" "), "mid_name" ), output_field=models.CharField(max_length=250), db_persist=True, ) created = models.DateTimeField(auto_now_add=True) updated = models.DateTimeField(auto_now=True) user = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.SET(get_sentinel_user)) However, when I tried to save a record in the admin page, I got ValueError("Cannot force an update in save() with no primary key."). To find out what causes the problem, I tried the following: Commented out the user field, and the system worked just fine. Re-instated back the user field, but changed to on_delete=models.SET_NULL, null=True, blank=True. Runserver and tried adding records in the admin page. Here, I observed that: If I left the user field blank, the system worked just fine. If I set the field with an existing user, this is where the system error occured. Anyone else encountered this problem? How did you fix this? Or is this some kind of a bug? django 5.0 -
Seeking Recommendations: Best Communities for Python and Django Developers?
Could you please recommend some great communities across different platforms that are largely beneficial for Python and Django developers? As a beginner Python developer, I wish to connect with the larger Python and Django communities to learn and stay updated with the latest trends. Any online forums, Discord servers, social media groups, or any other platform, I'm interested in discovering places where developers gather to discuss, share resources, and learn from each other. I've tried using Google to discover communities for Python and Django developers, but the results haven't been quite satisfying. Even personal recommendations mean a lot to me. Thank you in advance for sharing! -
MultipleObjectsReturned at /contact-agent/ get() returned more than one Property -- it returned 2
So I am trying to build a website using Django where users can visit a property-detail page then contact the property's agent. Users need to fill out a form which will then be sent to the agent via email. My email is working fine but since property-detail view is a class-based view and the contact_agent view is a function based view they are different views. So I can't seem to get the property's agent dynamically to get the agent's email to send him the email. My models.py: class Agent(models.Model): name = models.CharField(max_length=100) password = models.CharField(max_length=100) image = models.ImageField(upload_to = 'Images/') bio = models.TextField() instagram = models.URLField(max_length=100) twitter = models.URLField(max_length=100) facebook = models.URLField(max_length=100) linkedin = models.URLField(max_length=100) is_featured = models.BooleanField(default = False) slug = models.SlugField(default='') class Property(models.Model): price = models.IntegerField() price_per_sqft = models.IntegerField(null=True) address = models.CharField(max_length = 10000) state = models.CharField(max_length = 1000) country = models.CharField(max_length = 1000) description = models.TextField() image1 = models.ImageField(upload_to = 'Images/') image2 = models.ImageField(upload_to = 'Images/') image3 = models.ImageField(upload_to = 'Images/') agent = models.ForeignKey(Agent, on_delete=models.CASCADE) agent_description = models.TextField() is_featured = models.BooleanField(default = False) bedrooms = models.IntegerField() bathrooms = models.IntegerField() date_posted = models.DateTimeField(default=timezone.now) slug = models.SlugField(default='') My views.py: @login_required def contact_agent(request): property = get_object_or_404(Property) agent = property.agent if … -
The button in the template file does the work of the previous button
The seller should be able to choose one of the offers by entering the product page and sell the product to him, and then no one else can make an offer on the price of the product. On the product page, the winner should be notified that you have won. Now the button comes and there is no error. But the button does the work of the button before it, which is to save. That is, you click on the button and then the product will be added to the saved list. And the name of the button is place bid while it should be close product. views.py: def close_bid(request, product_id): product = get_object_or_404(Bid_info, pk=product_id) if request.method == 'POST': form = BidForm(request.POST) if form.is_valid(): if form.cleaned_data["price"] > product.price: product.bid_price = form.cleaned_data["price"] product.winner = request.user product.checkclose = True product.save() return HttpResponseRedirect(request.path_info) else: form = BidForm() return render(request, 'auctions/page_product.html', {'product': product, 'forms': form}) page_product.html: {% if product.checkclosed %} <p>Congratulations! You have won the auction for this product.</p> {% else %} <form method="post"> {% csrf_token %} {{ forms }} <input type="submit" value="Place Bid"> </form> {% if user.is_authenticated and user == product.seller %} <form method="post" action="{% url 'close_product' product.id %}"> {% csrf_token %} <button … -
Django page links issue
I have a problem with my page links, when I click on the picture in the brand details there should be a link for the brands and the related products, but when i hover over it seams that there is no link. However when I inspect the page the link appears to be there (check the attached pictures). The following is Django template for the product brands detail : https://github.com/mohsenAlsayegh/Django-Amazon-Clone/blob/main/products/templates/products/brand_detail.html The following is Django template for the products brands list : https://github.com/mohsenAlsayegh/Django-Amazon-Clone/blob/main/products/templates/products/brand_detail.html enter image description here (there is no links) enter image description here (when inspected the link is available for the brand) -
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: …