Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
fetch data using ForeignKey relationship data filtering
hai stackoverflow community, i need a favour from your side to complete this one class Store_Master(models.Model): id = models.IntegerField(primary_key=True) d_code = models.CharField(max_length=50,blank = True,null = True) showroom =models.CharField(max_length=50,blank = True,null = True) short_code=models.CharField(max_length=50,blank = True,null = True) type=models.CharField(max_length=50,blank = True,null = True) flat_house_no =models.CharField(max_length=50,blank = True,null = True) street_building_name=models.CharField(max_length=50,blank = True,null = True) landmark=models.CharField(max_length=50,blank = True,null = True) pincode=models.CharField(max_length=50,blank = True,null = True) area=models.CharField(max_length=50,blank = True,null = True) taluk=models.CharField(max_length=50,blank = True,null = True) district= models.CharField(max_length=50,blank = True,null = True) state=models.CharField(max_length=50,blank = True,null = True) status=models.CharField(max_length=50,blank = True,null = True) dob=models.CharField(max_length=50,blank = True,null = True) closed=models.CharField(max_length=50,blank = True,null = True) def __str__(self): return self.showroom class edition(models.Model): id = models.IntegerField(primary_key=True) district= models.ForeignKey(Store_Master, on_delete=models.DO_NOTHING) state = models.CharField(max_length=50, blank=True,null=True) vk_daily = models.CharField(max_length=50, blank=True,null=True) vk_dhinam= models.CharField(max_length=50,blank=True,null=True) def __str__(self): return self.district help me to write views for this on. in both tables district is present I use that as a foreign key. and I have some limited districts in that district we have more showrooms I need to map that using ForeignKey my expected output is when I click district the store_master data will appear on table view. please help me to resolve this thanks in advance -
smtplib.SMTPAuthenticationError: (534, b'5.7.9 Application-specific password required
smtplib.SMTPAuthenticationError: (534, b'5.7.9 Application-specific password required. Learn more at\n5.7.9 https://support.google.com/mail/?p=InvalidSecondFactor h22sm15927247pfv.25 - gsmtp') Environment Variable are set but does not work (even though it's the exact value). I have set the app password in google account, captcha is disabled I have set the env variables in .bashrc file export EMAIL_USER='da24@gmail.com' Comparision btw the os.environ.get('EMAIL_USER') and the mail value string is True -
When i register a worker, he gets added into both client and worker group. I only want him to be added to worker grp. For client it is working fine
When i register a worker, he gets added into both client and worker group. I only want him to be added to worker grp. For client it is working fine signals.py from django.db.models.signals import post_save from django.contrib.auth.models import User from django.contrib.auth.models import Group from .models import Client,Worker #worker signal def worker_profile(sender, instance, created, **kwargs): if created: group = Group.objects.get(name='worker') instance.groups.add(group) Worker.objects.create( user=instance, name=instance.username, ) print('profile created!') post_save.connect(worker_profile, sender=User) #client signal def client_profile(sender, instance, created, **kwargs): if created: group = Group.objects.get(name='client') instance.groups.add(group) Client.objects.create( user=instance, name=instance.username, ) print('Profile created!') `post_save.connect(client_profile, sender=User`) When i register a worker, he gets added into both client and worker group. I only want him to be added to worker grp. For client it is working fine signals.py Here is the views.py file from django.http.response import JsonResponse from django.shortcuts import render, redirect from .forms import CreateUserForm, AppointmentForm from .models import * from django.contrib.auth import authenticate, login, logout from django.contrib.auth.decorators import login_required from django.contrib.auth.models import Group from django.contrib import messages from .decorators import allowed_users, unauthenticated_user, worker_only from .forms import * from .filters import AppointmentFilter @unauthenticated_user def registerPage(request): form = CreateUserForm() if request.method == 'POST': form = CreateUserForm(request.POST) if form.is_valid(): user = form.save() username = form.cleaned_data.get('username') messages.success(request, 'Account was created … -
Django Youtube video download to client machine
Hi Friend I want to write python code to that video download to user machine. Now I send ajax request my view.py file and download video But my project videos file. def download_youtube_video(url): url="https://www.youtube.com/watch?v="+str(url) myVideo = YouTube(url) higest = myVideo.streams.get_highest_resolution().resolution if myVideo.streams.filter(res=higest).first().download('videos'): return True else: return False def ajax(request): if request.method == "GET": url=request.GET.get('url') if download(download_youtube_video(url)) == True: return JsonResponse(data = {"success":"Successs"}) else: return JsonResponse(data = {"success":"Error"}) -
Getting an CommandError in virtual environment in django app : You appear not to have the 'sqlite3' program installed or on your path
I am trying to create my first django website.I am using windows and visual studio code. I am following the tutorials given on their sitehere I have completed the part 1, now I want to use sqlite database. I have used the command $ python manage.py migrate Now I want to check the schema of the database created. I have tried running the command $ python manage.py dbshell But it is giving me error : CommandError: You appear not to have the 'sqlite3' program installed or on your path. I don't how to resolve. What I did? I have installed precompiled binaries from the official site. and also downloaded sqlite3.exe from the same link. Then I created a folder in my C:/ directory and included a folder SQLite and included these 3 files: sqlite3.def, sqlite3.dll and sqlite3.exe files. And also include the path of that folder into Environment Paths. Its working in a windows command prompt. But not running in virtual environment. Please suggest some solutions. -
Ran into this problem while using webbot library on python
Traceback (most recent call last): File "C:\Users\Anil\Desktop\instagram\instagram-brute-force.py", line 14, in <module> web = Browser() File "C:\Users\Anil\AppData\Local\Programs\Python\Python39\lib\site-packages\webbot\webbot.py", line 68, in __init__ self.driver = webdriver.Chrome(executable_path=driverpath, options=options) File "C:\Users\Anil\AppData\Local\Programs\Python\Python39\lib\site-packages\selenium\webdriver\chrome\webdriver.py", line 70, in __init__ super(WebDriver, self).__init__(DesiredCapabilities.CHROME['browserName'], "goog", File "C:\Users\Anil\AppData\Local\Programs\Python\Python39\lib\site-packages\selenium\webdriver\chromium\webdriver.py", line 93, in __init__ RemoteWebDriver.__init__( File "C:\Users\Anil\AppData\Local\Programs\Python\Python39\lib\site-packages\selenium\webdriver\remote\webdriver.py", line 268, in __init__ self.start_session(capabilities, browser_profile) File "C:\Users\Anil\AppData\Local\Programs\Python\Python39\lib\site-packages\selenium\webdriver\remote\webdriver.py", line 359, in start_session response = self.execute(Command.NEW_SESSION, parameters) File "C:\Users\Anil\AppData\Local\Programs\Python\Python39\lib\site-packages\selenium\webdriver\remote\webdriver.py", line 424, in execute self.error_handler.check_response(response) File "C:\Users\Anil\AppData\Local\Programs\Python\Python39\lib\site-packages\selenium\webdriver\remote\errorhandler.py", line 247, in check_response raise exception_class(message, screen, stacktrace) selenium.common.exceptions.WebDriverException: Message: unknown error: cannot find Chrome binary (Driver info: chromedriver=2.39.562718 (9a2698cba08cf5a471a29d30c8b3e12becabb0e9),platform=Windows NT 10.0.19042 x86_64) -
Multithreading in Django
I'm working on a Django project, in which I will need the use of multithreading and multiprocessing concepts (Send and receive data from other servers such as PACS server/ I/O Threads... ). The question I have is Django capable of applying multithreading /multiprocessing? Can we make two tasks run simultaneously or concurrently ? Thank you -
Django + PostgreSQL: how to identify user contributions?
I'm building a Django website based on a PostgreSQL database. Identified users will be allowed to add entities through the admin. I'm looking for a way to identify which entity was added by which user, to be able to keep the information associated with the record and retrieve it later. Is it possible? The "recent actions" widget that a connected user can see in the admin suggests it is. -
Reverse for 'edit-todo' with arguments '('',)' not found. 1 pattern(s) tried: ['edit\\-todo/(?P<id>[0-9]+)/$']
I've dug around the internet and can't find a solution. Please help me lovely people of the internet. In my views.py @login_required def edit_todo(request, pk): usertodo = get_object_or_404(Todo, pk=pk) return HttpResponse('test') In my urls.py urlpatterns = [ ... path('edit-todo/<int:pk>/', views.edit_todo, name='edit-todo'), path('test/<int:pk>/', views.edit_todo, name='test'), ... ] In my template/component that's included <form hx-encoding="multipart/form-data" hx-post="{% url 'core:edit-todo' tododetail.todo.id %}" hx-target="#todo-list" method="post"> tododetail.todo.id is called because I've got an ordering table which has todo & user as foreign keys. When accessing the view directly using a test URL it works -
How to allow the user to change theme color for a bootstrap4 theme using a color picker in a django website?
I want to allow the application users to be able to change the bootstrap theme color using a color picker. I haven't found any good examples yet on how to achieve this in Django. I understand that adding predefined themes and toggling between them is simpler. But in this case, I need to allow user to select from a color picker rather than switching between few predefined templates. -
Django Channels Consumer Not Connecting to websocket
i created a websocket with javascripts on the client side...then followed up with setting up my project to handle webocket connections as follows(following the official django-channels documentation). But each time i refresh the page and watch the websocket from the browser console...its fails. i inserted an print statement in the init of the consumer class and it was printed(each time a page containing a websocket was visited or refreshed)..which mean that the routing is working fine...but for some reasons the consumer is not connecting/accepting the connection as expected to the websocket. and again there is no log in the development server as to any websocket connection process.Please can anyone help and suggest a fix. my setting.py file(relevant lines) INSTALLED_APPS = [ ... 'channels', ] ASGI_APPLICATION = 'ma_mall.asgi.application' CHANNEL_LAYERS = { "default": { 'BACKEND': "channels_redis.core.RedisChannelLayer", "CONFIG": { 'hosts': [('127.0.0.1', 6379)], } } } my asgi.py file application = ProtocolTypeRouter({ "http": get_asgi_application(), "websocket": URLRouter( routing.websocket_urlpatterns ) }) my routing.py file websocket_urlpatterns = [ path("ws/notifications/", consumers.NotificationConsumer), ] my consumer file class NotificationConsumer(AsyncJsonWebsocketConsumer): groups = ['general_group'] async def connect(self): await self.accept() await self.channel_layer.group_add('notification_group', self.channel_name) await self.channel_layer.group_send('notification_group', { 'type': 'tester.message', 'tester': 'tester' } ) async def disconnect(self, close_code): await self.channel_layer.group_discard('notification_group', self.channel_name) the javascript for the … -
Removing element from for loop html django?
I have a for loop in my html to show the user their favourite games. Like this: <div class="dropdown-cart-products"> {% if user.is_authenticated %} {% for i in wishlist %} <div class="product"> <div class="product-details"> <h4 class="product-title"> <a href="{% url 'detail' i.oyunlar.platformurl i.oyunlar.slugyap %}">{{i.oyunlar.title}} {{i.oyunlar.platform}}</a> </h4> <span class="cart-product-info"> <!-- <span class="cart-product-qty">1</span>--> Anlık en ucuz Fiyatı: {{i.oyunlar.en_ucuz}} </span> </div><!-- End .product-details --> <figure class="product-image-container"> <a href="{% url 'detail' i.oyunlar.platformurl i.oyunlar.slugyap %}" class="product-image"> <img src=" {{i.oyunlar.image}}" alt="product"> </a> <a href="javascript:{document.getElementById('upvote1').submit()}" class="btn-remove" title="Favorilerden Çıkar"><i class="icon-retweet"></i></a> <form id="upvote1" method="POST" action="{% url 'favhome' i.oyunlar.game_id %}"> {% csrf_token %} </form> </figure> </div><!-- End .product --> {% endfor %} I am trying to remove element like this: form id="upvote1" method="POST" action="{% url 'favhome' i.oyunlar.game_id %}"> {% csrf_token %} </form> The problem is that I can only remove first element in this loop cannot remove the second one third one or last one. How can I change my code to remove the selected element? -
How do i inspect all tables in databes mssql by Django inspect
I have mssql database with few tables: [dbo].[one_table] [dbo].[two_table] [model].[three_table] [model].[four_table] [plan].[five_table] my django settings.py: DATABASES = { 'default': { "ENGINE": "mssql", "NAME": "ips_db", "USER": "sa", "PASSWORD": "***", "HOST": "***", "PORT": "1433", "OPTIONS": { "driver": "ODBC Driver 17 for SQL Server", }, }, } When i try inspect db by python inspectdb > models.py I get only one_table and two_table class One_table(models.Model): firstname = models.CharField(db_column='FirstName', max_length=30, db_collation='SQL_Latin1_General_CP1_CI_AS') # Field name made lowercase. lastname = models.CharField(db_column='LastName', max_length=40, db_collation='SQL_Latin1_General_CP1_CI_AS') # Field name made lowercase. class Meta: managed = False db_table = 'One_table' class Two_table(models.Model): test = models.CharField(db_column='Test', max_length=10, db_collation='SQL_Latin1_General_CP1_CI_AS', blank=True, null=True) # Field name made lowercase. tes2 = models.CharField(db_column='Tes2', max_length=10, db_collation='SQL_Latin1_General_CP1_CI_AS', blank=True, null=True) # Field name made lowercase. class Meta: managed = False db_table = 'Two_table' How can i get all tables models from my database??? -
How to fetch warnings from a django mysql query?
I'm trying to get a list of warnings after a mySQL query, using Django admin. I can see from the documentation here that it's possible to record warnings by setting connection.get_warnings to true. But I can't find anything explaining how to read those warnings. I do not want to throw an exception - I am deleting items from the database using a DELETE IGNORE statement and want to get all instances of deletions that failed (due to external keys, etc.) I've tried returning the result of the execute function itself (just gave me a number) and calling fetchwarnings() on the cursor (threw a "Cursor object has no attribute fetchwarnings" error). I'm still new to both Python and Django. I'm looking through all the documentation I can find but can't find anything that works. from django.db import connection query = "{query here}" connection.get_warnings = True with connection.cursor() as cursor: cursor.execute(query) <-- Returns a number return cursor.fetchwarnings() <-- Throws an error -
django logdna not working. server getting stuck
import logging from logdna import LogDNAHandler LOGGING = { 'version': 1, 'disable_existing_loggers': False, 'formatters': { 'verbose': { 'format': "[%(asctime)s] %(levelname)s [%(name)s:%(lineno)s]" + "%(message)s", 'datefmt': "%d/%b/%Y %H:%M:%S" }, 'color': { '()': 'colorlog.ColoredFormatter', 'format': '%(log_color)s%(asctime)s %(levelname)-8s %(name)s %(module)s %(pathname)s:%(lineno)s%(reset)s \n\r\t %(message)s', 'datefmt': "%d/%b/%Y %H:%M:%S", 'log_colors': { 'DEBUG': 'cyan', 'INFO': 'green', 'WARNING': 'yellow', 'ERROR': 'red', 'CRITICAL': 'red,bg_white', } } }, 'filters': { 'require_debug_true': { '()': 'django.utils.log.RequireDebugTrue', }, }, 'handlers': { 'console': { 'level': 'DEBUG', 'filters': ['require_debug_true'], 'class': 'logging.StreamHandler', 'formatter': 'color' }, 'logdna': { 'level': logging.DEBUG, 'class': 'logdna.LogDNAHandler', 'key': "f47ec154e993efce66ed784ad7g3g76b8cb91", 'options': { # 'app': '<app name>', # 'env': "alpha", 'index_meta': True, }, }, }, 'loggers': { '': { 'level': logging.DEBUG, 'handlers': ['logdna'], 'propagate': True, }, } } I am using above code for django logging using logdna. But when i am running django server it is getting stuck . what can be the reason ? Am i doing it correctly ? Please take a look I am following https://github.com/logdna/python doc for implementation. django with logdna for logging -
Sanitizing SQL input in Django for PostgreSQL
I know that there are tools how to prevent sql injection especially with psycopg2 and how to work with them, but i have an other use case. The query should not be directly executed in PostgreSQL, but in InfluxDB as a part of join between metadata from PostgreSQL and measurements from InfluxDB that is done with the sql package from it. So i need to produce a string part of a bigger query that is totally safe, especially in the filter part of the query where a LIKE part is entered. I think this is possible by acquiring the the cursor object of the connection from the connection pool and then use mogrify() to get the safe sql after binding, but this approach seems complex and unnecessary as i don't need to execute it in PostgreSQL directly. Is there a tool or library in Python that can check/adapt/escape/sanitize the query as a string, or bind parameters in a safe way? -
JQuery and Vuejs APIs not passing nor retrieving data to database Django
I had working been on a web app using Django and had to take a 3-month break. I decided to continue and suddenly all my jquery and vuejs code is not working although it had been perfectly working 3-months ago. This is my base.html <head> <link href="https://vjs.zencdn.net/7.11.4/video-js.css" rel="stylesheet"> <!-- Vue Js --> <script src="https://cdn.jsdelivr.net/npm/vue/dist/vue.js"></script> <!-- JQuery script --> <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js"></script> </head> urls.py from conversation.api import api_add_message urlpatterns = [ path('api/add_message/', api_add_message, name='api_add_message'), ] api.py import json from django.http import JsonResponse from django.contrib.auth.decorators import login_required from .models import ConversationMessage @login_required def api_add_message(request): data = json.loads(request.body) content = data['content'] conversation_id = data['conversation_id'] message = ConversationMessage.objects.create(conversation_id=conversation_id, content=content, created_by=request.user) template.html <li class="chat-left" v-for="message in messages"> <div class="chat-avatar"> <img :src="message.image"alt="Retail Admin"> <div class="chat-name">[[ message.user ]]</div> </div> <div class="chat-text">[[ message.content ]]</div> <div class="chat-hour">[[ message.user ]]</div> </li> And this is my script in the template {% block script %} <script> var conversationapp = new Vue({ el: '#conversationapp', delimiters: ['[[', ']]'], data () { return { messages: [], content: '', user: '{{ request.user.username }}', created_at: 'Now', image: '{% if request.user.profile.image %}{{ request.user.profile.image.url }}{% endif %}' } }, methods: { submitMessage() { if (this.content.length > 0) { var message = { 'content': this.content, 'user': this.user, 'created_at': this.created_at, 'image': this.image, … -
How do you combine two querysets into one queryset(not a list) in django?
I want to simply combine two querysets from different models into one queryset (and not a list as shown in other stackoverflow questions!). For example, here are two querysets: a = Modelone.objects.all() b = Modeltwo.objects.filter(number__gte=4) Then, I want a queryset c that combines both a and b. Thank you, and please leave me any questions you have. -
hello, why does my template Django not want to display the results of my review form?
I cannot understand why the result of my review form is not showing in the template, even though my ticket form is working fine. However, I have linked the 2 models with a foreign key. Then in the template I added "ticket.id". Finally, the objective of this app is to limit the review to one person. Thank you in advance for your help. My models: class Ticket(models.Model): title = models.CharField(max_length=128) content = models.TextField(max_length=2048, blank=True, null=True) image = models.ImageField(null=True, blank=True) user = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.CASCADE) date_created = models.DateTimeField(auto_now_add=True) def __str__(self) : return self.title class Review(models.Model): ticket = models.ForeignKey(Ticket, related_name="reviews" ,on_delete=models.CASCADE) rating = models.PositiveIntegerField(validators=[MinValueValidator(0),MaxValueValidator(5)]) user = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.CASCADE) headline = models.CharField(max_length=128) body = models.TextField(max_length=8192, blank=True, null=True) time_created = models.DateTimeField(auto_now_add=True) def __str__(self) : return self.ticket.title My forms : class TicketForm(forms.ModelForm): class Meta: model = models.Ticket fields = ['title', 'content','image'] class ReviewForm(forms.ModelForm): class Meta: model = models.Review fields = ['rating','headline','body'] My view : @login_required def review(request, ticket_id): ticket = get_object_or_404(models.Ticket, id=ticket_id) review_form = forms.ReviewForm(instance=ticket) if request.method == 'POST': review_form = forms.ReviewForm(request.POST, instance=ticket) if review_form.is_valid(): review = review_form.save(commit=False) review.user = request.user review.save() return redirect('home') return render(request, 'flux/create_review_post.html', context={'review_form': review_form}) My urls: path('home/', flux.views.home, name='home'), path('ticket/create/', flux.views.ticket, name='ticket_create'), path('flux/<int:ticket_id>/', flux.views.view_ticket, name='view_ticket'), path('<int:ticket_id>/review/create/', flux.views.review, name='review_create'), My template review … -
How to make media file's URL restricted to the unauthenticated users in Django?
I am going to build a Django storage application where users can upload files to the server. Users also can download their files from the server. To download the file, the server returns the URL of the media file to the user. I added a permission class, if the user is authenticated & owner of the file then return the URL of the media file, otherwise return 404. But there is a problem, if any unauthenticated user found the URL of the media file from the history of the browser, then he can download/access the file. How can I handle this case? -
Displaying DynamoDB data in Django admin panel
I want to show data from DynamoDB on the Django admin panel page. I have tried PynamoDB to create the model and register it with the admin panel. I am facing the following two issues: Getting only attribute 'id' instead of all attributes from the DynamoDB table. I have confirmed this issue while fetching attribute_definitions from the DynamoDB table using boto3. attribute_definitions = table_name.attribute_definitions The second issue I am facing is that I get errors while registering the created Model(by using PynamoDB) with the admin panel. I get the issue "TypeError: 'MetaModel' object is not iterable" -
Django equivalent to PostgreSQL NOT EXISTS?
I have to make some in_bulk queries in my project, which uses Django and PostgreSQL. Right now, I'm using the following query to return the desired queryset: users_list = [user.id for user in get_cached_users(request.uuid)] users_dict = User.objects.filter(~Q(pk__in=users_list)).values() I've heard that using Q objects to create "not_in" queries is not as optimized as the PostgreSQL NOT EXISTS, but I never heard of an equivalent in Django. Do you guys know if there is a direct one? -
ERROR: Failed building wheel for dependency-injector, ERROR: Failed building wheel for pyduktape
Failed to get both dependency injector and pyduktape in Django project requirements.txt. It asked to install Visual C++ 14.0 or greater but it is already there. requirements.txt containts dependency-injector==3.15.6 and pyduktape==0.0.6 Tried with Python 3.7, pip 21.3.1, and pipenv version 2021.5.29 '''Building wheels for collected packages: dependency-injector, pyduktape Building wheel for dependency-injector (setup.py) ... error ERROR: Command errored out with exit status 1: command: 'c:\users\yasiru\appdata\local\programs\python\python37\python.exe' -u -c 'import io, os, sys, setuptools, tokenize; sys.argv[0] = '"'"'C:\Users\yasi ru\AppData\Local\Temp\pip-install-ai16fcys\dependency-injector_e905913ba3f247b096ecaaf379d20b5b\setup.py'"'"'; file='"'"'C:\Users\yasiru\AppData\Loca l\Temp\pip-install-ai16fcys\dependency-injector_e905913ba3f247b096ecaaf379d20b5b\setup.py'"'"';f = getattr(tokenize, '"'"'open'"'"', open)(file) if os.path .exists(file) else io.StringIO('"'"'from setuptools import setup; setup()'"'"');code = f.read().replace('"'"'\r\n'"'"', '"'"'\n'"'"');f.close();exec(compile(co de, file, '"'"'exec'"'"'))' bdist_wheel -d 'C:\Users\yasiru\AppData\Local\Temp\pip-wheel-23n96w5t' cwd: C:\Users\yasiru\AppData\Local\Temp\pip-install-ai16fcys\dependency-injector_e905913ba3f247b096ecaaf379d20b5b Complete output (13 lines): running bdist_wheel running build running build_py creating build creating build\lib.win-amd64-3.7 creating build\lib.win-amd64-3.7\dependency_injector copying src\dependency_injector\errors.py -> build\lib.win-amd64-3.7\dependency_injector copying src\dependency_injector_init_.py -> build\lib.win-amd64-3.7\dependency_injector copying src\dependency_injector\containers.pxd -> build\lib.win-amd64-3.7\dependency_injector copying src\dependency_injector\providers.pxd -> build\lib.win-amd64-3.7\dependency_injector running build_ext building 'dependency_injector.containers' extension error: Microsoft Visual C++ 14.0 or greater is required. Get it with "Microsoft C++ Build Tools": https://visualstudio.microsoft.com/visual-cpp-build-tools/ ERROR: Failed building wheel for dependency-injector Running setup.py clean for dependency-injector Building wheel for pyduktape (setup.py) ... error ERROR: Command errored out with exit status 1: command: 'c:\users\yasiru\appdata\local\programs\python\python37\python.exe' -u -c 'import io, os, sys, setuptools, tokenize; sys.argv[0] = '"'"'C:\Users\yasi ru\AppData\Local\Temp\pip-install-ai16fcys\pyduktape_d628ca64f5d1498c83b77edf959e9080\setup.py'"'"'; file='"'"'C:\Users\yasiru\AppData\Local\Temp\p ip-install-ai16fcys\pyduktape_d628ca64f5d1498c83b77edf959e9080\setup.py'"'"';f = … -
Vanilla Javascript: How to add multiple event listeners to buttons which are dynamically created with same class in django?
I am currently working on a project 4 for CS50w - Network. One of the tasks is to add an edit posts button (for editing the posts that logged in user (only owner) created), which does this async. Since for storing posts I'm using Django Models, I'm using Django (and it's template capabilities) to display all the posts to users too, and an edit button (if user is the creator of the post too). I'm displaying all the posts in a div. This means that the button for editing is also a part of this div... meaning that I can give it only single class or id for referencing, but then I don't know how to distinguish between them, and how to know which one (from which post) is clicked so that I can edit that post and not the first one on which the JS in DOM comes up... Anyways here's the code: HTML in Django: {% for post in posts %} <div class="post"> <a href="{% url 'users' post.user.username %}">{{ post.user }}</a> <p>{{ post.content }}</p> <p>{{ post.created }}</p> {% if user.is_authenticated and user == post.user %} <button class="edit_post_button">Edit Post</button> {% endif %} </div> <div class="edit_post" style="display: none;"> <a href="{% … -
Getting an error 500 when trying to upload images to heroku app
Having trouble deploying a project to heroku app. Images won't shop up and I get an error 500 code