Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Video Title space giving Directory not found error
I am working on a downloader but while downloading a video (eg. Staying Alive) The space between Staying and Alive is giving directory error I tried to fix using methods given by chatgpt but it doesnt work for my case def download_video(video_url, download_path, resolution='720p'): video = YouTube(video_url) stream = video.streams.filter(res=resolution, file_extension='mp4').first() if stream: print(f"Downloading: {video.title}") file_path = os.path.join(download_path, f"{slugify(video.title)}.mp4") stream.download(download_path) return file_path else: print(f"Error downloading: {video.title}") return None def create_zip(zip_filename, files_to_zip): with zipfile.ZipFile(zip_filename, 'w') as zip_file: for file_path in files_to_zip: #each file to the zip file print(file_path) file_name = os.path.basename(file_path) zip_file.write(file_path, file_name) def download_files(request, downloaded_files): base_dir = os.path.dirname(os.path.dirname(os.path.abspath(__file__))) filename = '/test.zip' filepath = base_dir + '/media' + filename create_zip(filepath, downloaded_files) thefile = filepath filepath = os.path.basename(thefile) chunk_size = 8192 response = StreamingHttpResponse(FileWrapper(open(thefile, 'rb'), chunk_size), content_type=mimetypes.guess_type(thefile)[0]) response['Content-Length'] = os.path.getsize(thefile) response['Content-Disposition'] = "Attachment;filename=%s" % filename return response How exactly I have to do the fix? -
annotate() + distinct(fields) is not implemented. Python Django Error
When I try to use annotate with distict following error occurs NotImplementedError at /guest/book/1/checkavailability/ annotate() + distinct(fields) is not implemented. Request Method: GET Request URL: http://localhost:8000/guest/book/1/checkavailability/?start_date=2023-11-19&end_date=2023-11-28 Django Version: 4.2.7 Exception Type: NotImplementedError Exception Value: annotate() + distinct(fields) is not implemented. Exception Location: /home/abk/Desktop/project-qb/django/lib/python3.11/site-packages/django/db/models/sql/compiler.py, line 872, in as_sql Raised during: booking.views.views.RoomsAvailableBetweenSpecificDatesView Python Executable: /home/abk/Desktop/project-qb/django/bin/python Python Version: 3.11.4 Here is my query booked_rooms = RoomBooking.objects.filter( (Q(booking__start_date__range=(lookup_start_date, lookup_end_date)) | Q(booking__end_date__range=(lookup_start_date, lookup_end_date)) | Q(booking__start_date__lt=lookup_start_date, booking__end_date__gt=lookup_end_date)), booking__hotel=self.hotel, booking__guest_status__in=[ settings.NOT_CHECKED, settings.CHECKED_IN], ).select_related('booking', 'room').exclude(room__is_deleted=True).distinct('room__room_number').values(room_type=F('room__room_type')).annotate(count=Count('room__room_type')).order_by('room__room_type') Here is my model class RoomBooking(models.Model): booking = models.ForeignKey("Booking", on_delete=models.CASCADE) room = models.ForeignKey("Room", on_delete=models.CASCADE) class Room(models.Model): room_number = models.CharField(max_length=25) hotel = models.ForeignKey("Hotel", on_delete=models.CASCADE) room_type = models.CharField(max_length=25) rate = models.IntegerField(validators=[MinValueValidator(0)]) is_deleted = models.BooleanField(default=False) class Booking(models.Model): NOT_CHECKED = 'not checked' CHECKED_IN = 'checked in' CHECKED_OUT = 'checkout out' CANCELLED = 'cancelled' GUEST_STATUS = [ (NOT_CHECKED, "NOT_CHECKED"), (CHECKED_IN, "CHECKED_IN"), (CHECKED_OUT, 'CHECKED_OUT'), (CANCELLED, "CANCELLED") ] hotel = models.ForeignKey('Hotel', on_delete=models.CASCADE) guest = models.ForeignKey( "authentication.User", on_delete=models.CASCADE, null=True) total_rooms = models.IntegerField( default=1, validators=[MinValueValidator(1)]) start_date = models.DateTimeField() end_date = models.DateTimeField() booked_date = models.DateTimeField(auto_now_add=True) guest_status = models.CharField( max_length=15, choices=GUEST_STATUS, default=NOT_CHECKED) How could I make the same query without the issue ? After some googling I've found that if we try to call distinct on an annotated query, it sometimes works, sometimes get's … -
Async/Await Fetch POST parameters for text/html
How do I POST parameters for content type text/html without sending it as an object? Posting using body : {} or body: JSON.Stringify({}) posts data an object. I want data to be posted as individual values. $(document).on('click', '#update', async () => { try { const response = await fetch("/getupdate",{ method:'POST', headers:{ 'Content-Type':'text/html; charset=utf-8' }, body: JSON.stringify({ "country": getCookie("country"), "city": getCookie("city").replace(/"/g, ""), "action": 1, "csrfmiddlewaretoken": $('input[name=csrfmiddlewaretoken]').val() }), }); } catch (error){ console.log(error) } }); Got an object instead of individual values - { "country": "US", "city": "Miami", "action": 1, "csrfmiddlewaretoken": "iLoS4Bsgdyc6EhOtQKiiXrIqr9S1eojdhdyEeClA8qI5ei2WpfQQu1JrduLrbndndR" } Expecting individual values - "country": "US", "city": "Miami", "action": 1, "csrfmiddlewaretoken": "iLoS4Bsgdyc6EhOtQKiiXrIqr9S1eojdhdyEeClA8qI5ei2WpfQQu1JrduLrbndndR" -
Django and Docker image (Postgres): could not translate host name "db" to address
I am trying to run a django project using a database created on a docker image but I fail with grace all over again. Let me show you my error when I use > python manage.py migrate: System check identified some issues: WARNINGS: ?: (staticfiles.W004) The directory 'D:\2xProjects\Python\ExploreHub\explore_hub\static' in the STATICFILES_DIRS setting does not exist. Traceback (most recent call last): File "D:\2xProjects\Python\ExploreHub\.dj-env\Lib\site-packages\django\db\backends\base\base.py", line 289, in ensure_connection self.connect() File "D:\2xProjects\Python\ExploreHub\.dj-env\Lib\site-packages\django\utils\asyncio.py", line 26, in inner return func(*args, **kwargs) ^^^^^^^^^^^^^^^^^^^^^ File "D:\2xProjects\Python\ExploreHub\.dj-env\Lib\site-packages\django\db\backends\base\base.py", line 270, in connect self.connection = self.get_new_connection(conn_params) ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ File "D:\2xProjects\Python\ExploreHub\.dj-env\Lib\site-packages\django\utils\asyncio.py", line 26, in inner return func(*args, **kwargs) ^^^^^^^^^^^^^^^^^^^^^ File "D:\2xProjects\Python\ExploreHub\.dj-env\Lib\site-packages\django\db\backends\postgresql\base.py", line 275, in get_new_connection connection = self.Database.connect(**conn_params) ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ File "D:\2xProjects\Python\ExploreHub\.dj-env\Lib\site-packages\psycopg2\__init__.py", line 122, in connect conn = _connect(dsn, connection_factory=connection_factory, **kwasync) ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ psycopg2.OperationalError: could not translate host name "db" to address: No such host is known. The above exception was the direct cause of the following exception: Traceback (most recent call last): File "D:\2xProjects\Python\ExploreHub\explore_hub\manage.py", line 22, in <module> main() File "D:\2xProjects\Python\ExploreHub\explore_hub\manage.py", line 18, in main execute_from_command_line(sys.argv) File "D:\2xProjects\Python\ExploreHub\.dj-env\Lib\site-packages\django\core\management\__init__.py", line 442, in execute_from_command_line utility.execute() File "D:\2xProjects\Python\ExploreHub\.dj-env\Lib\site-packages\django\core\management\__init__.py", line 436, in execute self.fetch_command(subcommand).run_from_argv(self.argv) File "D:\2xProjects\Python\ExploreHub\.dj-env\Lib\site-packages\django\core\management\base.py", line 412, in run_from_argv self.execute(*args, **cmd_options) File "D:\2xProjects\Python\ExploreHub\.dj-env\Lib\site-packages\django\core\management\base.py", line 458, in execute output = self.handle(*args, **options) ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ File "D:\2xProjects\Python\ExploreHub\.dj-env\Lib\site-packages\django\core\management\base.py", line 106, … -
Django, Nginx, Gunicorn: 400 Bad Request when accessing AWS EC2 instance externally
I am encountering a "400 Bad Request" error when attempting to access my Django application externally on an AWS EC2 instance. Notably, the application functions correctly when accessed locally on the server. This issue arises when using Nginx as a reverse proxy and Gunicorn as the application server. For example when I'm on the ec2 instance and uses the command "curl --unix-socket /run/gunicorn.sock localhost/events/" I get the right data from the database. In the chrome console I can see this error: "The Cross-Origin-Openor-Policy header has been ignored, because the URL's origin was untrustworthy. It was defined either in the final response or a redirect. Please deliver the response using the HTTPS protocol. You can alos use the localhost origin instead." I have looked at the nginx logs and I don't get any information from that. I have tried many different solutions and looked and followed various tutorials and documentations, but it still won't work. I will add here some of the files that might be needed in figuring out this problem, and ask if you need more information, or can give me any direction of what I could try. tutorials I have looked at: https://www.youtube.com/watch?v=7O1H9kr1CsA https://medium.com/@madhankm/set-up-django-with-nginx-and-gunicorn-on-ubuntu-20-04-lts-8a02748435fe, settings.py (The important parts) … -
Django Project on Linode Server not pointing to the right PostgreSQL database
I am new to django and just uploaded a project to Linode through Nginx server. I am facing a very weird problem. When I first uploaded the project, the PostgreSQL database was "pinkgiraffedb". However, after encountering some problem on migration, I decided to create a new database called "mydb" and pull data from there. Unfortunately, the project is still pointing towards the old database. I have tried to solve the problem, but none worked so far. What I am doing wrong? I have restarted nginx server several times but it didn't work. Changed Debug from TRUE to False in settings.py but it didn't work. Any suggestion would be on how to solve it would be appreciated. Thank you in advance. Previously, I deleted the whole "pinkgiraffedb" database but then I started to see operational/programming error on Django admin. So created the DB again and ran migration. Restarted server several times. 'mydb' table migrations list of databases settings.py DATABASES = { 'default': { 'ENGINE': 'django.db.backends.postgresql_psycopg2', 'NAME': 'mydb', 'USER': 'postgres', 'PASSWORD': '', 'HOST': 'localhost', 'PORT': '5432', } }``` -
How to return actual data from a serializer Django
I'm trying to test a register_customer api endpoint I'm working on on Django, but I'm getting the the user_id as a response instead of the actual user's data. ` { "data": { "user_id": 15 }, "message": "Thank you for registering" }` I have a Customer model that has a OneToOne relationship with the CustomUser ` class Customer(models.Model): user_id = models.OneToOneField(CustomUser, on_delete=models.CASCADE)` And here's my serializer: ` from rest_framework import serializers from .models import Customer, CustomUser import logging logger = logging.getLogger(name) class UserSerializer(serializers.ModelSerializer): password = serializers.CharField(write_only=True, required=True) confirm_password = serializers.CharField(write_only=True, required=True) class Meta: model = CustomUser fields = [ "email", "first_name", "last_name", "phone_number", "password", "confirm_password", ] def validate_password(self, value): # Password must be at least 8 characters long if len(value) < 8: raise serializers.ValidationError( "Password must be at least 8 characters long." ) # Check for at least one uppercase character if not any(char.isupper() for char in value): raise serializers.ValidationError( "Password must contain at least one uppercase character." ) # Check for at least one special character special_characters = "!@#$%^&*()-_=+[]{}|;:'\",.<>/?" if not any(char in special_characters for char in value): raise serializers.ValidationError( "Password must contain at least one special character." ) # Check for at least one number if not any(char.isdigit() for … -
django autocomplete for filtered queryset
I am trying to customize django-admin when working with django rest framework. I am adding Article object, which may have Participants (users who contributed to writing the article), and I want to create autocomplete when choosing users, but display only Users who are active and team_members. For now, all Users get displayed despite filtering. Here is my code: class ParticipantInlineForm(forms.ModelForm): class Meta: model = Participant fields = '__all__' def __init__(self, *args, **kwargs): super().__init__(*args, **kwargs) user_field = self.fields['user'] if hasattr(user_field, 'queryset'): user_field.queryset = user_field.queryset.filter(is_active=True, is_team_member=True) class ParticipantInline(admin.TabularInline): model = Participant form = ParticipantInlineForm autocomplete_fields = ['role', 'user'] # here! Here are my User and Participant models: class User(AbstractUser): """ Расширение стандартной модели пользователя Django """ patronymic = models.CharField(max_length=100, null=True, blank=True, verbose_name="Отчество") date_joined = models.DateField(null=False, default=timezone.now, verbose_name="Дата регистрации") profile_info = models.CharField(max_length=500, null=True, blank=True, verbose_name="Биография") profile_picture = models.ImageField(upload_to='images/users/', null=True, default='images/alt_image.jpg', verbose_name="Аватар") is_team_member = models.BooleanField(default=False, verbose_name="Член команды") full_name = models.CharField(max_length=255, blank=True, verbose_name="Полное имя") # sort of caching for quick search article_participated = models.ManyToManyField('Article', through='Participant', related_name='parts', verbose_name="Участники в создании") favourites = models.ManyToManyField('ContentObject', through='Favourite', related_name='favs', verbose_name="Избранное") class Participant(models.Model): """ Какую конкретно роль пользователь сыграл при создании """ user = models.ForeignKey(User, on_delete=models.CASCADE, verbose_name="Пользователь") article = models.ForeignKey(Article, on_delete=models.CASCADE, verbose_name="Статья") role = models.ForeignKey(Role, null=True, blank=True, on_delete=models.SET_NULL, verbose_name="Фактическая роль") With … -
Docker Django Gunicorn Nginx "This site can’t be reached" error
I have django project. I want to do deployment on AWS. I have docker-compose-prod.yml file: version: "3.8" services: api: image: meduzzen-backend-api container_name: django entrypoint: ./start_prod.sh tty: true stdin_open: true volumes: - .:/code - ./code:/apps - static:/static expose: - "8000" ports: - "8000:8000" depends_on: - postgres-db - redis env_file: - .env networks: - api-db-redis celery: image: meduzzen-backend-api container_name: celery command: celery -A meduzzen_backend worker -l INFO volumes: - .:/code - ./code:/apps depends_on: - postgres-db - redis env_file: - .env networks: - api-db-redis celery-beat: image: meduzzen-backend-api container_name: celery-beat command: celery -A meduzzen_backend beat -l INFO --scheduler django_celery_beat.schedulers:DatabaseScheduler volumes: - .:/code - ./code:/apps depends_on: - postgres-db - redis env_file: - .env networks: - api-db-redis flower: image: mher/flower:latest container_name: flower command: celery --broker=redis://redis_cache:6379/0 flower ports: - "5555:5555" depends_on: - celery - celery-beat - redis networks: - api-db-redis postgres-db: image: postgres:latest container_name: postgres_db ports: - "5432:5432" volumes: - data:/var/lib/postgresql/data env_file: - .env networks: api-db-redis: # Have access the database using pgadmin4 ipv4_address: 172.24.0.6 pg-admin: image: dpage/pgadmin4:latest container_name: pg_admin env_file: - .env ports: - "5050:5050" networks: - api-db-redis redis: image: redis:latest container_name: redis_cache ports: - "6379:6379" networks: - api-db-redis nginx: image: meduzzen-backend-nginx container_name: nginx volumes: - static:/static - ./nginx-conf.d:/etc/nginx/conf.d ports: - "80:80" depends_on: - api volumes: … -
Pressure Notifications Not Displaying in bidvertiser
I am having an issue with the pressure notifications on my website. I have added the sw.js file to the root directory of my site, and I have selected a location for the notifications to display. However, when I open the site, only the text "by BidVertiser" is displayed in place of the ad. I have checked the following: The site is fully loaded. There is not a lot of activity on the site. There are not a lot of visitors to the site. I have also tried the following: Using a different location for the notifications. Using different sizes and types of images for the notifications. I am still having the same issue. -
Django post save on user registration question
I have a custom user model and I am using all-auth to register users. I am attempting to use a post save signal to auto assign new users to a specific group based on their email domain. For example, I user with the email joe@domainone.com might be assigned to group 2 based on the @domainone.com email. I also have a model that stores email domains and associated groups. So far it doesn't look like the signal is being called when I register a new user via and all-auth form at http://localhost:8000/accounts/signup/. Any ideas to fix this? Models: from django.contrib.auth.models import AbstractUser from django.db import models from allauth.account.models import EmailAddress from django.contrib.auth.models import Group class CustomUser(AbstractUser): age = models.PositiveIntegerField(null=True, blank=True) preferred_name = models.CharField(null=True, blank=True, max_length=75) # adds model for entering company email domains and assigning groups class EmailDomainGroup(models.Model): email_domain = models.CharField(max_length=255, unique=True) group = models.ForeignKey(Group, on_delete=models.CASCADE) def __str__(self): return self.email_domain apps.py from django.apps import AppConfig class AccountsConfig(AppConfig): default_auto_field = 'django.db.models.BigAutoField' name = 'accounts' ready_executed = False # Add this flag def ready(self): if not self.ready_executed: import accounts.adapter import accounts.signals print('signal called') import accounts.admin self.ready_executed = True # Set the flag to True after executing the logic signals.py # accounts/signals.py from django.db.models.signals … -
How to make only the last few characters show in a CharField for a django model
I have a model with a secret key field: class Settings(model.Models): secret_key = models.CharField(max_length=100) I do not want this field to be seen publicly. How do I make only the last few characters show and star out or hide the rest. -
Using NewRelic monitor of Django Channels/asyncio/asgi
NewRelic doesn't have a documented example of how to monitor a Django Channels application. Mostly concern about monitoring the eventloop, using the methods provided here don't seem to work as ProtocolRouter in Channels is the "application" and seems layers deep since we are running Gunicorn with Uvicorn workers. Love to see someone who has implemented this. -
most optimal approach for my django application regarding django cache
I am using DRF token based authentication with Django with custom user model and using PostgreSQL (in AWS RDS) as DB. Now everything is running on AWS EC2 t3.micro (as free tire available). And using SSL certificate and configured nginx and Gunicorn properly and working fine as a wsgi application. Now i added a chat feature using django channels (in my local sys and not on ec2). Now my chat app is designed such that if a user send message to offline user i am storing them in django filecache (decided not to store chat in database to decrease read/write operations on database) (key=username,value=[msg1,msg2,...]) and send them when he is available. And using Inmemory_channel_layer backend. Everything working fine in my local system. Now what I want is:- As filecache is not recommended for production, i want a efficient way to cache that. should i use Redis or it is overkill for such small task?, if i want to use Redis shall i use it in my ec2 instance itself or host separately using aws elastic cache? or are there any better alternatives? I want to use the same cache for token authentication as well if possible (a copy of token … -
Change foreign key data type from bigint to string
While im trying to save an instance of a model I get the error for having wrong data type in foreign key it says it must be a bigint however the primary key is charfiled of the model which is made as a foreign key. I checked the primary key again, I tried explicitly to link to the name field of that model -
redirect to same url which is user in that using django
I have an list view "product_list" and here that's html file button which I want to redirect that to the same url which is .../products/: <form action="{% url 'cart:cart_add' product.id %}" method="post"> {% csrf_token %} <input hidden="hidden" name="quantity" value="1"> <button type="submit" class="btn btn-small btn-bg-sand btn-color-dark px-3"> {% trans 'Add to Cart' %} </button> </form>` that's view is: @require_POST def add_to_cart_view(request, product_id): cart = Cart(request) product = get_object_or_404(Product, id=product_id) form = AddToCartProductForm(request.POST) if form.is_valid(): cleaned_data = form.cleaned_data quantity = cleaned_data['quantity'] cart.add(product, quantity, replace_current_quantity=cleaned_data['inplace']) return redirect('cart:cart_detail') and here that's urls.py file: app_name = 'cart' urlpatterns = [ path('', cart_detail_view, name='cart_detail'), path('add/<int:product_id>/', add_to_cart_view, name='cart_add'), path('remove/<int:product_id>/', remove_from_cart, name='cart_remove'), path('clear/', clear_cart, name='cart_clear'), ] now I want redirect that with this urls, how I can redirect this view to any page that user in that, I mean if user in anywhere of site (e.g, list view, detail view, and etc.) stay that and process continue to adding product to cart. -
Primary Key Error In PostgreSQL Database when using Django Admin Panel
I am developing a website. To test the routes and functions, I added some data to a table, I directly uploaded that data to the database from a csv file. At this time there were 4 entry to the table. I went to django admin panel and it showed all the data correctly. I then added another column to database (a foreign key). After that i tried to enter a new data via django admin panel. After 4 try (where it showed primary key is already there) it started accepting the entry. This is second time this has happened with me in a python and PostgreSQL condition. First time it was with Flask using SQLAlchemy. At that time I deleted data mistakenly I inserted via other routes there also. What is happening here? I have no clue, please help and tell me what I can do to avoid this. Because I can handle 4 or 5 entries, but what will happen when I have to keep trying 100 times. I have no idea what the problem is and why it starts working after retrying number of rows in the table. Please help. -
I'm struggling to create a if condition with a for loop with Django template language
View my code here https://gist.github.com/Schultzy11/d93bc34d13adc1263337604c44827147 I have a for loop with the 'listings' variable that works and I can index into it to create the values I want. But when I try to create an if condition with the top_bids variable and index into it with .listings.id it does not give me the expected result. For reference When I print the top_bids variable I get {1: 700.0, 2: None}. I expect to get: the first post showing Top Bid: $700 and the second to show Starting Price $10000 this is what I am currently getting enter image description here -
calculate total amount from the sub total( New to JS )
when ever i change value in Quantity the sub total is calculate. but i need to calculate the total amount also by sum all the sub total values. How to achieve this. when ever i change value in Quantity the sub total is calculate. but i need to calculate the total amount also by sum all the sub total values. How to achieve this. -
Why do I get "This field is required" error from Django imageField?
I have problems with Django's image field. It says that the image field is empty even though I have selected an image This is my models.py: from django.db import models class Post(models.Model): picture = models.ImageField(upload_to="uploads") This is my forms.py: from django import forms from django.forms import ModelForm from .models import Post class PostForm(ModelForm): class Meta: model = Post fields = '__all__' This is my views.py: from django.shortcuts import render, redirect from .forms import PostForm def postsite(request): form = PostForm() if request.method == 'POST': form = PostForm(request.POST, request.FILES) if form.is_valid(): form.save() else: print(form.errors) return redirect('post') context = {'form':form} return render(request, 'post.html', context) And this is my post.html: <form action="" method="POST" enctyppe="multipart/form-data"> {% csrf_token %} {{form.as_p}} <input type="submit" value="Submit Post"> </form> After I have selected an image for the imageField and submitted the form, the output of this code print(form.errors) is: <ul class="errorlist"><li>picture<ul class="errorlist"><li>This field is required.</li></ul></li></ul> Because of other discussions about this error I tried to add this to my form: enctyppe="multipart/form-data" However, the error still persisted. -
Cause of this error: No List matches the given query
The user can add that product to the watch list by clicking on the add button, and then the add button will change to Rimo. And this time by clicking this button, the product will be removed from the list. There should be a link on the main page that by clicking on it, all the products in the watch list will be displayed, and by clicking on the detail button, you can see the details of the product, and by clicking on the remove button, you can remove them from the list. It sends me this error when I click on the button. What is wrong? Page not found (404) No List matches the given query. Request Method: GET Request URL: http://127.0.0.1:8000/add/?productid=1 Raised by: auctions.views.add Using the URLconf defined in commerce.urls, Django tried these URL patterns, in this order: admin/ [name='index'] login [name='login'] logout [name='logout'] register [name='register'] product_detail/<int:product_id>/ [name='product_detail'] watchlist/<str:username> [name='watchlist'] add/ [name='add'] The current path, add/, matched the last one. views.py: @login_required(login_url="login") def watchlist(request, username): products = Watchlist.objects.filter(user = username) return render(request, 'auctions/watchlist.html', {'products': products}) @login_required(login_url="login") def add(request): product_id = request.POST.get('productid', False) watch = Watchlist.objects.filter(user = request.user.username) for items in watch: if int(items.watch_list.id) == int(product_id): return watchlist(request, request.user.username) … -
ImportError for Nonexistent File in Django's Main Branch After Working on Separate Branch
I'm encountering an ImportError in my Django project involving branch management. Here's what I did: New branch: In a branch named test-new-spider, I created and committed a file named spider_base.py, which includes a class SpiderStores and a new command to run the spiders. Switching to Main Branch: After committing these changes in the test-new-spider branch, I switched to the main branch, which does not include the spider_base.py file, as the changes were not merged. Issue in Main Branch: Now, when trying to run the spider in the main branch, I encounter the following error: ImportError: cannot import name SpiderStores This is confusing because spider_base.py does not exist in the main branch; it's only in the test-new-spider branch where it has been committed. I deleted some files that were generated as eggs and logs, thinking they might be causing conflicts or stale references. I disconnected from the virtual environment to ensure that there were no environment-specific issues contributing to the problem. I searched for any instances of spider_base and SpiderStores in the main branch to confirm that it indeed doesn't exist there. -
Django-cors-headers not working with Django and Vue
When I try to access my Django rest framework from the frontend I get this error and the data is not passed along enter image description here I tried using django-cors-headers and every setting for it that I could find online; absolutely nothing worked. Here are the settings from my settings.py file (currently commented out) enter image description here enter image description here I also tried using custom middleware that I found here on stack overflow. enter image description here I did not try to use the custom middleware and django-cors-headers together. I must have spent at least a day on this nonsense. I'd really appreciate a working solution or at least a workaround! PS: I am following this tutorial https://www.youtube.com/watch?v=7GWKv03Osek&t=189s He doesn't have the same problems that I am though. -
Cannot get the delete button to work in my Djangochat room app
When clicking the delete button, i get this message in the console and screen:Not Found: /delete_message/125/ HTTP DELETE /delete_message/125/ 404 [0.05, 127.0.0.1:63513]. The same code works in another system, but not here. The information is in the database with the correct id.. I want the user to be able to delete a message that may have the wrong information, or wrong code. Here is the code for submissions: room.html {% extends "base.html" %} {% block title %} {{room.name}} | {% endblock title %} {% block content %} <div class="p-5 text-center"> <h3 class="lg:text-6xl text-white">Room: {{ room.name }}</h3> </div> <div class=" flex flex-wrap w-full "> <div class="w-full md:w-2/3 lg:mx-auto p-4 bg-white rounded-xl"> <div class="chat-messages space-y-3" id="chat-messages"> {% for message in messages %} <div id="message-{{message.id}" class="p-4 bg-gray-200 rounded-xl"> <p class="font-bold"> {{message.user.username}} {{message.date_added}} </p> <p> {{ message.content|safe }} </p> <p>{% if message.user.username == current_user %}</p> <form action="" method="post"> {% csrf_token %} {{ form.as_p }} <button class="float-right d-inline" onclick="deleteMessage({{ message.id }})"> del </button> <br/> <br/> </div> {% endif %} {% endfor %} </div> </div> <div class="w-full md:w-1/3 lg:mx-auto p-4 bg-white rounded xl"> <form class=""> <div> <textarea name="content" id="editor"></textarea> </div> <button class="px-5 py-3 rounded-xl text-white bg-teal-600 hover: bg-teal-700" id="chat-message-submit"> Submit </button> </form> </div> </div> {% endblock … -
Making requests after logging in django
I want to apologise upfront for a noob level question. I am working on an e-commerce project where I am making a bunch of requests to Django from REST. These requests are as follows, GET request for fetching products POST request for onboarding new products PUT request for updating products POST request for login GET request for cart details GET/POST/PUT requests for address related queries etc. Since a lot of these requests are user specific (i.e. my onboarded products/my addresses/my cart data) I want to somehow manage identify customer from the request without actually passing the customer id. Is there a way to achieve this?