Django community: Django Q&A RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
SQL Query to combine alterative rows into a single table using Django's Models
I have created an attendance server that allows staffs to log their attendance. There is a manual and a automatic way of logging attendance. The SQL tables for the system is as follows. Staff Local User Device Biometrics Log Punch Log Id Id Id Id Id Name Name Location Local User ID Staff ID Device ID API Key Punched On Punched On Staff ID Is Disabled Anytime a biometrics log is added, if the local user in that log has a staff foreign key then a punch log gets created. I felt that this helps in combining automatic and manual logs. Manual Logs are added straight to Punch Log When the user is requesting for Attendance. This currently will take alterative rows of punch log that are active and combines it into a single row. Output Data Format Attendance Log Id Punch In Punch Out Staff ID CODE IN USE Currently I am using raw sql query to get the data The basic logic is to Split into two sub queries -> Punch In & Punch Out with Roll Number Unique to User Join with Roll Number select i.id, username, i.punched_on as punch_in, min(punch_out) as punch_out from (select *,row_number() over … -
Gunicorn is getting slow after project start or restart
I have deployed my django project on "Centos 7" OS with posgresql, nginx and gunicorn. After couple of minutes of project is running or restart, it's getting so slow. But there is no errors in the project or responses. It's for sure not db related issue. One thing to take into considiration that, my project gets quite big load gunicorn.service is given below: [Unit] Description=gunicorn daemon After=network.target [Service] User=user Group=nginx WorkingDirectory=/home/user/myproject ExecStart=/home/user/myproject/myprojectenv/bin/gunicorn --workers 3 --bind unix:/home/user/myproject/myproject.sock myproject.wsgi:application [Install] WantedBy=multi-user.target``` checked network, cpu load, db load. Everything is fine. No idea what is wrong -
Django: Why does my view writes 5 times to DB the last order?
I have a page with 5 forms and there is only 1 submit type button which is outside the selector in my template. When I click this button, it's the same as if I click the submit button 5 times for each form. So when I submit, I don't know why, but it writes to the DB 5 times the cleaned_data of the last form. Where is my issue? Thanks! My models.py: class Order(models.Model): date = models.DateField(unique=True, blank=True, null=True) first_course = models.CharField(null=True, blank=True, unique=False, max_length=30) first_course_quantity = models.IntegerField() second_course = models.CharField(null=True, blank=True, unique=False, max_length=30) second_course_quantity = models.IntegerField() dessert = models.CharField(null=True, blank=True, unique=False, max_length=30) dessert_quantity = models.IntegerField() drink = models.CharField(null=True, blank=True, unique=False, max_length=30) drink_quantity = models.IntegerField() def __str__(self): return f"Date of order: {self.date}" My forms.py: class DisabledOptionWidget(forms.Select): def render(self, name, value, attrs=None, renderer=None): html_code = super(DisabledOptionWidget, self).render(name, value, attrs, renderer) html_code = html_code.replace(f'<option value=""', f'<option value="" disabled') return html_code class OrderForm(forms.ModelForm): first_course = forms.ChoiceField(choices=[("", 'Select a dish')] + [(f"{item}", item) for item in list( Menu.objects.values_list("first_course", flat=True))], widget=DisabledOptionWidget, required=False) first_course_quantity = forms.IntegerField(min_value=0) second_course = forms.ChoiceField(choices=[("", 'Select a dish')] + [(f"{item}", item) for item in list( Menu.objects.values_list("second_course", flat=True))], widget=DisabledOptionWidget, required=False) second_course_quantity = forms.IntegerField(min_value=0) dessert = forms.ChoiceField(choices=[("", 'Select a dish')] + [(f"{item}", item) for … -
How can I resign Photo in Django Form
I am working a Django project where I want to reduce the image size to be less than 300kb and crop the images to be 1280px 820px. The aim is to make sure every image uploaded is the same irrespective of the initial so any best solution would be appreciated. Below is what I have tried but nothing works. ALLOWED_EXTENSIONS = ('.gif', '.jpg', '.jpeg') class PropertyForm(forms.ModelForm): description = forms.CharField(label='Property Description:', max_length=60, widget=forms.TextInput(attrs={'placeholder': 'Briefly Describe your Property. E.g. Bedroom & Palour with Private Detached Bathroom'})) state = forms.ChoiceField(choices=Property.STATE_CHOICES, required=False) state_lga = forms.CharField(label = 'Local Govt. Area:', max_length=12, widget=forms.TextInput(attrs={'placeholder': 'Enter Local Govt. of Property.'})) address = forms.CharField(label = 'Property Address:', max_length=60, widget=forms.TextInput(attrs={'placeholder': 'Enter Street Name with Number and Town Name only.'})) class Meta: model = Property fields = ('description', 'address', 'country', 'state', 'state_lga', 'property_type', 'bedrooms', 'bathroom_type', 'price', 'is_available', 'image') def __init__(self, *args, **kwargs): super().__init__(*args, **kwargs) self.fields['bedrooms'].required = False def clean_image(self): image = self.cleaned_data.get('image') if image: # Check if the image size exceeds 1MB if image.size > 1024 * 1024: # 1MB in bytes # Open the image using Pillow with Image.open(image) as img: # Reduce the image size while preserving the aspect ratio max_width = 1920 max_height = 820 img.thumbnail((max_width, max_height), Image.ANTIALIAS) … -
Gmail API OAuth redirect issue
I have website with the following code that works perfectly on my local machine, but on the remote server, it doesn't redirect to Google OAuth to create token.json and gives me a 502 error. Where could I have made a mistake? I just need to authenticate with OAuth to access my Gmail account and retrieve emails from it. Can't generate token.json. SCOPES = [ 'https://mail.google.com/', ] def get_gmail_service(): creds = None config_path = os.path.join(os.path.dirname(__file__), 'config') credentials_path = os.path.join(config_path, 'creds.json') token_path = os.path.join(config_path, 'token.json') if os.path.exists(token_path): creds = Credentials.from_authorized_user_file(token_path, SCOPES) if not creds or not creds.valid: if creds and creds.expired and creds.refresh_token: creds.refresh(Request()) else: flow = InstalledAppFlow.from_client_secrets_file( credentials_path, SCOPES) creds = flow.run_local_server(port=0) with open(token_path, 'w') as token: token.write(creds.to_json()) try: service = build('gmail', 'v1', credentials=creds) return service except HttpError as error: print(f'An error occurred: {error}') def get_emails(): service = get_gmail_service() -
How can I load something from Django models in a HTML file without writing anything in views.py
I want to include the title and message from every notification in the model Notifications from models.py. I don't want to have to change every single views.py that I have to do this. I know that it's possible to put the tag {% request.user.name %} to get details from the user, but how can I do this with another random model? I have already tried some things. These are the files that I created/changed in an attempt to do this. (home is the name of my app) home/templatetags/__init__.py from .custom_tags import register home/templatetags/custom_tags.py from django import template from home.models import Notifications register = template.Library() @register.simple_tag def notifications(): data = Notifications.objects.all() return data home/templates/base.html {% load custom_tags %} <html> <head><!-- Some code here --></head> <body> <!-- Some more code here --> {% notifications %} {% for notification in notifications_list %} {{ notification.title }} {% endfor %} </body> In base.html, the line {% notifications %} shows <QuerySet [<Notifications: Notifications object (1)>]>. But all of the other lines don't do anything. Can anyone tell me what I'm doing wrong? -
Transform an array of objects and a simple array with python
I would like to ask for help on how to transform this arry result into a simple array of the type array=['a', 'b','c', ... 'aaa', 'aab' ...] that I want to be able to call the elements that are in the array only with indices ex: array[1] ='a'; arry[2]='b' and so on To help you understand what I want, see the result in this py file that I share here, try to run it on your machine and see the result it gives. from string import ascii_lowercase import itertools def iter_all_strings(): for size in itertools.count(1): for s in itertools.product(ascii_lowercase, repeat=size): yield "".join(s) lista=[] for s in itertools.islice(iter_all_strings(), 1000): lista.append(s) print (lista[-1:1000]) -
How to inherit template in django asyncronously
How can I inherit blocks eg.({% block title %}{% endblock title %}) in base.html without fully loading the entire page because my player always keeping stop wherever user try to do with other links. What's an ideal way to achieve this. I somehow able to load my entire html asynchronously but that didn't work. function ajax_load_page(this_a_tag, to_page) { event.preventDefault(); load_Page(this_a_tag, to_page); }; function load_Page(this_a_tag, to_page) { fetch(`${to_page}`) .then(response => response.text()) .then(data => { document.open(); document.write(data); document.close(); window.history.pushState({}, '', `${to_page}`); }) .catch(error => { console.log("An error occurred:", error); }); }; usage in my html <button class="nav-link active text-white w-100 text-start" onclick="ajax_load_page(this, '/')"> <i class="bi bi-house-heart me-2"></i> Home </button> thank you! -
In Django, how do I access request variable when validating password?
In Django I need to create a custom password validator which needs to read from the DB to fetch password policy configuration. To do this I need the client ID which is usually embedded in the request variable but in this case, request it is not available. Is there an alternative method to achieve this? class MinimumLengthValidator: """ Validate whether the password is of a minimum length. """ def __init__(self, min_length=8): self.min_length = min_length #get minimum length from client config here, typically request.client.config.password_min_length e.g. value is 10 -
Celery not picking up task from queue on ECS
I am using celery in my Django application together with rabbitmq to perform heavy long running tasks. I created ECS services on AWS and for celery worker service I enabled autoscaling. I created an alert on Cloudwatch to create new container when new message appears in queue. I chose message count VirtualHost celery queue because that's where all my messages are going to. The problem I am facing is that celery does not pick up the task from the queue even if new container in service is created. I checked rabbimq admin panel and I see new messages and I see that we containes are added but celery is not picking up them. I set up concurrency to 2 and 2 tasks are running properly but the next ones are starting only if any of these 2 tasks are completed. I tried to use --autoscale=15,2 option and I added -Q celery to specify the queue name. It is working but when I tried to run more than 15 tasks simultaneously I have the same problem so containers are created but tasks are not picked up from the queue. What I want to achieve is that new containers in a service … -
foregin key using name value fetch in django rest frame work
[![views.py][1]][1][![model.py][1]][1][![Model.pyfile][4]][4] i have add model.py ,view.py and serilializer.py file ,i will share country and state model . I wiil apply foregin key country and state fields. I will check in html fields in django rest framework in only object id fetch not value so like city(Morbi). -
Djangoe error: Reverse for 'detail' with arguments '('',)' not found. 1 pattern(s) tried: ['items/(?P<pk>[0-9]+)/\\Z']
Models.py: from django.contrib.auth.models import User from django.db import models class Category(models.Model): name = models.CharField(max_length=225) class Meta: verbose_name_plural = 'Categories' def __str__(self): return self.name class Item(models.Model): Category = models.ForeignKey(Category,related_name='items', on_delete=models.CASCADE ) name = models.CharField(max_length=225) description = models.TextField(blank=True, null=True) image = models.ImageField(upload_to='item_images', blank=True, null=True) created_by = models.ForeignKey(User, related_name='items', on_delete=models.CASCADE) created_at = models.DateTimeField(auto_now_add=True) def __str__(self): return self.name views.py: from django.shortcuts import render , get_object_or_404 from .models import Item def detail(request, pk): item = get_object_or_404(Item, pk=pk) return render(request, 'item/detail.html',{ 'item': item }) detail.html: {% extends 'core/base.html' %} {% block title %}{{ item.name }}{% endblock %} {% block content %} <div class="grid grid-cols-5 gap-6"> <div class="col-span-3"> <img src="{{ item.image.url }}" class="rounded-xl"> </div> </div> {% endblock %} index.html: {% extends 'core/base.html' %} {% block title %}Welcome{% endblock %} {% block content %} <div class="mt-6 px-6 py-12 bg-gray-100 rounded-xl"> <h2 class="mb-12 text-2xl text-center">Newest Oportunity</h2> <div class="grid grid-cols-3 gap-3"> {% for item in items %} <div> <a href="#"> <div> <img src="{{ item.image.url }}" class="rounded-t-xl"> </div> <div class="p-6 bg-white rounded-b-xl"> <h2 class="text-2xl">{{ item.name }}</h2> </div> </a> </div> {% endfor %} </div> </div> <div class="mt-6 px-6 py-12 bg-gray-100 rounded-xl"> <h2 class="mb-12 text-2xl text-center">Categories</h2> <div class="grid grid-cols-3 gap-3"> {% for category in categories %} <div> <a href="{% url 'item:detail' item.id %}"> … -
In Django, how can I create a database independent combobox that doesn't use it?
I'm new to Django. In my index.html page, I would like to insert a simple combobox that won't be connected to the database, but will be independent, for building miscellaneous code. What should I write in forms.py, view.py, models.py index.html and elsewhere? In forms.py i wrote: FAVORITE_COLORS_CHOICES = [ ("blue", "Blue"), ("green", "Green"), ("black", "Black"), ] class SimpleCombobox(forms.Form): favorite_colors = forms.MultipleChoiceField( required=False, widget=forms.CheckboxSelectMultiple, choices=FAVORITE_COLORS_CHOICES, ) -
import "adminsortable2.admin" could not be resolved
I am using python3.10.7 version of python and 4.1.1 version of django. I have installed Django Admin Sortable 2 in to my Django project. I have added 'adminsortable2', on INSTALLED_APPS of settings.py. when I used from adminsortable2.admin import SortableAdminMixin on admin.py the error import "adminsortable2.admin" could not be resolved is shown, how can I resolve this issue? -
multiple notifications from crontab in Django
I have a crontab in django/python, the code is given below. It is sending multiple notifications at the same time instead of sending single one. what is the problem? `def send_statistics(): today = date.today() yesterday = today - timedelta(days=1) try: if StatisticModel.objects.filter(date=yesterday).exists(): stat = StatisticModel.objects.get(date=yesterday) if not stat.is_send: text = "some text" send_message_telegram(text, SEND_STATISTIC_GROUP_ID) stat.is_send = True stat.save() time.sleep(100) else: StatisticModel.objects.create(is_send=True, date=yesterday) text = f"<b>*******HISOBOT*******</b>\n" \ send_message_telegram(text, SEND_STATISTIC_GROUP_ID) time.sleep(100) except: send_message_telegram def start(): scheduler = BackgroundScheduler({'apscheduler.timezone': 'Asia/Tashkent'}) scheduler.add_job(send_statistics, 'cron', hour=9) scheduler.start()` -
Trouble deploying Django application to AWS via Jenkins and Elastic Beanstalk
I have a Django application hosted on an EC2 instance that I deploy manually via eb deploy. This is my production instance, and works fine. The Ec2 instance is an Amazon Linux 2 Platform. I'm standing up a dev server using this tutorial. I wanted to include a Jenkins pipeline, so I am. I was able to deploy a barebones EB application to an Amazon Linux 2023 platform, but now I'm trying to deploy my own application. I think the change from Amazon Linux 2 to Amazon Linux 2023 might be a part of the issue. I'm pretty new to dev ops/infra and I'm trying my best to figure it out. The tutorial I'm following (as well as several other sources) made it seem that I need to use an Ubuntu EC2 instance. So Ubuntu as the OS w/ Amazon Linux 2023 as the platform (please correct me if my terminology is incorrect) My Jenkins builds are pushing to AWS for deployment, but they are failing. The intial errors complain about yum and amazon-linux-extras. Through some reaserch, I beleve that the amazon-linux-extras package is not requred on Amazon Linux 2023, but maybe that's not correct. Regardless, when I push with … -
docker-compose) Django+NGINX+gunicorn, not served static files
My project name is mvp. and I want to build docker-compose that django+nginx+gunicorn ├── Dockerfile ├── README.md ├── mvp │ ├── __init__.py │ ├── __pycache__ │ ├── asgi.py │ ├── settings.py │ ├── urls.py │ └── wsgi.py ├── contents ├── core ├── db.sqlite3 ├── docker-compose.yml ├── mains ├── manage.py ├── media ├── nginx.conf ├── requirements.txt ├── static │ ├── css │ ├── fonts │ ├── images │ ├── js │ └── thirdparty └── templates and Django project's settings.py static code is STATIC_URL = "static/" STATIC_ROOT = os.path.join(BASE_DIR, 'staticfiles') STATICFILES_DIRS = (os.path.join(BASE_DIR, "static"),) dockerfile FROM python:3.9 RUN apt-get update && apt-get install -y python3-pip && apt-get clean WORKDIR /usr/src/app/ COPY requirements.txt ./ RUN python -m pip install --upgrade pip RUN pip install -r requirements.txt COPY . . RUN python manage.py collectstatic --noinput RUN python manage.py makemigrations RUN python manage.py migrate nginx.conf user nginx; worker_processes auto; events { worker_connections 1024; } http { server { listen 80; server_name localhost; include mime.types; client_max_body_size 16M; location /static/ { alias /staticfiles/; } location /media/ { autoindex on; alias /media/; } location / { proxy_pass http://mvp:8000; proxy_redirect off; proxy_set_header Host $host; proxy_set_header X-Real-IP $remote_addr; proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for; } } } docker-compose.yml version: "3.7" services: nginx: image: … -
How to make test codes JSONField in DRF
I have JSON parse problem. When I use Insomnia(API Testing tool), there is no problem. But my test case, it is. Do you think that my test case code is wrong? {'detail': ErrorDetail(string='JSON parse error - Expecting property name enclosed in double quotes: line 1 column 2 (char 1)', code='parse_error')} models.py class Profile(models.Model): ... passions = models.JSONField(max_length=100, null=True, blank=True) ... tests.py from rest_framework.test import APITestCase class UpdateProfileTestCase(APITestCase): def setUp(self): ... self.url = reverse("profile") def test_can_update_profile(self): data = { "passions": {"data": ["soccer", "tennis"]} } response = self.client.patch( self.url, data, content_type="application/json", ) self.assertEqual(response.status_code, status.HTTP_200_OK) views.py class ProfileViewSet(viewsets.ViewSet): def partial_update(self, request, pk=None): ... serializer = ProfileSerializer(profile, data=request.data, partial=True) if serializer.is_valid(): serializer.save() return Response(serializer.data) return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST) serializers.py class ProfileSerializer(serializers.ModelSerializer): class Meta: model = Profile fields = [ "passions" ] -
Using FormMixin with DetailView?
In detail page: We want to display form:According docs,We must be used wrapper: from django.views import View class CommentGet(DetailView): model = Article template_name = "article_detail.html" def get_context_data(self, **kwargs): context = super().get_context_data(**kwargs) context["form"] = CommentForm() return context class CommentPost(SingleObjectMixin, FormView): model = Article form_class = CommentForm template_name = "article_detail.html" def post(self, request, *args, **kwargs): self.object = self.get_object() return super().post(request, *args, **kwargs) def form_valid(self, form): comment = form.save(commit=False) comment.article = self.object comment.save() return super().form_valid(form) def get_success_url(self): article = self.get_object() return reverse("article_detail", kwargs={"pk": article.pk}) class CView(View): def get(self, request, *args, **kwargs): view = CommentGet.as_view() return view(request, *args, **kwargs) def post(self, request, *args, **kwargs): view = CommentPost.as_view() return view(request, *args, **kwargs) Are we could simply used post method with detailview? class Detail(DetailView): model = ... def post(self): #do something here. -
How to send JSON data from client to Django websocket server
I'm trying to create Django server to receive JSON data fast from external client (sensor), so I decided to go from classic HTTP to consumers. I can add data from admin page and from REST framework page, but I can't send anything via test client (browser extention). Here is my consume.py (based on this repo live-data-drf-channels). # consumers.py from djangochannelsrestframework.generics import GenericAsyncAPIConsumer from djangochannelsrestframework.mixins import ListModelMixin from djangochannelsrestframework.observer import model_observer from . import models, serializers class PostConsumer(ListModelMixin, GenericAsyncAPIConsumer): queryset = models.SensorsValue.objects.all() serializer_class = serializers.SensorsValueSerializer() # permissions = (permissions.AllowAny,) authentication_classes = [] # disables authentication permission_classes = [] async def connect(self, **kwargs): await super().connect() await self.model_change.subscribe() print("Connected") @model_observer(models.SensorsValue) async def model_change(self, message, **kwargs): print("JSON") await self.send_json(message) @model_change.serializer def model_serialize(self, instance, action, request_id=None, **kwargs): print(dict(data=serializers.SensorsValueSerializer(instance=instance).data, action=action.value)) return dict(data=serializers.SensorsValueSerializer(instance=instance).data, action=action.value) async def disconnect(self, message): print("Disconnected") await super().disconnect(message) My test client is connecting and disconnecting correctly, but every time I try to add new data like: {"data": {"timer": 3, "accX": 10.0, "accY": 10.0, "accZ": 10.0, "gyrX": 10.0, "gyrY": 10.0, "gyrZ": 10.0}, "action": "create"} I get this error: Exception inside application: 'request_id' Traceback (most recent call last): File "C:\Users\Natalia\Desktop\djangoProject\venv\lib\site-packages\django\contrib\staticfiles\handlers.py", line 101, in __call__ return await self.application(scope, receive, send) File "C:\Users\Natalia\Desktop\djangoProject\venv\lib\site-packages\channels\routing.py", line 62, in __call__ return … -
what i handel 500 (Internal server error) when url pattern str?
This is my code: project/urls/py: from django.contrib import admin from django.urls import path from todoapp import views urlpatterns = [ # admin page path('admin/', admin.site.urls), # home page path('', views.index, name='todo'), # delete with item_id path('del/<str:item_id>', views.remove, name='del'), ] handler404 = 'todoapp.views.handling404' and app/views.py: def remove(request, item_id): item = get_object_or_404(Todo, id=item_id) item.delete() messages.info(request, "Item Removed!!!") return redirect('todo') index.html: <form action="/del/{{item.id}}" method="POST" style="padding-right: 4%; padding-bottom: 3%;"> {% csrf_token %} <button value="Remove" type="submit" class="btn btn-primary" style="float: right;"> <span class="glyphicon glyphicon-trash"> Remove</span> </button> </form> when I intentionally access eg /del/abc then I get the 500 error instead of the 404 I expected So what's the real problem here? i tried replacing str to int and then i went to /del/abc got the page not found i expected path('del/<int:item_id>', views.remove, name='del'), -
Django best Practice for checking user type using Model
I am working on a Django project where I have Landlord, Agent and Prospect users and I want to check user type whenever a user logs in to determine the user type and redirect user appropriately, but my code does not work properly. Even when a valid user tries to login, the view redirects back to the login page. Some should help a brother. Models: class Landlord(models.Model): user = models.OneToOneField(User, on_delete=models.CASCADE) is_verified = models.BooleanField(default=False) def __str__(self): return self.user.username class Agent(models.Model): user = models.OneToOneField(User, on_delete=models.CASCADE) is_verified = models.BooleanField(default=False) def __str__(self): return self.user.username class Prospect(models.Model): user = models.OneToOneField(User, on_delete=models.CASCADE, related_name='prospect_profile') payment_ref = models.CharField(max_length=100, blank=True, null=True) payment_status = models.BooleanField(default=False) properties = models.ManyToManyField('Property', through='Tenancy') def __str__(self): return self.user.username def become_tenant(self, property): if self.payment_status: tenant = Tenancy.objects.create(tenant=self, property=property, agent=property.agent, landlord=property.landlord) return tenant else: return None class Tenancy(models.Model): tenant = models.ForeignKey(Prospect, on_delete=models.CASCADE) property = models.ForeignKey('Property', on_delete=models.CASCADE) agent = models.ForeignKey('Agent', on_delete=models.CASCADE) landlord = models.ForeignKey('Landlord', on_delete=models.CASCADE) start_date = models.DateField() end_date = models.DateField() def __str__(self): return f'{self.tenant} - {self.property}' class Meta: verbose_name_plural = 'Tenancies' View code: def index(request): user = request.user if user: # Check if User Profile is completed with new image uploaded def profile_complete(profile): return ( profile.full_name is not None and profile.full_name != '' and profile.phone_number is … -
Django: How to use a modal to delete an object?
On the index page for a list of food objects I've included a button to delete an object that is not used. The delete button launches a Bootstrap 5 modal delete form. But when I click the Delete button, the error thrown includes the name of index page. In the code below, where & how can this be fixed? Expected url on delete: .../food/1/delete Page not found: Request URL: http://127.0.0.1:8000/food/foodIndex/1/delete It may be worth noting that the 404 error considers the request to be GET rather than POST [I'm attempting to learn Python & Django by recreating a working PHP project. All of the HTML & javascript comes from that project.] food/urls.py: urlpatterns = [ path('foodIndex/', views.foodIndex, name="foodIndex"), path('<int:id>/edit/', views.foodEdit, name="foodEdit"), path('<int:id>/foodDelete/', views.foodDelete, name = "foodDelete") ] + static(settings.STATIC_URL, document_root=settings.STATIC_ROOT) Note: a path('foodIndex/<int:id>/foodDelete/',... does not solve the problem Template included in ".../food/foodIndex.html": {% if allFoods.count > 0 %} {% for food in allFoods %} <tr> <td data-foodid="{{ food.id }}">{{ food }}</td> <td><a class="btn p-0" href='{% url "food:foodEdit" food.id %}'>Edit</a></td> {% if food.used == False %} <td><button id='btn_delete' type="button" class="btn p-0" data-bs-toggle="modal" data-bs-target="#modal-delete" data-bs-foodid='{{ food.id }}' data-bs-foodname='{{ food }}'>Delete</button></td> {% endif %} </tr> {% endfor %} {% else %} <tr> <td … -
Django/Async: When Using {%For Loop%}
I have working javascript in my Django code. The Javascript updates a field by fetching the field and passing the data as json to a view. Then it updates this field in the DB. The html contains a table and every time someone fills a form out a new row in the table is created. Problem: It doesn't work when I use For Loops in my html code. What do I need to add to my javascript to get it to accept the code changes one at a time? . . . <td> <form action=" method='post' "> {%csrf_token%} <textarea name="cust_notes" maxlength="1000" required="" id="cust_notes" class="form-control" value="">{{ x.cust_notes }} </textarea> </form> </td> . . . . <script> const customerNoteInput = document.querySelector('#cust_notes'); const notesEndpointURL = '/customers/notes/' const customerId = {{note.user_cust_id}} let autosaveTimer; customerNoteInput.addEventListener('input', () => { clearTimeout(autosaveTimer); autosaveTimer = setTimeout(autosaveNote, 2000); }) function autosaveNote() { let noteText = customerNoteInput.value let data = { 'user_cust_id': customerId, 'cust_notes': noteText, } // Fetch API fetch(notesEndpointURL, { method: 'post', headers: { 'Content-Type': 'application/json', 'X-CSRFToken': '{{csrf_token}}', }, body: JSON.stringify(data) }) .then(response => { if (response.status == 200) { console.log('Success! Response was 200!') } return response.json() }) .then(data => { console.log(data) }) .catch(error => { console.error('Error: ', error) }) … -
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 …