Django community: Django Q&A RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Django: Reverse lookup of optional foreignkey-entry and inclusion in dataset
I would like to compose list of database entries, and corresponding (but not necessarily existing) related entries in another table. The concrete context is a list of events, in which the user should be able to see, whether he already stated his participation (thus has an entry in the database which should be displayed) or not (which would give him a link to a participation form) My models (minimal): class Event(models.Model): title = models.CharField(max_length = 200) #... class Event_Participation(models.Model): EVENT_PARTICIPATION_CHOICES = [ ("Y", "Yes"), ("N", "No"), # few other options ] event = models.ForeignKey(Event, on_delete=models.CASCADE) participation = models.CharField(max_length=1, choices= EVENT_PARTICIPATION_CHOICES) user = models.CharField(max_length=10) #originally another foreign key Ideally, I'm searching for one expression like Event.appendIfExists(Event_Participation)... For template rendering, I was able to query the data, but this doesn't seem elegant and I don't know, how to merge the information inside the template: def event_list(request): e_all = Event.objects.all() #normally filtered part_list = {} for e in e_all: if e.event_participation_set.get(user_id = request.user.id) : p = e.event_participation_set.get(user_id = request.user.id).participation else: p = "X" part_list[e.id]= p context = {"part_list":part_list,"full_event_list":e_all} return render(request, "event_list.html", context) An index-based variable in the template did not work for part_list, and I was not able to extend the queries in … -
Page not found (404) error django for given id in url
I have this path : re_path('likecomment/(?P<comment_id>[0-9]+)/', LikeComment_view , name="LikeComment_page"), and I have the fallowing view: def LikeComment_view(request , comment_id): comment = get_object_or_404(Comment , id=comment_id) if not comment.likes.filter(id = request.user.id).exists(): comment.likes += 1 comment.liked.add(request.user) comment.save() else: comment.likes -= 1 comment.liked.remove(request.user) comment.save() and I generate the url with this code in template: {% url 'LikeComment_page' i.id %} and when I try to enter this url : http://127.0.0.1:8000/likecomment/6/ I get an 404 error . I have the object with id=6 but I still get this error! -
remove ManyToMany from model but still access data
I'm a DJANGO/python novice and I have two models Enqueue and EnqueueGroup. Enqueue has a M2M field: groups = models.ManyToManyField( "EnqueueGroup", related_name="Enqueued", blank=True, ) if I remove the groups field from the Enqueue model, what do I need to do in order to access the data formerly in groups if EnqueueGroups is currently as follows class EnqueueGroup(models.Model): name = models.CharField( max_length=100, null=False, blank=False, ) description = models.TextField( null=True, blank=True ) class Meta: app_label = "test" verbose_name = "Enqueue Group" verbose_name_plural = "Enqueue Groups" def __str__(self): return "Enqueue Group {}".format(self.name) read through the DJANGO M2M and relational database docs. I understand that the relation is called groups in Enqueue and Enqueued in EnqueueGroup. I just dont /get/ how to still access the data. -
The data in a table when this code is refreshed in a django server disappers. How to make it so that the code stays and just new rows in db stay?
I am running django server and when I run the server for the first time the code adds the data to the database. Upon running it a second time the data in the database disappears. How do I have it so that everytime the server runs it just adds the new data to the database? The data in this case is youtube data import sqlite3 def youtube_data(request): # Replace 'YOUR_API_KEY' with your actual YouTube Data API key api_key = 'YOUR_API_KEY' youtube = build('youtube', 'v3', developerKey=api_key) channel_ids = ['CHANNEL_ID_1', 'CHANNEL_ID_2', 'CHANNEL_ID_3'] # Replace with the desired channel IDs videos = [] conn = sqlite3.connect('your_database.sqlite3') # Replace 'your_database.sqlite3' with your SQLite database file path try: for channel_id in tqdm(channel_ids, desc="Extracting Channels"): response = youtube.search().list( part='snippet', channelId=channel_id, maxResults=10 ).execute() for item in tqdm(response.get('items', []), desc="Extracting Videos"): video_id = item.get('id', {}).get('videoId') if video_id: # Check if the video already exists in the database cursor = conn.cursor() query = "SELECT * FROM youtube_video WHERE video_id = ?" cursor.execute(query, (video_id,)) result = cursor.fetchone() if not result: try: video_data = youtube.videos().list( part='snippet, statistics, contentDetails', id=video_id ).execute() snippet = video_data['items'][0]['snippet'] statistics = video_data['items'][0]['statistics'] content_details = video_data['items'][0]['contentDetails'] transcript = get_video_transcript(youtube, video_id) insert_query = """ INSERT INTO youtube_video (published_at, title, … -
Why N+1 problem is enormous in DRF and how can I solve it?
I have site that was powered on vanilla django framework. I created a custom manager for my models to reduce N+1 problem and it worked very well. But when I moved to DRF, I just can't handle it with usual select_related and prefetch_related methods. Number of queries has increased dramatically. For example, here is my UserPostListView that should display 10 user's posts: class UserPostListView(generics.ListAPIView): serializer_class = PostSerializer comment_serializer_class = CommentSerializer def get_queryset(self): slug = self.kwargs['slug'] return Post.objects.detail().filter(author__slug=slug).order_by('-post_date') def list(self, request, *args, **kwargs): response = super().list(request, *args, **kwargs) data = response.data posts = data['results'] for post in posts: comments = Comment.objects.detail().filter(post_id=post['id'], comment_to_reply=None)[:5] serialized_comments = self.comment_serializer_class(comments, many=True).data post['comments'] = serialized_comments data['results'] = posts response.data = data return response It generates around 130 queries. I tried move this comment functionality to the serializer. It didn't help at all. Ideally I see it working smth like that: class PostSerializer(TaggitSerializer, serializers.ModelSerializer): author = UserSerializer(read_only=True) tags = CustomTagListSerializerField(required=False, allow_empty=True, allow_null=True) connected_subs = UserFilteredSubscriptionsField(many=True, required=False) post_media = PostMediaSerializer(many=True, required=False) likes_count = serializers.SerializerMethodField() views_count = serializers.SerializerMethodField() comments_count = serializers.SerializerMethodField() calculate_grid = serializers.SerializerMethodField() def get_comments(self, instance): comments = Comment.objects.detail().filter(post=instance, comment_to_reply=None)[:5] comments_serializer = CommentSerializer(comments, many=True) return comments_serializer.data def to_representation(self, instance): representation = super().to_representation(instance) representation['comments'] = self.get_comments(instance) return representation But actually … -
Why page renders slowly (about 2s)? Django
Rendering page takes too long (about 2s) Even if i return dummy data (without querying) page renders slowly. But when i return empty dict tasks_by_day it takes only ~150ms to load page. My question is why it takes so much time to process so small amount of data and how can I fix this? Here is my view code: def tasks(request): tasks = Task.objects.filter(owner=request.user.id) tasks_by_day = { "MONDAY" : [tasks[0]], "TUESDAY" : [tasks[1]], "WEDNESDAY": [tasks[2]], "THURSDAY": [tasks[3]], "FRIDAY": [tasks[4]], "SATURDAY": [tasks[5]], "SUNDAY": [tasks[7]] } return render(request, "todo/tasks.html", {"tasks_by_day": tasks_by_day}) Here is my model code: class Task(models.Model): # DAY_OF_THE_WEEK_CHOICES, STATUS_CHOICES - constants day_of_the_week = models.CharField( max_length=10, choices=DAY_OF_THE_WEEK_CHOICES, default=default_day ) status = models.CharField( max_length=2, choices=STATUS_CHOICES, default=NOT_COMPLETED ) task_text = models.CharField(max_length=200) owner = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.CASCADE) I've measured time that needed to execute tasks function - it's around 110ms. -
django : How can i check if an object is exist in a many-to-many relation?
I have a model named Post that has some fields like this : class Post(models.Model): title = models.CharField(max_length=500) slug = models.SlugField(allow_unicode=True , unique=True , null=True , blank=True) likes = models.ManyToManyField(User , blank=True , help_text="amount of likes") likes_count = models.IntegerField(default=0 , help_text="amount of likes") def __str__(self): return self.title and I have a view that needs to check if the user is in "likes" relation and do some stuff . But I don't know what to do ! this is my view: def Like_view(request , slug): post = get_object_or_404(Post , slug=slug) if not request.user in post.likes: post.likes.add(request.user) post.likes_count += 1 post.save() else: post.likes.remove(request.user) post.likes_count -= 1 post.save() -
HTMX form not getting file upload succesfully with django
I have this form: class FormCotacao(forms.Form): descricao = forms.CharField( label = 'Descrição', max_length = 200, required = True ) valor1 = forms.FloatField( label = "Valor 1 (R$)", required = True ) orcamento1 = forms.FileField( label = "Orçamento 1", widget = forms.FileInput(attrs={'accept': '.pdf, .xls, .xlsx'}), required = True ) This htmx: {% load crispy_forms_tags %} <form method="post" enctype="multipart/form-data" hx-enconding="multipart/form-data" action=""> {% csrf_token %} {{ form|crispy }} <input type="hidden" name="id" value="{{ orcamento.id }}"> <input type="hidden" name="acao" value="addItemCotacao"> <button type="button" class="btn btn-secondary" hx-get="{% url 'visualizar-orcamento' id %}" hx-swap="innerHTML" hx-target="#itemsAdicionados">Cancelar</button> <button type="submit" hx-post="{% url 'item-cotacao' id %}" hx-swap="innerHTML" hx-target="#itemsAdicionados" class="btn btn-primary" name="addItemCotacao">Salvar item</button> </form> And this is the view to which it's directed: def orcamentoCotacao(response, id): usuario = response.user orcamento = Orcamento.objects.get(id=id) if orcamento.aprovado != True: if response.method == 'POST': form = FormCotacao(response.POST) arquivos = response.FILES if form.is_valid(): pass else: form = FormCotacao() context = { 'form': form, 'id': id } return render(response, "main/partials/item-cotacao.html", context) When the user uploads files in the form, they show up in response.POST but, for some reason, there's nothing in response.FILES. What might be the problem? -
Ubuntu Django WebSocket connection to ... failed
i am new to this field, i tried to run websocket in ubuntu but it gives error i followed the instructions on this page(enter link description here) i don't understand where the error is located. -
How to run a Jupyter Notebook tool in a server
I have created data analysis tool using Jupyter Notebook. Currently, I installed python+Jupyter Notebook in virtual machine and my teammates login to VM to use the tool. But, it’s limiting the users as only one person can login at a time. So, moving forward , I want to keep tool in a server so n number of users can use it at a time. Note: I am from non-it background. Except coding and logic building, don’t have any knowledge on server, web application etc. currently, I built and developed code in Jupyter notebook.. once Jupyter Notebook finishes running user saves notebook as html report as notebook has all plots and statistical tables. I see some options like streamlite, mercury but I didn’t get any clear idea for my problem. I want to run Jupyter Notebook in the backend and save it as html report but users should run from their own laptops without login to virtual machine or installing anaconda distribution on their laptops -
Passing Correct POST request from React component, but Django view is receiving an empty dictionary
In my application, users can play songs and the play count is supposed to get updated in the backend. When I pass the song ID of the song that needs it's play count incremented, it is being passed as None. When I hardcode a song ID into the Django view, the plays are incremented like it's supposed to, but when I try to use the song ID that is passed from the frontend, it passes None. This is the where the handlePlay function is called, which handles the play count update <audio controls src={`/media/${song.file}`} data-song-id={song.id} onPlay={() => handlePlay(song.id)} ></audio> This is the handlePlay function which makes the request to the backend. Both of the console.log(songID) lines are correctly logging the song ID in the browser console. function handlePlay(songID) { console.log(songID) axios .post('/api/update-plays/', { "songID": songID }) .catch((error) => { console.log(error); }); console.log(songID) } This is the updatePlays Django view which gets the song ID, finds the song, then increments the play count. When I print(request.POST), it prints an empty dictionary. @csrf_exempt def updatePlays(request): print(request.POST) if request.method == "POST": songID = request.POST.get("songID") song = Song.objects.get(id=songID) song.plays += 1 song.save() return JsonResponse({"song": song}, safe=False) return JsonResponse({"error": "error"}) When I hardcode the actual … -
Usage of .to_representation() in django-rest-framework resulting a slow response for a large(1000 records) list
I have an endpoint www.exapmle.com/list?page_size=1000 sample code looks like - class TestViewSetV10(ViewSet): queryset = Test.objects.all()#.order_by("pk") serializer_class = TestSerializerV10 filterset_class = TestFilterV10 class TestSerializerV10(serializers.ModelSerializer): #pass Backend serializers is serializers.ModelSerializer, which is calling .to_representation() in the list. This is leading to a slow response, taking around 2 min. Is there any way to optimize the above-mentioned case? -
How to fetch relation table one to another via serializer? django
I have two serializers for two models (Blog and User). This is one to many relation, User can have one or more Blog. But a Blog should belong only to one User. The goal is I want to include blogs model if I will fetch the user. vice-versa API: /user/1 response: { name: 'John Doe', blogs: [ <========== include { id: 1, title: 'First Blog', }, ... so on, so forth ] ... more field } The current situation is, the UserSerializer can incude the blogs. But in BlogSerializer it cannot include the user since "BlogSerializer" is not defined. class BlogSerializer(serializers.ModelSerializer): class Meta: model = Blog fields = "__all__" user = UserSerializer(many=True, read_only=True) class UserSerializer(serializers.ModelSerializer): class Meta: model = User fields = "__all__" blog = BlogSerializer(many=True, read_only=True) Do you have idea how to fix or achieve this? I'm new in Django, I would appreciate any comments or suggestions. -
Django: query parameters in the middle of the url - how?
This is a Django project and our project lead has come up with following URL-schema: <some-url>/avail?region_id=1&date=2021-01-01 ... get avail-data for given region and date <some-url>/cust?id=1/regs/ ... meaning we want the regions of customer with id 1 Now for all I know this is not really the way you normally would do it in Django, where you would define an URL as something like: <some-url>/cust/1/regs/ Furthermore I read that "query parameters are usually handled in the view" with request.query_params.get(). But if we go forward with this URLs-schema of having query parameters - even in the middle of the URL as in the 2nd case - what would be the best way of implementing it? How to set up urls.py? Another option would be to convince our lead of a better way - a more Django-ish way? How would we best define these URLs to adhere to Django conventions? -
`ValueError: %s has host bits set` while using InetAddressField in django model
I am using InetAddressField from django.netfields to store IP address in DB. I followed steps from this answer. I have following model: class MyModel(models.Model): // some fields ... ip_address = InetAddressField() objects = NetManager() I have two REST end points, one with MyModel.objects.exclude(ip_address__net_contained=subnet_mask) and another with MyModel.objects.filter(ip_address__net_contained=subnet_mask) where subnet_mask is input from UI. Now the thing is all bits for host need to be zero in subnet mask. In, 10.0.0.2/24, its 2. So it gives error as follows: ERROR [2023-06-15 20:49:41,326] [django.request] [log] [Process:2090] [Thread:139874097665792] Internal Server Error: /my_module/my_rest_endpoint Traceback (most recent call last): File "/usr/local/lib/python3.6/site-packages/django/core/handlers/exception.py", line 34, in inner response = get_response(request) File "/usr/local/lib/python3.6/site-packages/django/core/handlers/base.py", line 115, in _get_response response = self.process_exception_by_middleware(e, request) File "/usr/local/lib/python3.6/site-packages/django/core/handlers/base.py", line 113, in _get_response response = wrapped_callback(request, *callback_args, **callback_kwargs) File "/myapp/my_module/views.py", line 484, in my_rest_endpoint .exclude(ip_address__net_contained=subnet_mask) File "/usr/local/lib/python3.6/site-packages/django/db/models/query.py", line 899, in exclude return self._filter_or_exclude(True, *args, **kwargs) File "/usr/local/lib/python3.6/site-packages/django/db/models/query.py", line 908, in _filter_or_exclude clone.query.add_q(~Q(*args, **kwargs)) File "/usr/local/lib/python3.6/site-packages/django/db/models/sql/query.py", line 1290, in add_q clause, _ = self._add_q(q_object, self.used_aliases) File "/usr/local/lib/python3.6/site-packages/django/db/models/sql/query.py", line 1318, in _add_q split_subq=split_subq, simple_col=simple_col, File "/usr/local/lib/python3.6/site-packages/django/db/models/sql/query.py", line 1251, in build_filter condition = self.build_lookup(lookups, col, value) File "/usr/local/lib/python3.6/site-packages/django/db/models/sql/query.py", line 1116, in build_lookup lookup = lookup_class(lhs, rhs) File "/usr/local/lib/python3.6/site-packages/django/db/models/lookups.py", line 20, in __init__ self.rhs = self.get_prep_lookup() File "/usr/local/lib/python3.6/site-packages/netfields/lookups.py", … -
Django migration issues when changing model field
we have a Model with a field such as from core import snippets from modelcluster.fields import ParentalKey, ParentalManyToManyField tags = ParentalManyToManyField( snippets.Tag, blank=True, ) we have changed the snippets import from from readiness import snippets to from core import snippets where snippets is just the same but moved to the core app getting migration errors tags was declared with a lazy reference to 'readiness.tag', but app 'readiness' isn't installed. -
Having issues running py, python3, python etc. Environment Variables correct as far as I can tell
I have used Django in the past but just got this new computer and was running though the Django tutorial a refresher. Having issues running the python manage.py runserver command. I get "Python was not foun; run....." error. I've tried py, python, python3. I have made sure my path varibles are set correctly. Not really sure what to try next. The only thing that is different on this PC than other computers Ive used is my username has been set as (username.computername) not really sure but it has messed with some code I use to get the user for file directories. I added a path variable with my full path instead of the %USERPROFILE% incase this was effecting something. Path Varibles Image of CMD I have also looked at the "Manage App Execution Aliases" and python is clicked to on. Thanks in advance for any help here is what I'm getting from CMD: `C:\Users\jlr.DESKTOP-4N4QMUN\Documents\GitHub\Tracker_Reporting>py --version Python 3.11.4 C:\Users\jlr.DESKTOP-4N4QMUN\Documents\GitHub\Tracker_Reporting>python --version Python was not found; run without arguments to install from the Microsoft Store, or disable this shortcut from Settings > Manage App Execution Aliases. C:\Users\jlr.DESKTOP-4N4QMUN\Documents\GitHub\Tracker_Reporting>python3 --version Python was not found; run without arguments to install from the Microsoft Store, or disable … -
Nginx ERR_SSL_PROTOCOL_ERROR
Need help setting up Ngin. I need to set up https for my service This is the service configuration events {} http { server { listen 80; listen \[::\]:443 ssl; server_name example.com localhost; # SSL-сертификаты ssl_certificate /etc/nginx/certs/example.crt; ssl_certificate_key /etc/nginx/certs/example.key; ssl_session_cache shared:SSL:10m; ssl_session_timeout 10m; keepalive_timeout 70; ssl_protocols TLSv1 TLSv1.1 TLSv1.2; ssl_prefer_server_ciphers on; ssl_stapling on; ssl_trusted_certificate /etc/nginx/certs/ca.crt; resolver 8.8.8.8; location / { proxy_pass http://example_app:8000; proxy_set_header Host $host; proxy_set_header X-Real-IP $remote_addr; } } } This is the docker-compose.yml configuration version: '3' networks: imggen_network: driver: bridge services: nginx: container_name: nginx image: nginx:latest ports: - "80:80" - "443:443" volumes: - ./nginx/nginx.conf:/etc/nginx/nginx.conf:ro - ./nginx/certs:/etc/nginx/certs:ro depends_on: - example_app networks: - imggen_network The service works on port http://127.0.0.1:8000/, but when accessing https://127.0.0.1:8000/ it gives an error This site cannot provide a secure connection. Site 127.0.0.1 sent an invalid response. Run network diagnostics in Windows. ERR_SSL_PROTOCOL_ERROR The service works on port http://127.0.0.1:8000/, but when accessing https://127.0.0.1:8000/ it gives an error This site cannot provide a secure connection. Site 127.0.0.1 sent an invalid response. Run network diagnostics in Windows. ERR_SSL_PROTOCOL_ERROR -
Getting Docker-Compose file working on ubuntu
I have a django project running correctly with docker compose on my mac, but I want to get the docker-compose working on my linux ubuntu machine. When I run the docker-compose file on my mac everything works fine; however, I run into an issue on ubuntu where it says that port 5432 is in use. This is because: "On your Mac, you can run PostgreSQL on the host machine and use the same port (5432) without conflict because Docker for Mac uses a feature called "host networking" by default. With host networking, containers share the network stack with the host machine, allowing them to access services running on the host directly. In the case of your Docker Compose file, when you run it on your Mac with PostgreSQL running on the host on port 5432, the container can still access the PostgreSQL service on the host because it shares the network stack. The container's PostgreSQL service listens on the same port inside the container (5432) as the host's PostgreSQL service. So, when your Django application inside the container tries to connect to the database at localhost:5432, it effectively connects to the PostgreSQL service running on the host." So I modify … -
how to shrink my celery-worker docker image?
I am running Django application on ECS and I am trying to optimize the size of Docker containers. Below are my Dockerfiles that I am using to build django-app, celery-worker and celery-beat services on ECS. CMD are inserted in ECS task definition. The problem I have is that the size of celery worker container exceeds 1 GB and with enabled autoscalig it takes around 5 minutes to create new task in ECS service, to build and deploy the container. It is not a problen when deploying whole application but it is probmematic when I want to autoscale my app and I need to wait 5 minutes for new task so celery can run another tasks. Concurrency is set up to 3 and I cannot put higher number because my tasks are heavy and last around an hour (each). How can I optimize the size of celery Dockerfile and the way in is being built and deployed on ECS? Dockerfile for Django: FROM python:3.9-slim ENV DockerHOME=/home/app/web ENV GitHubToken=ghp_*** RUN mkdir -p $DockerHOME WORKDIR $DockerHOME ENV PYTHONDONTWRITEBYTECODE 1 ENV PYTHONUNBUFFERED 1 RUN pip install --upgrade pip COPY . $DockerHOME RUN apt-get update && apt-get install -y git RUN pip install git+https://github.com/ByteInternet/pip-install-privates.git@master#egg=pip-install-privates # … -
My Home page doesn't work in Django and react app
I am working on a project with Django and React and I have already deployed it in Render but my Home page doesn't work. The screen is all white. The others pages work correctly. This is my urls.py in core: urlpatterns = [ path('auth/', include('djoser.urls')), path('auth/', include('djoser.urls.jwt')), path('auth/', include('djoser.social.urls')), path('api/blog/', include('apps.blog.urls')), path('api/category/', include('apps.category.urls')), path('api/contacts/', include('apps.contacts.urls')), path('ckeditor/', include('ckeditor_uploader.urls')), path('admin/', admin.site.urls), ] + static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT) urlpatterns += [re_path(r'^.*', TemplateView.as_view(template_name='index.html'))] And this is my Home route in React: <Route path="/" element={<Home />} /> I have tried everything including Chat GPT but I can't find the error. When I was working on debug mode the Home page worked correctly. -
Permission denied for urls paths Django + Apache + mod_wsgi
I have configured a Dajgno application to be hosted in an Apache server using mod_wsgi. I have successfuly opened the home page, but haven't been able to open others urls paths. For instance, if I try to access /pop/, it returns 403 forbidden error. Here are my code: urls.py from django.contrib import admin from django.urls import path, include from dashboard import views from django.contrib.staticfiles.urls import staticfiles_urlpatterns urlpatterns = [ path('admin/', admin.site.urls), path('', views.NewView.as_view()), path('pop', views.PopView.as_view()), ] urlpatterns += staticfiles_urlpatterns() wsgi.py import os import sys from django.core.wsgi import get_wsgi_application path = '/home/andremou/DashboardUnicamp/unicamp/unicamp' if path not in sys.path: sys.path.append(path) #os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'unicamp.settings') os.environ["DJANGO_SETTINGS_MODULE"] = "unicamp.settings" application = get_wsgi_application() .conf file <VirtualHost *:443> ServerAdmin [CENSORED] DocumentRoot [CENSORED] #ServerName [CENSORED] ServerName [CENSORED] #ServerAlias [CENSORED] ServerAlias [CENSORED] RewriteEngine On RewriteCond [CENSORED] RewriteCond [CENSORED] RewriteRule [CENSORED] Alias /dashboardteste/ /home/andremou/DashboardUnicamp/unicamp/unicamp/ # Executar o Django como usuario apache SuexecUserGroup apache apache #Header set X-Frame-Options SAMEORIGIN <Directory /home/andremou/DashboardUnicamp/unicamp/unicamp> <Files wsgi.py> Order deny,allow Allow from all Require all granted </Files> </Directory> # Certificados TLS/SSL SSLEngine on SSLCertificateFile /etc/httpd/conf.d/ssl/moodle.pem SSLCertificateKeyFile /etc/httpd/conf.d/ssl/moodle.key SSLCertificateChainFile /etc/httpd/conf.d/ssl/moodle_chain.crt WSGIScriptAlias /dashboardteste /home/andremou/DashboardUnicamp/unicamp/unicamp/wsgi.py WSGIDaemonProcess unicamp python-home=/home/andremou/DashboardUnicamp/my_env python-path=/home/andremou/DashboardUnicamp/unicamp WSGIProcessGroup unicamp WSGIApplicationGroup %{GLOBAL} </VirtualHost> The structure of my files: home |-andremou |-DashboardUnicamp |-my_env |-unicamp ||-dashboard | |-migrations | |-static | |-templates … -
django dynamic URL routing
so i have been trying to use single template to display multiple content for different pages in django. i have an main app called websiteappand main template as index.html if i click a link in main page it goes to another app called moviedetailthat contains a template called movie-detail. html from that template i want to display various content according to the link clicked in main page i have been trying so long i didn't find any answer what do i need to change and how i have tried int:pk and objects.get(id=pk) it doesn't work -
how can i bookmark songs in my django project with rest framework and js
I've been trying to put the favorites feature for days with django rest framework and javascript api fetch in my lyrics project but without success all the methods I'm trying don't work please help me I'm a beginner in javascript, even in api with django too. here is what I tried, where did I mow apiviews.py from rest_framework.views import APIView from rest_framework.response import Response from rest_framework import status,permissions from rest_framework.viewsets import ModelViewSet from rest_framework.viewsets import ReadOnlyModelViewSet from rest_framework.permissions import IsAuthenticated from rest_framework import generics from rest_framework.response import Response from rest_framework import viewsets, status from rest_framework.decorators import action from .serializers import SongSerializer from .models import Song, User from .models import Song, Favorite class FavoritesongView(APIView): serializer_class = SongSerializer queryset = Song.objects.all() @action(detail=True, methods=['post'], permission_classes=[IsAuthenticated]) def favorite(self, request, id): song = self.get_object() user = request.user if user not in song.favorited_by.all(): song.favorited_by.add(user) song.save() return Response({'status': 'favorited'}) @favorite.mapping.delete def unfavorite(self, request, id=None): song = self.get_object() user = request.user if user in song.favorited_by.all(): song.favorited_by.remove(user) song.save() return Response({'status': 'unfavorited'}) api_urls from django.contrib import admin from django.urls import path from favorites.apiViews import FavoritesongView urlpatterns = [ path('songs/<int:id>/favorite/', FavoritesongView.as_view()) ] Js file function addToFavorites(songId) { fetch(`/api/songs/${songId}/favorite/`, { method: 'POST', headers: { 'Content-Type': 'application/json', 'Authorization': `Bearer ${localStorage.getItem('token')}` } }) .then(response … -
HTMX tags not activating when using locally-stored copy of source code in Django project
I have a Django project where I'm using HTMX to set up "cascading" SELECT widgets (i.e. the options listed in SELECT #2 are modified based on the user option from SELECT #1). I've confirmed that the HTMX tags in SELECT #1 are triggering as expected when I put this line in the HTML template header to pull in the HTMX code from their web site: <script src="https://unpkg.com/htmx.org@1.9.2" integrity="sha384-L6OqL9pRWyyFU3+/bjdSri+iIphTN/bvYyM37tICVyOJkWZLpP2vGn6VUEXgzg6h" crossorigin="anonymous"></script> Specifically, I can confirm the event is triggering because at this point the corresponding view for the target (create_itemid_2) is just a stub, and I see the printed message in my Powershell console. def create_itemid_2(request): print('HTMX event fired') context = {} return render(request,'create_itemid_2.html',context) So now I want to pull down the code, and use it locally in my Django project, so I'm not dependent on the external resource. The problem is, after I've done that, the event never triggers. I can even see the js file being successfully retrieved in my console (HTTP status 200, then 304 after that), but still the event never triggers. [14/Jun/2023 08:05:05] "GET /newitemid/ HTTP/1.1" 200 1652 [14/Jun/2023 08:05:05] "GET /static/htmx/htmx.min.js HTTP/1.1" 200 361101 [14/Jun/2023 08:09:50] "GET / HTTP/1.1" 200 515 [14/Jun/2023 08:09:52] "GET /newitemid/ HTTP/1.1" …