Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
{{Peoples}} django template is not rendering my backend data in html page
enter image description hereenter image description here (https://i.stack.imgur.com/dXn0b.png) in my views.py I have written function with dictionary in it u can see in image which is in my html page I have written code of html and pass the variable of django with {{peoples}} but it is not rendering in my live server and I have attached all of my code images -
Includes HTML template, not rendering Django content
I have created a special offers page which is meant to form as a carousel. I have created this HTML file in my products/templates/products/includes/special_offers.html folder. I have then added {% include products/includes/special_offers.html %} on the appropriate page. When I vew that page, everything before my for loop is appearing. I cannot get content within the for loop to appear and I have no idea why. I'm using a similar for loop on my products page already and it's working fine. I must be missing some piece of the puzzle. I've tried remove most of the HTML and just render a product image but no joy. Anyone able to spot anything? I've tested quite a bit to no avail. What would cause code that works on 1 page, but not on the other page? HTML {% load static %} {% block content %} <section class="container"> <hr> <h2 class="sub-title">Special Offers</h2> <div class="container my-5"> <div class="row"> <div class="col-12 m-auto"> <div class="owl-carousel owl-theme"> {% for product in products %} <p>HELLO</p> <div class="card card-owl h-100 border-0"> {% if product.image %} <a href="{% url 'product_detail' product.id %}"> <img class="card-img-top img-fluid w-75 product-img" src="{{ product.image.url }}" alt="{{ product.name }} Image"> </a> {% else %} <a href="{% url … -
__init__() got an unexpected keyword argument 'id'
It's my first time asking question here :) I'm a beginner with Django and I've been stuck on my edit_booking method for days, I don't even know what I'm doing wrong anymore... I'm making a booking system and I'm getting a "TypeError at /edit-booking/6 __init__() got an unexpected keyword argument 'id'". I've been trying a lot of things to make editing the exact booking possible, but they only cause more errors... Views: class EditBooking(DetailView): def __init__(self): template_name = 'edit-profile.html' initial = {} @login_required def edit_booking(request, id): booking = get_object_or_404(Booking, id=id) if request.method == 'POST': form = BookingForm(request.POST, instance=booking) customer_data = UserProfile.objects.all() if form.is_valid(): instance = form.save(commit=False) instance.customer_data = customer_data instance.save() messages.success(request, 'Thank you! Your booking has been updated!') else: return messages.error(request, form.errors) else: form = BookingForm(initial={ 'booking_date': booking.booking_date, 'booking_time': booking.booking_time, 'table_size': booking.table_size, 'additional_info': booking.additional_info, }) return render(request, template_name, {'form': form}) Templates: profile.html button triggering edit page: <a href="{% url 'editbooking' id=booking.id %}" aria-label="edit booking"> <button type="button" class="btn btn-secondary btn-brown px-5">Edit</button> </a> edit_booking.html: <form method="POST" action="{% url 'editbooking' id=booking.id %}" class="col-6"> {% csrf_token %} {% crispy form %} </form> Urls: path('edit-booking/<int:id>', views.EditBooking, name='editbooking'), Models: class Booking(models.Model): booking_customer = models.ForeignKey(UserProfile, on_delete=models.CASCADE, null=True) booking_date = models.DateField(default=datetime.date.today) booking_time = models.CharField(choices=TIME_SLOTS, default='8:00 - 8:30', max_length=50) … -
Troubleshooting ReactJS Display Issue with MediaPipe-Django API Integration for Exercise Rep Calculation Web App
I'm currently developing a web application that utilizes MediaPipe for calculating exercise repetitions. The backend is implemented using Django, which communicates with the frontend written in ReactJS via an API. However, I've encountered an issue where ReactJS seems unable to process the frames being sent by Django through the API. As a result, the exercise interface isn't displaying anything at all, making it impossible to view or interact with the exercise calculation functionality. How can I troubleshoot and resolve this problem to ensure that ReactJS properly handles the frames received from Django via the API, allowing the exercise interface to display as intended? In attempting to resolve the issue of ReactJS not processing frames sent by Django through the API, I initially checked for any potential errors in the data transfer between the backend and frontend. I reviewed the API endpoints, the data format being sent, and ensured that the communication between Django and ReactJS was properly established. -
Gunicorn file for Django project gunicorn.service keep getting Permission denied
Hello I am currently practicing Linux and Django project using Gunicorn and Nginx on CentOS. I'm testing my server on AWS Lightsail and here's some info of what I'm using for this practice. CS9-20230110 Python 3.9 Django 4.0.2 Nginx 1.22.1 Gunicorn 21.2.0 The test of opening the server by opening a gunicorn socket and port 8000 with Gunicorn was successful. I had no trouble in here. gunicorn --bind 0:8000 mysite.wsgi:application gunicorn --bind unix:/home/ec2-user/Django/venv/gunicorn.sock config.wsgi:application (I put sock file into my venv directory, thinking this could've be the problem (sadly it wasn't)) But when I try to start Gunicorn service on systemd. The system send permission denied message on gunicorn file. So I set every single files UID and GID to my user account and group and set 775 authorization on most files. It didn't work at all. I have no clue what I'm missing now. Just thinking that I made a mistake and the mess is everywhere now. Please someone tell me what's going on here. Directory Tree # /home/ec2-user/Django Django ├── Django_Project │ ├── db.sqlite3 │ ├── manage.py │ ├── mysite │ │ ├── asgi.py │ │ ├── db.sqlite3 │ │ ├── __init__.py │ │ ├── __pycache__ │ │ … -
Trying to send Emails in models.py to members in django 4.2
I'm trying to send an email to people when 3 or fewer days are remain, I'm using Django, this is the models.py in my main app, I want to automatically send emails when 3 days or less remain I'm using 4.2 from django.db import models from django.contrib.auth.models import User import uuid from django.urls import reverse from datetime import date from django.conf import settings from django.core.mail import send_mail # Create your models here. class sub(models.Model): id = models.UUIDField(default=uuid.uuid4, primary_key = True, editable = False) provider = models.CharField(max_length=70) tier = models.CharField(max_length=40) date_started = models.DateField(auto_now=False, auto_now_add=False) date_end = models.DateField(auto_now=False, auto_now_add=False, ) author = models.ForeignKey(User, on_delete=models.CASCADE) def remain(self): today = date.today() remaining_days = (self.date_end - today).days return(remaining_days) def get_absolute_url(self):` return reverse('sub-detail', kwargs={'pk':self.id}) trying to send emails to people -
fcm-django push notifications to mobile app messages is falling
I'm new with Firebase. The problem is that the sending of messages is falling. I suspect this is due to lack of Firebase authentication. So, what I did: I created new Firebase project and turn on an Anonymous authentication on project settings. On the backend side I installed fcm-django, add settings, and make migrations. Settings: # Firebase app certificate = json.loads(config('FIREBASE_CREDENTIALS', default='')) cred = credentials.Certificate(certificate) FIREBASE_APP = firebase_admin.initialize_app(cred) FCM_DJANGO_SETTINGS = { "DEFAULT_FIREBASE_APP": FIREBASE_APP, "APP_VERBOSE_NAME": ("FCM Brokers CRM notifications"), "ONE_DEVICE_PER_USER": False, "DELETE_INACTIVE_DEVICES": False, } Add standard route from this library: router = DefaultRouter() router.register('devices', FCMDeviceAuthorizedViewSet) path('', include(router.urls)), I call post device/ endpoint with my drf auth user, and send only registration_id (firebase token). Is it enough? So I see in database id of user from AUTH_USER_MODEL: I have simple test endpoint with code: from firebase_admin.messaging import Message, Notification ... devices = FCMDevice.objects.filter(user=request.user) from device in devices: device.send_message(Message( notification=Notification(title="title", body="text"), topic="Optional topic parameter: Whatever you want", )) And I call it from my android app. But its fall with error: I really desperate and don't know what to do. Do I have to somehow add another user and connect it to the endpoint call? Or I have to match the android app … -
Django Template not displaying model objects
` class BookView(CreateView): model = Booking fields = 'all' success_url = "/customer/" template_name = 'book.html' class CustomerBook(View): template_name = 'customer_booking.html' def get(self, request, *args, **kwargs): return render(request, self.template_name) def post(self, request, *args, **kwargs): first_name = request.POST.get('first_name') last_name = request.POST.get('last_name') guest_number = request.POST.get('guest_number') comment = request.POST.get('comment') booking_data = get_object_or_404(Booking, first_name=first_name, last_name=last_name, guest_number=guest_number, comment=comment ) print(booking_data) #context = {"bookers": booking_data} return render(request, self.template_name , {"bookers": booking_data}) class Booking(models.Model): first_name = models.CharField(max_length=200) last_name = models.CharField(max_length=200) guest_number = models.IntegerField() comment = models.CharField(max_length=1000) def __str__(self): return self.first_name + ' ' + self.last_name class Menu(models.Model): name = models.CharField(max_length=200) price = models.IntegerField() discription = models.TextField(max_length=1000, default='') def __str__(self): return self.name` urlpatterns = [ path('book/', BookView.as_view(), name="book"), path('customer/', CustomerBook.as_view(), name="customer"),] urlpatterns = [ path('book/', BookView.as_view(), name="book"), path('customer/', CustomerBook.as_view(), name="customer"),] I have tried making the model objects display with different code but to no avail. I want to return customer's booking details on the browser after booking. -
Django custom middleware get Anonymous user even after sending authenticated request
I have implemented the custom middleware in which I wanted to have logged in user. But I'm getting AnonymousUser in request.user For authentication method, I have implemented JWT Authentication using django-rest-framework-simplejwt library. Settings.py REST_FRAMEWORK = { 'DEFAULT_AUTHENTICATION_CLASSES': ( 'rest_framework_simplejwt.authentication.JWTAuthentication', ) } MIDDLEWARE = [ 'django.middleware.security.SecurityMiddleware', 'django.contrib.sessions.middleware.SessionMiddleware', 'django.middleware.common.CommonMiddleware', 'django.middleware.csrf.CsrfViewMiddleware', 'django.contrib.auth.middleware.AuthenticationMiddleware', 'django.contrib.messages.middleware.MessageMiddleware', 'django.middleware.clickjacking.XFrameOptionsMiddleware', 'core.middleware.ReverseProxyMiddleware', ] custom_middleware.py class ReverseProxyMiddleware(MiddlewareMixin): def __init__(self, get_response): self.get_response = get_response def process_request(self, request): print(request.user.is_authenticated) for each_path in settings.BY_PASS_URLS: if each_path in request.path: response = self.get_response(request) return response if self.check_permission(request): response = self.get_response(request) return response else: return HttpResponseForbidden("Permission denied") def check_permission(self, request): perm = APICheckPermission() return perm.has_permission(request) logs 2023-12-09 17:43:34 False AnonymousUser 2023-12-09 17:43:34 Forbidden: /some_url 2023-12-09 17:43:34 [09/Dec/2023 17:43:34] "GET /some_url HTTP/1.1" 403 17 Response Permission denied -
How to fix No ":" found in value with Django core signing
I have a django rest framework api where a i create a token using the django.core.signing module. The signing and unsigning of object works fine when using an API Clinet (E.g) Postman. But when i try to connect with my Next Js frontend using axios it get. No ":" found in value for the token eyJlbWFpbCI6InJhbW9ucmFzaDJAZ21haWwuY29tIiwiZmlyc3RfbmFtZSI6IlJhc2hlZWQiLCJsYXN0X25hbWUiOiJSYW1vbiIsInBhc3N3b3JkIjoiTmluaW9sYTEyIiwiYWN0aXZhdGlvbl9jb2RlIjoiNzk3ODY5In0%3A1rBvFl%3Ato5l_EAmsHy76eJt0sHDcO_eqlk0k4fho78czQeNVx4. But the acutal token is eyJlbWFpbCI6InJhbW9ucmFzaDJAZ21haWwuY29tIiwiZmlyc3RfbmFtZSI6IlJhc2hlZWQiLCJsYXN0X25hbWUiOiJSYW1vbiIsInBhc3N3b3JkIjoiTmluaW9sYTEyIiwiYWN0aXZhdGlvbl9jb2RlIjoiNzk3ODY5In0:1rBvFl:to5l_EAmsHy76eJt0sHDcO_eqlk0k4fho78czQeNVx4 This is the API Code def create(self, request, *args, **kwargs): activation_token = request.data.get("activation_token") activation_code = request.data.get("activation_code") print(activation_token) try: data = signer.unsign_object( activation_token, max_age=timedelta(minutes=10)) except Exception as e: print(e) return Response({"message": "OTP has expired! Try registering again."}, status=status.HTTP_400_BAD_REQUEST) if data["activation_code"] == activation_code: user = User.objects.create_user( email=data["email"], password=data["password"], first_name=data["first_name"], last_name=data["last_name"]) serializer = UserSerializer(user, many=False) return Response(serializer.data, status=status.HTTP_201_CREATED) else: return Response({"message": "Invalid OTP"}, status=status.HTTP_400_BAD_REQUEST) And The Axios Code const response = await axios.post( `${BASEURL}auth/users/activate/`, JSON.stringify({ activation_code: values.otp, activation_token: token, }), { headers: { Accept: "*/*", "Content-Type": "application/json", }, } ); -
line 158, in get_app_config return self.app_configs[app_label] KeyError: 'account'
I am developing a django project, the main directory/project name is django-basic-ecommerce. One of the apps name is accounts (note that it has the final "s"). as I run python manage.py makemigrations I get Traceback (most recent call last): File "/my/path/basic-django-ecommerce/venv/lib/python3.10/site-packages/django/apps/registry.py", line 158, in get_app_config return self.app_configs[app_label] KeyError: 'account' During handling of the above exception, another exception occurred: [...] /my/path/basic-django-ecommerce/venv/lib/python3.10/site-packages/django/apps/registry.py", line 165, in get_app_config raise LookupError(message) LookupError: No installed app with label 'account'. During handling of the above exception, another exception occurred: [...] /my/path/basic-django-ecommerce/venv/lib/python3.10/site-packages/django/contrib/auth/__init__.py", line 176, in get_user_model raise ImproperlyConfigured(django.core.exceptions.ImproperlyConfigured: AUTH_USER_MODEL refers to model 'account.User' that has not been installed The last message makes me think that I missed some configurations for account.User, however, it is correctly installed in mainapp_ecommerce/settings.py INSTALLED_APPS = [ ... 'accounts', ... 'django.contrib.auth', ... ] AUTH_USER_MODEL = 'account.User' # it changes the builtin model user to User custom defined model and about that AUTH_USER_MODEL , it refers to the account.User modeldefined in accounts/models.py as class User(AbstractBaseUser): email = models.EmailField(max_length=255, unique=True) # full_name = models.CharField(max_length=255, blank=True, null=True) active = models.BooleanField(default=True) # is h* allowed to login? staff = models.BooleanField(default=False) # staff user, not superuser admin = models.BooleanField(default=False) # superuser timestamp = models.DateTimeField(auto_now_add=True) # superuser USERNAME_FIELD = 'username' … -
Difficulty Sending List of Working Hours as Multipart Data Using Swagger in Django DRF
I'm currently facing an issue when attempting to send data in the correct format using Swagger in Django Rest Framework (DRF). The specific challenge is with sending a list of working hours as multipart data. Below is a simplified version of my code: # models.py class Facility(models.Model): name = models.CharField(max_length=255) # ... other fields class WorkingHours(models.Model): linkedFacility = models.ForeignKey(Facility, on_delete=models.CASCADE, related_name='workingHours') dayOfWeek = models.IntegerField(validators=[MinValueValidator(1), MaxValueValidator(7)]) startTime = models.TimeField() endTime = models.TimeField() # serializers.py class WorkingHoursSerializer(serializers.ModelSerializer): class Meta: model = WorkingHours fields = ('dayOfWeek', 'startTime', 'endTime') class FacilitySerializer(serializers.ModelSerializer): workingHours = WorkingHoursSerializer(many=True, read_only=True) class Meta: model = Facility fields = ('id', 'name', 'workingHours') curl -X 'POST' \ 'http://127.0.0.1:8000/api/v1/facilities/' \ -H 'accept: application/json' \ -H 'Content-Type: multipart/form-data' \ -H 'X-CSRFTOKEN: ot91cIAOrwhjDMU0LtAFhAce1vVxODO5JVQqTRrFumPjyHImS6e0dHqDqseqMbVI' \ -F 'name=first' \ -F 'price=300' \ -F 'phoneNumber=+3821312231213' \ -F 'coordinates=POINT(44.7866 20.4489)' \ -F 'uploadImages=@1.jpeg;type=image/jpeg' \ -F 'uploadSearchImage=@2.jpeg;type=image/jpeg' \ -F 'workingHours={ "dayOfWeek": 7, "startTime": "string", "endTime": "string" },{ "dayOfWeek": 6, "startTime": "string", "endTime": "string" }' In Swagger (I'm using drf-spectacular), when attempting to send a POST request to create a new Facility along with a list of related WorkingHours, the format of the request data appears to be causing issues. Specifically, the Swagger interface is struggling to handle the correct format … -
How to pass self.request data in django form?
I want to pass self.request data in the form class. I can access it in View, but unable to access it in form class. class AttendanceCreateView(LoginRequiredMixin, CreateView): model = Attendance template_name = 'attendance/attendances_new.html' form_class = AttendanceForm def get_initial(self): initial = super().get_initial() initial['class_name'] = self.request.GET.get('class', '') return initial My Form class: class AttendanceForm(forms.ModelForm): class_name = forms.ChoiceField(choices=CLASS_NAMES, disabled=True) teacher = forms.ModelMultipleChoiceField( queryset=Teacher.objects.all().order_by('id')) subject_name = forms.ChoiceField(choices=[]) total_students = forms.IntegerField(initial=0) unique_code = forms.IntegerField(initial=0) class Meta: model = Attendance fields = ['class_name', 'teacher', 'subject_name', 'total_students', 'unique_code'] def __init__(self, *args, **kwargs): super(AttendanceForm, self).__init__(*args, **kwargs) # This I need to be done # if self.request.GET.get('class', '') = 'class1': # self.fields['subject_name'].choices = MY_CHOICES_1 # elif self.request.GET.get('class', '') = 'class2': # self.fields['subject_name'].choices = MY_CHOICES_2 I want to set subject_name choices according to the request values passed. For class 1, I want different subject choices., and for class 2, different subject choices etc. So getting request data is important. Is there any way to set the initial choice in direct View like I did for class_name? Or any suggestions on how to do it in form? -
Generic Delete view
I have a model for booking table that has a onetoone relation with another model table. And i want to be able to change the value of a field of table before deleting the model booking. Here is my BookingTable model... class BookingTable(models.Model): table = models.OneToOneField(Table, on_delete=models.CASCADE) user = models.OneToOneField(get_user_model(), on_delete=models.CASCADE) time = models.TimeField(auto_now_add=True) def __str__(self) -> str: return self.user.get_username() + " - " + self.table.name def get_absolute_url(self): return reverse("list_tables") Here is my Table model... class Table(models.Model): name = models.CharField(max_length=100, unique=True) ocupation_status = models.BooleanField(default=False) size = models.PositiveIntegerField() image = models.ImageField(upload_to='static/media/images/', default='static/media/images/default.jfif') description = models.TextField(null=False, blank=False, default="This is a very beatiful table") def __str__(self) -> str: return self.name[:50] def get_absolute_url(self): return reverse("list_tables") And here is my view class CancelBookingView(DeleteView): model = BookingTable template_name = 'cancel_booking.html' success_url = reverse_lazy('list_tables') def form_valid(self, form): form.instance.table.ocupation_status = False return super().form_valid(form) I tried to use form_valid and accessing the table field using the instance attr but it gave an error saying that form has no attr instance. class CancelBookingView(DeleteView): model = BookingTable template_name = 'cancel_booking.html' success_url = reverse_lazy('list_tables') def form_valid(self, form): form.instance.table.ocupation_status = False return super().form_valid(form) -
Button style in Django
The button should be a small vertical rectangle and the top width should stick out a little. It should also be white before pressing and crimson after pressing. And when the pointer goes over this button, the text "Add" and when deleting, "Remove" should be displayed. However, it's just a rectangle, and even its name doesn't change from addition to deletion (the color and style don't change either). Thank you in advance for your ideas:) product_detail.html: <form method= "get" action = "{% url 'add' product.id %}"> {% csrf_token %} <button clasa="bottonwatch" type = "submit" value = "{{ product.id }}" name = "productid"> <div class="addwatch"> {% if product.watch_list %} addWatchlist </div> <div class="removewatch"> {% else%} remove </div> {% endif %} </button> </form> Style: .bottonwatch { border-radius: 50%; height: 2.5rem; min-width: auto; padding: 0; width: 2.5rem; } .addwatch { color: black; background-color: white; } .remove{ color: white; background-color: rgb(100, 36, 36); } views.py: @login_required(login_url="login") def add(request, productid): product_id = request.GET.get('productid', False) watch = Watchlist.objects.filter(user = request.user.username) for items in watch: if (items.watch_list.all) == int(productid): return watchlist(request, request.user.username) else: return remove(request, productid) new_watch = Watchlist(product_id, user=request.user.username) new_watch.save() messages.success(request, "The product has been added to your WatchList.") return product_detail(request, productid) @login_required(login_url="login") def remove(request, pid): … -
Making a common DB for one app across multiple django projects
I have 3 distinct Django projects (or instances) running on the same Ubuntu server (for the same user) in different folders. Lets call these instances (D1, D2, D3). All the 3 projects use sqlite3 as DB. All the 3 projects aside from their inherent differences also have a single common django Model called "Word" (that is basically responsible for storing word images). there can be millions of entries for word model for each of the django projects at any given time. The problem I am encountering is that I need to frequently transfer the word instances from one project to another. the Volume of the words to be transferred is huge (millions of word model instances per day). My current solution is very inefficient, what I am doing is to export all the word entries from D1 project to a single folder and import all the entries from the folder to D2 project. Is there any way to make a common database that all the 3 projects can access for the "Word" model? this will make life much easier where to transfer the words from D1 to D2, I would just have to change a field (probably belongs_to) in all … -
run thread immediately after runserver in docker django
i want to run a thread in my django project after runserver and everything in local deployment is OK: scraper/apps.py: from django.apps import AppConfig import threading class ScraperConfig(AppConfig): default_auto_field = 'django.db.models.BigAutoField' name = 'scraper' def ready(self): from .functions import start_scraper threading.Thread(target=start_scraper).start() But in docker deployment the server not runs until this thread done complete! this is my Dockerfile: FROM python:3.8 ENV PYTHONDONTWRITTEBYTEBYTECODE=1 ENV PYTHONUNBUFFERED=1 RUN mkdir -p /app WORKDIR /app COPY ./core . RUN pip3 install pip --upgrade RUN pip3 install -r requirements.txt CMD yes yes | python3 manage.py makemigrations && \ python3 manage.py migrate && \ yes yes | python3 manage.py collectstatic && \ python3 manage.py create_superuser && \ python3 manage.py runserver 0.0.0.0:${SCRAPER_OUTER_PORT} it is so amazing that I can run this thread as a request in an endpoint of a rest api in this server without any problem. But I want to run this auotomaticaly , immediately after runserver I think problem is from Dockerfile configs. thanks for your responses and solutions before I tried this methods: python:3.8-slim-buster image ubuntu:20.04 image run server with gunicorn run server with asgi application run all CMD as an init.sh file and make executable it(chmod +x) before all of them not solved … -
How to save vue3openlayer coords to Django SRID4326
I am trying to make markers in my OpenStreetMap. Currently one building in the Bangkok when I use Django coordinate it shows. "SRID=4326;MULTIPOINT (100.53007692708017 13.721325314629256)" Then I make my own Vue3 to be a marker. My function to get the coordinates is template <ol-map :loadTilesWhileAnimating="true" :loadTilesWhileInteracting="true" style="height: 400px" @click="handleMapClick" > <ol-view ref="view" :center="center" :rotation="rotation" :zoom="zoom" :projection="projection" /> <ol-tile-layer> <ol-source-osm/> </ol-tile-layer> </ol-map> script import { fromLonLat, toLonLat } from 'ol/proj'; // Import fromLonLat and toLonLat const convertToSRID4326 = (coordinates) => { const latitude = coordinates[0]; const longitude = coordinates[1]; const latitudeInDegrees = latitude * (180 / Math.PI); const longitudeInDegrees = longitude * (180 / Math.PI); return { latitude: latitudeInDegrees, longitude: longitudeInDegrees }; } const handleMapClick = (event) => { const clickedCoords = toLonLat(event.coordinate); markers.value.push(clickedCoords) markers.value.forEach(element => { console.log(element) console.log(convertToSRID4326(element)) }) } My widget: {0: 0.0009030769278815491, 1: 0.00012325954951108997} My conversion: latitude: 0.05174249654325298 longitude: 0.007062251971669265 But Django is: "SRID=4326;MULTIPOINT (100.53007692708017 13.721325314629256)" Goal: Vue3 be able to use same SRID:4326 as Django. -
Django linking to generic.DetailView page but page contents is the same as the generic.ListView page
I've encountered an issue where I've created a list view and each item in it has a detail view. When I click the item in the list view, the link in the searchbar changes from http://127.0.0.1:8000/catalog/articles/ to http://127.0.0.1:8000/catalog/articles/[UUID], but the actual page contents does not change. Even though I am supposedly in the detail view and I have a detail view html file, the displayed contents is still the list view. articles.html: {% extends 'head.html' %} {% load static %} {% block content %} <h1 class="flex items-center justify-center text-6xl">Articles</h1> <br> {% if articles %} <div class="flex items-center justify-center"> <div class="posts"> {% for article in articles reversed %} <a href="{{ article.get_absolute_url }}"> <div class="article_box"> <img src="{{ article.article_cover_image.url }}" alt="img"> <div class="article_box_sub"> <div>{{ article.article_title }}</div> <div class="text-xs">{{ article.article_date_and_time }} UTC</div> <div class="text-xs"> Written by {% for author in article.article_author.all %} {% if not forloop.last and forloop.revcounter0 > 1 %} <span class="link_light">{{author}}</span>, {% elif forloop.revcounter0 == 0 and forloop.counter0 > 0 %} and <span class="link_light">{{author}}</span> {% elif forloop.revcounter0 == 1 and forloop.counter0 > 1 %} <span class="link_light">{{author}}</span>, {% else %} <span class="link_light">{{author}}</span> {% endif %} {% endfor %} </div> <div> {% for tag in article.article_tags.all %} <div class="tag text-xs">{{tag}}</div> {% endfor %} <div … -
Django ModelFormSets: display each model object along with a field value in a form
This is something that I thought would be easy, but I haven't figured it out yet. I have a simple model called Channel. Here it is: class Channel(models.Model): id = models.PositiveBigIntegerField(primary_key=True) name = models.CharField(max_length=100) disabled = models.BooleanField(default=False) I want the user to be able to see all of the channels, displayed by name, and select which ones to disable or enable. I've gotten close, here's my view (simplified): def channel_setup(request): ChannelFormSet = modelformset_factory( models.Channel, fields=['disabled'], edit_only=True ) formset = ChannelFormSet() context = { 'formset': formset } return render(request, "channel_setup.html", context) What it does is display a checkbox for every single channel in the database. Perfect! The problem is that all of them are labeled "Disabled:", so there's no way to discern which channel is which. I'd like to display each channel by name next to each checkbox. I know there's a way to change the label, but I haven't figured out how to set the label equal to the Channel's name field value. I could probably do some hacky magic with javascript to make it happen but there has got to be a way to just do this with Django, right? -
Django script can't save to database
I'm working on a Django project that has 3 models: class Player(models.Model): nickname = models.CharField(max_length=255) profile_image = models.URLField(null=True, blank=True) class Game(models.Model): players = models.ManyToManyField(Player, related_name='players') winner = models.ForeignKey(Player, on_delete=models.SET_NULL, null=True, blank=True) class Stat(models.Model): player = models.ForeignKey(Player, on_delete=models.CASCADE) creation_date = models.DateTimeField(auto_now_add=True) score = models.PositiveIntegerField(null=True, blank=True) game = models.ForeignKey(Game, on_delete=models.CASCADE, null=True, blank=True) I've added a generate_data.py script to my app's management/commands/ folder to automatically create random data and add populate the database. The relevant part is this: class Command(BaseCommand): def handle(self, *args, **options): try: print(self.style.SUCCESS('Creating random data')) # generate Player data players = self.generate_random_players() for player in players: player_data = self.generate_random_player_data() player.nickname = player_data['nickname'] player.profile_image = player_data['profile_image'] player.save() # generate Game data game = Game() game.save() for player in players: game.players.add(player) winner = random.choice(players) game.winner = winner game.save() # generate Stat data for player in players: Stat.objects.create(player=player, creation_date=timezone.now(), score=random.randint(0, 100), game=game) print(self.style.SUCCESS('Successfully added')) except Exception as e: print(self.style.ERROR(f'An error occurred: {str(e)}')) There are also some methods to randomly create Players, but those seem to be working as expected. The thing is, when I run the script I always get An error occurred: "<Game: (ID: None). WINNER: No winner.>" needs to have a value for field "id" before this many-to-many relationship can be … -
How to use distinct in django? And help me Find the average of subjects so I can list the top 10 students per School year
marccamba Filipino 07 78.0 78.0 90.0 90.0 SY: 2021 to 2022 alasterpalacio Filipino 07 78.0 79.0 80.0 85.0 SY: 2021 to 2022 alasterpalacio English 07 78.0 78.0 78.0 78.0 SY: 2021 to 2022 marccamba English 07 78.0 79.0 79.0 76.0 SY: 2021 to 2022 denniscabahug Filipino 07 76.0 78.0 76.0 76.0 SY: 2021 to 2022 denniscabahug English 07 75.0 75.0 75.0 75.0 SY: 2021 to 2022 albertbroqueza English 07 75.0 75.0 75.0 75.0 SY: 2021 to 2022 marccamba Filipino 08 90.0 90.0 90.0 90.0 SY: 2022 to 2023 alasterpalacio Filipino 08 90.0 90.0 90.0 90.0 SY: 2022 to 2023 denniscabahug Filipino 08 89.0 89.0 89.0 89.0 SY: 2022 to 2023 marccamba English 08 89.0 89.0 89.0 89.0 SY: 2022 to 2023 I would like to get the average of the scores of english7, filipino7, of a all the students average_session1 = (subject1_session1, subject2_session1,...subjectN_session1)/N average_session2 = (subject1_session2, subject2_session2,...subjectN_session2)/N . . . average_sessionN = (subject1_sessionN, subject2_sessionN,...subjectN_sessionN/N -
Dockerized Mysql: ERROR 1045 (28000): Access denied for user 'root'@'localhost' (using password: YES)
I'm working on a Django project locally (on a virtual environment) where I have a Django folder (the one automatically by "startproject") called django-test. Within this folder I have a secrets.py file where I store sensitive data. So this file contains the following variables: mysql_root_password = 'my_root_password' mysql_database = 'my_db' mysql_user = 'my_user' mysql_password = 'my_password' I also have a docker-compose.yml file to bring up a mysql database: services: db: image: mysql:latest restart: always environment: MYSQL_DATABASE: /run/secrets/mysql_database MYSQL_USER: /run/secrets/mysql_user MYSQL_PASSWORD: /run/secrets/mysql_password MYSQL_ROOT_PASSWORD: /run/secrets/mysql_root_password secrets: - mysql_root_password - mysql_database - mysql_user - mysql_password ports: - '3306:3306' expose: - '3306' volumes: - my-db:/var/lib/mysql secrets: mysql_root_password: file: ./django-test/secrets.py mysql_database: file: ./django-test/secrets.py mysql_user: file: ./django-test/secrets.py mysql_password: file: ./django-test/secrets.py volumes: my-db: I was initially able to bring up the container (docker-compose up -d --build) and go into to mysql shell to create the database, the user and grant privileges, using docker exec -it mysql_container mysql -u root -p. However, I had to make some major modifications to my django model, which required to recreate the database. So I did: docker-compose down docker volume ls docker volume rm <my_volume_name> From that moment on I wasn't able to use my db again. I recreated my container (docker-compose … -
Django ManytoMany form with checkboxes: how to keep "checked" and "unchecked" values?
I'm trying to display and use a form that uses a manytomany field, widgetized as checkboxes The problem I'm having is when I view the page, the state of the checkboxes isn't visible (all the checkboxes show as unchecked, but there are related rows in the database for the manytomany relations). What I'd like to do is display an "edit" form with all the correct statuses for the checkboxes (i.e. checked checkboxes for existing manytomany values in the database, unchecked checkboxes for missing values) here's the form declaration: class EditPatientForm(forms.ModelForm): flags = forms.ModelMultipleChoiceField( queryset=PatientFlag.objects.filter(visible_on_edit=True), widget=forms.CheckboxSelectMultiple, required=False) class Meta: model = Patient exclude = ('profile_picture','registered_on') fields = "__all__" helper = FormHelper() Every "patient" has some associated "flags" such as "has diabetes" or "has heart problems". I want to display a form with a list of checkboxes so the user can select "has diabetes" as a checkbox, which then gets saved in the database. Here are the two models: class PatientFlag(models.Model): name = models.CharField(max_length=255, null=True) question = models.CharField(max_length=255, null=True) description = models.TextField(null=True) visible_on_create = models.BooleanField( default=True) visible_on_edit = models.BooleanField(default=True) class Patient(models.Model): """Represents a patient""" first_name = models.CharField(max_length=255) last_name = models.CharField(max_length=255) flags = models.ManyToManyField(PatientFlag, db_index=True, related_name='patient') Now, when I go and edit the … -
I cant install and use pipenv to create a virtual environment
pip install pipenv Requirement already satisfied: pipenv in c:\users\user\appdata\roaming\python\python312\site-packages (2023.11.15) Requirement already satisfied: certifi in c:\users\user\appdata\roaming\python\python312\site-packages (from pipenv) (2023.11.17) Requirement already satisfied: setuptools>=67 in c:\users\user\appdata\roaming\python\python312\site-packages (from pipenv) (69.0.2) Requirement already satisfied: virtualenv>=20.24.2 in c:\users\user\appdata\roaming\python\python312\site-packages (from pipenv) (20.25.0) Requirement already satisfied: distlib<1,>=0.3.7 in c:\users\user\appdata\roaming\python\python312\site-packages (from virtualenv>=20.24.2->pipenv) (0.3.7) Requirement already satisfied: filelock<4,>=3.12.2 in c:\users\user\appdata\roaming\python\python312\site-packages (from virtualenv>=20.24.2->pipenv) (3.13.1) Requirement already satisfied: platformdirs<5,>=3.9.1 in c:\users\user\appdata\roaming\python\python312\site-packages (from virtualenv>=20.24.2->pipenv) (4.1.0) when I'm trying to install a got this answer pip install pipenv Requirement already satisfied: pipenv in c:\users\user\appdata\roaming\python\python312\site-packages (2023.11.15) Requirement already satisfied: certifi in c:\users\user\appdata\roaming\python\python312\site-packages (from pipenv) (2023.11.17) Requirement already satisfied: setuptools>=67 in c:\users\user\appdata\roaming\python\python312\site-packages (from pipenv) (69.0.2) Requirement already satisfied: virtualenv>=20.24.2 in c:\users\user\appdata\roaming\python\python312\site-packages (from pipenv) (20.25.0) Requirement already satisfied: distlib<1,>=0.3.7 in c:\users\user\appdata\roaming\python\python312\site-packages (from virtualenv>=20.24.2->pipenv) (0.3.7) Requirement already satisfied: filelock<4,>=3.12.2 in c:\users\user\appdata\roaming\python\python312\site-packages (from virtualenv>=20.24.2->pipenv) (3.13.1) Requirement already satisfied: platformdirs<5,>=3.9.1 in c:\users\user\appdata\roaming\python\python312\site-packages (from virtualenv>=20.24.2->pipenv) (4.1.0) I'm trying to get my path but nothing is working like these two tries PS C:\Users\USER> pipenv --venv Fatal error in launcher: Unable to create process using '"C:\Program Files\python.exe" "C:\Users\USER\AppData\Roaming\Python\Python312\Scripts\pipenv.exe" --venv': The system cannot find the file specified. PS C:\Users\USER> pipenv --where Fatal error in launcher: Unable to create process using '"C:\Program Files\python.exe" "C:\Users\USER\AppData\Roaming\Python\Python312\Scripts\pipenv.exe" --where': The system cannot find the file specified.