Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
How do I rectify this collectstatic error?
I am trying to run python manage.py collectstatic But I got the following error message: FileNotFoundError: [WinError 3] The system cannot find the path specified: 'C:\\Users\\User\\Desktop\\PY4E\\djangoPorfolio\\static' Below are my settings.py STATIC_URL and STATIC_ROOT from pathlib import Path import os # Build paths inside the project like this: BASE_DIR / 'subdir'. BASE_DIR = Path(__file__).resolve().parent.parent STATICFILES_DIRS = [ os.path.join(BASE_DIR, 'static'), os.path.join(BASE_DIR, 'media') ] STATIC_URL = '/static/' STATIC_ROOT = BASE_DIR / 'staticfiles/' MEDIA_URL = '/media/' MEDIA_ROOT = BASE_DIR / 'mediafiles/' # Default primary key field type # https://docs.djangoproject.com/en/4.1/ref/settings/#default-auto-field DEFAULT_AUTO_FIELD = 'django.db.models.BigAutoField' CKEDITOR_BASEPATH = "/static/ckeditor/ckeditor/" Am I missing something? -
javascript fetch request(PUT) for formdata doesnt work when i specify the Content-type in the headers param
this is the request: let form = document.querySelector('form') let data = new FormData(form) fetch("http://127.0.0.1:8000/products/", { method: 'PUT', body: data, headers: { 'X-CSRFToken': "{{ csrf_token }}", } }) .then((response) => response) .then((data) => console.log(data)); So when I specify the Content-type in the headers param(doesnt matter if multipart/form-data, urlencoded etc. I tried it all) it doesnt work, but when I omit the content-type my backend(django) can process the request and the image is uploaded to the server and the rest of the formdata is being processed too. I looked at the network tab in ChromeDev Tools and the header is set to multipart with a strange ending: "multipart/form-data; boundary=----WebKitFormBoundary1QDdcJugTKrSMnto", does someone know the reason for this strange behavior? enctype is not set in the form element Thanks in advance <3 the content type header is set automatically. -
Django: Return values based on condition using SerializerMethodField
I have the tables: User, Event and EventTicket. I have to return total transactions and total tickets sold of each event. I am trying to achieve this using Django serializers. Using only serializers, I need to find the following: 1. total tickets sold: count of items in EventTicket table for each event 2. total transactions: sum of total_amount of items in EventTicket table for each event where payment_status: 1 models.py: class User(AbstractUser): first_name = models.CharField(max_length=50,blank=False) middle_name = models.CharField(max_length=50,blank=True) last_name = models.CharField(max_length=50,blank=True) class Event(models.Model): name = models.CharField(max_length=100, null=False, blank=False) user = models.ForeignKey(User, related_name='%(class)s_owner', on_delete=models.CASCADE) description = models.TextField(null=False, blank=False) date_time = models.DateTimeField() class EventTicket(models.Model): user = models.ForeignKey(User,on_delete=models.CASCADE) event = models.ForeignKey(Event,on_delete=models.CASCADE, related_name='event_tickets') payment_status = models.SmallIntegerField(default=0, null=False, blank=False) ## payment_success: 1, payment_failed: 0 total_amount = models.FloatField() date_time = models.DateTimeField() My desired output is: "ticket_details": [ { "event_id": 1, "event_name": Event-1, "total_transactions": 10000, ## Sum of all ticket amounts of event_id: 1, where payment_status: 1 "total_tickets": 24, ## Count of all tickets that belong to event_id: 1 }, { "event_id": 2, "event_name": Event-2, "total_transactions": 10000, ## Sum of all ticket amounts of event_id: 2, where payment_status: 1 "total_tickets": 24, ## Count of all tickets that belong to event_id: 2 }] This is what I have … -
How to get value from the different django model in DTL?
I am having 3 different models - User, Thread and UserProfile. User model contains information like ID, First_name and Last_name. Thread model contains information like class Thread(models.Model): first_person = models.ForeignKey(User, on_delete=models.CASCADE, null=True, blank=True, related_name='thread_first_person') second_person = models.ForeignKey(User, on_delete=models.CASCADE, null=True, blank=True,related_name='thread_second_person') updated = models.DateTimeField(auto_now=True) and UserProfile model, class master_personal_profile(models.Model): custom_user = models.OneToOneField(CustomUser, on_delete=models.CASCADE) picture = models.ImageField(default='profile_image/pro.png', upload_to='profile_image', blank=True) when I am trying to get all the threads from Thread model and pass it from views.py to my HTML template then I can access User model fields like - {{ thread.second_person.ID}} {{ thread.second_person.First_name}} But how can I access picture field from UserProfile with the help of custom_user ? -
Access django url without apache http basic authentication
I'm working on a Django 3.2 project which is hosted using Apache 2.4 server. The user authentication in this project is handled using HTTP Basic Authentication configured using LDAP. I have implemented a sign up feature for new users. For that I have created the necessary form, view, template and url pattern in the Django project. The urlpattern to visit the sign up form is /signup. My goal is to make the sign up urlpattern accessible to anyone i.e. prevent the Basic Authentication from showing when the sign up urlpattern is requested by user in the browser. JFI, the complete Apache configuration is already complete and works already. To achieve this, I have used the "LocationMatch" directive in the Apache configuration within the VirtualHost directive: ... <LocationMatch "^/signup$"> Require all granted </LocationMatch> ... With this the Basic Authentication is removed when /signup URI is requested, but the server always redirects to another url which ultimately requires authentication hence giving the basic auth pop-up. $ curl -I https://*****.com/signup HTTP/1.1 302 Found ... I have tried to redirect the request explicitly to /signup whenever the is /signup. This ends up in an endless loop of redirections. RewriteEngine on ... RewriteRule ^/signup$ /signup … -
How add object variable in static block django?
How can I implement addition object variable in static block, for example: <script src="{% static 'base/js/{{obj.id}}_container.js' %}"></script> How to make it works? -
how do I render out all objects of a loop in a email template
I'm trying to render all the product names, prices and quantities related to list_ordered_items into my email template. But the email contains just one product object detail instead of multiple product object details, I'm already looping through in the view! what's causing this? how do I fix this? models class Product(models.Model): name = models.CharField() final_price = models.DecimalField() class OrderItem(models.Model): product = models.ForeignKey(Product) quantity = models.IntegerField(default=0) views list_ordered_items = OrderItem.objects.filter(order__customer__user=request.user).select_related('product') for loi in list_ordered_items: product_name = loi.product.name product_price = loi.product.final_price product_qty = loi.quantity context = {'product_name': product_name, 'product_qty': product_qty, 'product_price': product_price} email template <tr> <td align="left" style="padding:0;Margin:0"><h4 style="Margin:0;line-height:17px;mso-line-height-rule:exactly;font-family:arial, 'helvetica neue', helvetica, sans-serif;font-size:14px"><strong></strong>{{product_name}}<strong></strong></h4></td> </tr> <tr> <td style="padding:0;Margin:0;text-align:center;font-size:13px;line-height:13px" width="15%" align="center"><p style="Margin:0;-webkit-text-size-adjust:none;-ms-text-size-adjust:none;mso-line-height-rule:exactly;font-family:arial, 'helvetica neue', helvetica, sans-serif;line-height:21px;color:#333333;font-size:14px"><strong></strong>{{product_qty}}<strong></strong></p></td> <td style="padding:0;Margin:0;text-align:center;font-size:13px;line-height:13px" width="30%"><p style="Margin:0;-webkit-text-size-adjust:none;-ms-text-size-adjust:none;mso-line-height-rule:exactly;font-family:arial, 'helvetica neue', helvetica, sans-serif;line-height:21px;color:#333333;font-size:14px"><strong></strong>${{product_price | floatformat:2}}<strong></strong></p></td> </tr> current view: should look like this: -
django: Exception has occurred: IndexError pop from empty list
I have been building a website where each essay may have a video object. For some reason, this error in Django continues to persist and I cannot understand where it comes from and how to fix it. The error related to views.py Exception has occurred: IndexError pop from empty list File "C:\foo\project\bar\views.py", line 65, in index_dev return render( IndexError: pop from empty list views.py: def index_dev(request): essay = EssayCls.objects.all().order_by('-date')[:3] video_obj = VideoObject.objects.all() user_agent = get_user_agent(request) context = { 'text_content': essay, 'show_text_content': True, 'video_obj': video_obj } if user_agent.is_pc: return render( request, 'dev/index_page.html', context ) models.py: ... from embed_video.fields import EmbedVideoField ... class VideoObject(models.Model): video_item_url = EmbedVideoField() # same like models.URLField() added_date = models.DateTimeField(auto_now_add=True, null=True) title_video = models.CharField(max_length=200) class Meta: ordering = ['-added_date'] class EssayCls(models.Model): title = models.CharField(max_length=200) organizer_email = models.EmailField(null=True) date = models.DateField(null=True) slug = models.SlugField(unique=True, db_index=True) description = models.TextField(validators = [MinLengthValidator(10)]) details = models.TextField() image = models.ImageField(upload_to='images') video = models.ForeignKey(VideoObject, blank=True, null=True, on_delete=models.SET_NULL, related_name="video_obj") language = models.ForeignKey(ProgLang, null=True, on_delete=models.SET_NULL) guest = models.ManyToManyField(SendMeMessage, blank=True) tags = models.ManyToManyField(Tag) template.html: {% for essay_item in text_content %} <div class="contact-details"> <h3><a href="{% url 'essay-path' slug %}" style="text-decoration: none; color: #35049080;">{{ title}}</a></h3> <p>{{ essay_item.description|convert_markdown|safe }}</p> <br /><br /> <p>Does this video work? check below:</p> {% comment … -
How to use HTML and JSON at the same time in DRF
I started using Django REST framework just a while ago and I had a little question. How can I get an HTML page on the site that I am currently making and get JSON format for other "clients"(e.g mobile aps, desktop etc) I searched for the answer on the internet, but didn't found any information about this -
Django. Websockets. Replace repalce part websocket URL
I have page with chat. There is list which consist of started dialogues and current dialog. Example Current dialog work by using webscoket connection and Django channels. I want then when click then jump in other dialog without refresh page. At the same time, URL changes, but websocket connection not changes - it is problem. How change websocket connetion? Example: .../chat/Joseph change to .../chat/Tyler If this can be implemented in some other way, I will be glad to have a couple of words. Thank you! -
СМС рассылка на Python/ Django
Я делаю сайт на DJANGO для одной компании. Они хотят внедрить СМС рассылку. Есть база данных номеров. Как это все можно реализовать? Подскажите если не сложно P.s. Я знаю что есть платные смс сервисы для этого. Но я бы хотел использовать самый правильный способ. -=========================== -
django.db.utils.OperationalError: FATAL: password authentication failed for user "postgres" 2023
I have got this error when I 'am doing for the first time dockerizing a Django existing app. bellow I have PostgreSQL db. image and conf its volume and add it to my app web...… can u help this one plz compose.yml version: '3.8' services: web: build: . volumes: - .:/dstorage ports: - 8000:8000 container_name: web_container command: python manage.py runserver 0.0.0.0:8000 depends_on: db: condition: service_healthy db: image: postgres volumes: - ./data/db:/var/lib/postgresql/data environment: - POSTGRES_DB= postgres - POSTGRES_USER = postgres - POSTGRES_PASSWORD= 123654 container_name: POSTGRES_db healthcheck: test: ["CMD", "pg_isready", "-q"] settings DATABASES = { 'default': { 'ENGINE': 'django.db.backends.postgresql', 'NAME':'postgres', 'USER':'postgres', 'PASSWORD': '123654', 'HOST':'db', 'PORT': 5432, i can't pass this error in return i have got FATAL: password authentication failed for user -
Control an asynchronous routine elegantly in Django
Using Django, I need to poll updates from a GraphQL subscription and being able to turn the updates on and off. My implementation uses websockets package wrapped in an async function to poll updates from a local container providing a GraphQL subscription and stores them in Django database. I need to find a way to control this polling feature with an on/off GraphQL mutation that would start or stop the readings and database updates. I've tried using celery by starting a celery task upon Django apps.py ready() method, but I think it became overkill and I ended up having multiple tasks being too hard to manage. I've also thought about using a database record to keep the status and run the asynchronous polling code in a management command, but it seems not a great idea to continuously read the feed status from database without any hook or so. My last attempt was to trigger a GraphQL mutation on my own service using a management command at the start of my docker-compose fleet to start the readings, but the asyncio event loop ends up locking the main thread for some reason. Here's my current implementation unsing asyncio : """ Feed listener … -
Using python script to upload a file to django server localhost
I build an django rest framework that can help me to upload a file in view.py class FileResultViewSet(viewsets.ModelViewSet): queryset = FileResult.objects.order_by('-timestamp') serializer_class = FileResultSerializer parser_classes = (MultiPartParser, FormParser) def perform_create(self, serializer): serializer.save() The script work well without any error, and the file is stored in media folder Then, I use an python script that can help me to upload file to django import requests import openpyxl url = "http://localhost:8000/upload/" headers = {'Content-Type': 'multipart/form-data'} file_path = "H:/MEGA_H/Data/uploaded/Book1.xlsx" ''' with open(file_path, 'rb') as f: file = {'file': f} response = requests.get(url, headers=headers, files=file) ''' filename = "Book1.xlsx" # Open the file and read its contents with open(file_path, 'rb') as f: file_contents = f.read() # Create a dictionary to store the file information #file_data = {'file': (filename, file_contents,result_file)} file_data = { "result_file": file_contents } # Make a POST request to the URL with the file information response = requests.post(url, files=file_data) # Check if the request was successful if response.status_code == 201: print("File successfully uploaded") else: print("Failed to upload file") The code still works with an issue, after upload the file to media folder, the file doesnt include the file type, so it can not read. I have to change the name of the … -
DJango how to create path to custom method in view?
I've been learning django for a few days and I started creating a simple project. However I have small problem with urls. In my project I created view: views/cars/scrapped_view.py from app.models import ScrappedCar from django.views.decorators.csrf import csrf_exempt from django.utils.decorators import method_decorator from rest_framework import status from rest_framework.views import APIView from rest_framework.response import Response from rest_framework.request import Request @method_decorator(csrf_exempt, name='dispatch') class ScrappedView(APIView): def get(self, request: Request) -> Response: # /cars/scrapped scrapped_cars = ScrappedCar.objects.all() return Response(scrapped_cars, status=status.HTTP_200_OK) def related(self, request: Request, id=None) -> Response: # /cars/scrapped/<int:id>/related scrapped_car = ScrappedCar.objects.get(id=id) related_scrapped_cars = ScrappedCar.objects.filter(user_id=scrapped_car.user_id, paid=True) return Response(related_scrapped_cars, status=status.HTTP_200_OK) The problem is that I don't know how to create a path to the method related. I was trying many different things but nothing works. Here you can see few of them: urls.py from django.urls import path from .views.cars.scraped_view import ScrapedView urlpatterns = [ path(route=‘cars/scrapped’, view= ScrapedView.as_view()), # works # path(route='cars/scrapped/<int:id>/related', view=NegativeKeywordView.as_view()) not working # path(route='cars/scrapped/<int:id>/related', view=NegativeKeywordView.as_view({‘get’ : ‘related})) not working # path(route='cars/scrapped/<int:id>/related', view=NegativeKeywordView.related) not working ] Do you know what I am doing wrong? How I can create path /cars/scrapped/<id>/related to the method related? -
Django - Find sum and count of values in child table using serializers
I have two tables: Event and EventTicket. I have to return total transactions and total tickets sold of each event. I am trying to achieve this using Django serializers. Using only serializers, I need to find the following: 1. total tickets sold: count of items in EventTicket table for each event 2. total transactions: sum of total_amount of items in EventTicket table for each event where payment_status: 1 I read about SerializerMethodField but couldn't find a solution specific to this scenario. class Event(models.Model): name = models.CharField(max_length=100, null=False, blank=False) description = models.TextField(null=False, blank=False) date_time = models.DateTimeField() class EventTicket(models.Model): user = models.ForeignKey(User,on_delete=models.CASCADE) event = models.ForeignKey(Event,on_delete=models.CASCADE) payment_status = models.SmallIntegerField(default=0, null=False, blank=False) ## payment_success: 1, payment_failed: 0 total_amount = models.FloatField() date_time = models.DateTimeField() My desired output is: "ticket_details": [ { "event_id": 1, "event_name": Event-1, "total_transactions": 10000, ## Sum of all ticket amounts of event_id: 1, where payment_status: 1 "total_tickets": 24, ## Count of all tickets that belong to event_id: 1 }, { "event_id": 2, "event_name": Event-2, "total_transactions": 10000, ## Sum of all ticket amounts of event_id: 2, where payment_status: 1 "total_tickets": 24, ## Count of all tickets that belong to event_id: 2 }] -
Partial change in the model of one field for individual users - DRF
I have a model: class Task(models.Model): title = models.CharField(max_length=255) description = models.TextField() status = models.ForeignKey(Status, on_delete=models.PROTECT, related_name='todo_status') author = models.ForeignKey(User, on_delete=models.PROTECT, related_name='todo_author') assignet_to = models.ManyToManyField(User, blank=True, related_name='todo_assigned_to') I want the user/users who will in field assigned_to the Task to only be able to edit the field Status. How I see it: url - for view Check_status And view Check_status class CheckStatusView(generics.RetrieveUpdateAPIView): queryset = Task.objects.all() serializer_class = TaskDetailSerializer permission_classes = [permissions.IsAuthenticated] and then I think I need redefine this def put(self, request, *args, **kwargs): return self.update(request, *args, **kwargs) or def patch(self, request, *args, **kwargs): return self.partial_update(request, *args, **kwargs) or maybe: def partial_update(self, request, *args, **kwargs): kwargs['partial'] = True return self.update(request, *args, **kwargs) I want the user/users who will in field assigned_to the Task to only be able to edit the field Status. -
What static code analyzer should be choosen for backend and frontend?
I need to choose great static code analyzer for a product where backend is on django and frontend is on angular. Which one is best? What options are great? To get list of static code analysers -
error al ejecutar npm run serve dentro de la carpeta frontend
estaria necesitando ayuda ya que al intentar ejecutar npm run serve dentro de mi carpeta front en mi proyecto django saltan los siguientes errores ERROR Failed to compile with 1 error 13:19:35 [eslint] Failed to load plugin '@typescript-eslint' declared in '.eslintrc.json': Cannot find module 'typescript' Require stack: /home/juan/Escritorio/proyectopersonal/app_front/node_modules/@typescript-eslint/eslint-plugin/dist/util/astUtils.js /home/juan/Escritorio/proyectopersonal/app_front/node_modules/@typescript-eslint/eslint-plugin/dist/util/index.js /home/juan/Escritorio/proyectopersonal/app_front/node_modules/@typescript-eslint/eslint-plugin/dist/rules/adjacent-overload-signatures.js /home/juan/Escritorio/proyectopersonal/app_front/node_modules/@typescript-eslint/eslint-plugin/dist/rules/index.js /home/juan/Escritorio/proyectopersonal/app_front/node_modules/@typescript-eslint/eslint-plugin/dist/index.js /home/juan/Escritorio/proyectopersonal/app_front/node_modules/@eslint/eslintrc/lib/config-array-factory.js /home/juan/Escritorio/proyectopersonal/app_front/node_modules/@eslint/eslintrc/lib/index.js /home/juan/Escritorio/proyectopersonal/app_front/node_modules/eslint/lib/cli-engine/cli-engine.js /home/juan/Escritorio/proyectopersonal/app_front/node_modules/eslint/lib/cli-engine/index.js /home/juan/Escritorio/proyectopersonal/app_front/node_modules/eslint/lib/api.js /home/juan/Escritorio/proyectopersonal/app_front/node_modules/eslint-webpack-plugin/dist/getESLint.js /home/juan/Escritorio/proyectopersonal/app_front/node_modules/eslint-webpack-plugin/dist/linter.js /home/juan/Escritorio/proyectopersonal/app_front/node_modules/eslint-webpack-plugin/dist/index.js /home/juan/Escritorio/proyectopersonal/app_front/node_modules/@vue/cli-plugin-eslint/index.js /home/juan/Escritorio/proyectopersonal/app_front/node_modules/@vue/cli-service/lib/Service.js /home/juan/Escritorio/proyectopersonal/app_front/node_modules/@vue/cli-service/bin/vue-cli-service.js Referenced from: /home/juan/Escritorio/proyectopersonal/app_front/.eslintrc.json You may use special comments to disable some warnings. Use // eslint-disable-next-line to ignore the next line. Use /* eslint-disable */ to ignore all warnings in a file. ERROR in [eslint] Failed to load plugin '@typescript-eslint' declared in '.eslintrc.json': Cannot find module 'typescript' Require stack: /home/juan/Escritorio/proyectopersonal/app_front/node_modules/@typescript-eslint/eslint-plugin/dist/util/astUtils.js /home/juan/Escritorio/proyectopersonal/app_front/node_modules/@typescript-eslint/eslint-plugin/dist/util/index.js /home/juan/Escritorio/proyectopersonal/app_front/node_modules/@typescript-eslint/eslint-plugin/dist/rules/adjacent-overload-signatures.js /home/juan/Escritorio/proyectopersonal/app_front/node_modules/@typescript-eslint/eslint-plugin/dist/rules/index.js /home/juan/Escritorio/proyectopersonal/app_front/node_modules/@typescript-eslint/eslint-plugin/dist/index.js /home/juan/Escritorio/proyectopersonal/app_front/node_modules/@eslint/eslintrc/lib/config-array-factory.js /home/juan/Escritorio/proyectopersonal/app_front/node_modules/@eslint/eslintrc/lib/index.js /home/juan/Escritorio/proyectopersonal/app_front/node_modules/eslint/lib/cli-engine/cli-engine.js /home/juan/Escritorio/proyectopersonal/app_front/node_modules/eslint/lib/cli-engine/index.js /home/juan/Escritorio/proyectopersonal/app_front/node_modules/eslint/lib/api.js /home/juan/Escritorio/proyectopersonal/app_front/node_modules/eslint-webpack-plugin/dist/getESLint.js /home/juan/Escritorio/proyectopersonal/app_front/node_modules/eslint-webpack-plugin/dist/linter.js /home/juan/Escritorio/proyectopersonal/app_front/node_modules/eslint-webpack-plugin/dist/index.js /home/juan/Escritorio/proyectopersonal/app_front/node_modules/@vue/cli-plugin-eslint/index.js /home/juan/Escritorio/proyectopersonal/app_front/node_modules/@vue/cli-service/lib/Service.js /home/juan/Escritorio/proyectopersonal/app_front/node_modules/@vue/cli-service/bin/vue-cli-service.js Referenced from: /home/juan/Escritorio/proyectopersonal/app_front/.eslintrc.json webpack compiled with 1 error probe borrar y reinstalar la carpeta node modules pero no hay solución por mas que la reinstalo sigue saltando el mismo error -
How do I display my list view in recommended_items?
I'd like to show the list's introduction to users, and I've used the Association rule in Django for this project. views.py def user_detail(req, id): AllParcel = Add_Parcel.objects.filter(id=id).first() df = pd.read_csv('myapp/recommend.csv') df = df.drop_duplicates().reset_index(drop=True) df = df.pivot(index='item_id', columns='user_id', values='user_id') df = df.notnull().astype(int) frequent_itemsets = apriori(df, min_support=0.5, use_colnames=True) rules = association_rules(frequent_itemsets, metric="confidence", min_threshold=0.5) user_loans = LoanParcel.objects.filter(user=req.user) user_borrowed = [loan.parcel_item.name for loan in user_loans] recommended_items = [] for item in rules['antecedents']: if set(item).issubset(set(user_borrowed)): recommended_items.extend(list(Add_Parcel.objects.filter(name__in=rules[rules['antecedents'] == item]['consequents'].tolist()[0]))) context = { "AllParcel": AllParcel, "recommended_items" : recommended_items, } return render(req,'pages/user_detail.html',context) I wanted to render recommended_items to display similar to Add_Parcel using data from Add_Parcel's database to display, but when I put the display command in HTML, it returned as a blank value. How should I fix it? user_detail.html <h2>Recommended Items</h2> <ul> {% for parcel in recommended_items %} <li>{{ parcel.name }} ({{ parcel.nametype }}) - {{ parcel.description }}</li> {% endfor %} </ul> recommend.csv item_id,user_id 1,1 1,2 1,3 1,4 1,5 1,6 1,7 3,8 3,9 3,10 3,11 1,12 1,11 1,10 2,9 2,8 2,7 -
How can I customize text wrapping and text style in Bokeh table?
I have a base Bokeh table in Django Python. I have it displayed in its basic form - as by default without any style editing. At me all words are superimposed on other columns of the data. What's in the header of the table - what's in the body of the table. I can not change the font of the table - the title and body of the table. How can I set up a data-wrapped display of table text on another line? And how can I change the font of the text inside the table - the table header and table body? My table does not expand to the entire DIV container in which it is located. Sometimes layering on other template objects. How can this be set up? def table_htmx(request): context = {} qs_select_tabl = Table_model.objects.filter(name_1=select_1).order_by('name_name') qs = qs_select_tabl.values() df = pd.DataFrame.from_records(qs) header = [field.verbose_name for field in Table_model._meta.get_fields()] df.columns = header template = """ <div style="font-size: 100%"> <%= value %> </div> """ template_html = HTMLTemplateFormatter(template=template) columns = [TableColumn(field=col, title=col, formatter=template_html) for col in header] source = ColumnDataSource(df) data_table = DataTable(source=source, columns=columns, width=800) script, div = components(data_table) context['script'] = script context['div'] = div return render(request, "table_htmx.html", context) -
Display a list of related fields in the admin panel
I have two related models. class Refbook(models.Model): code = models.CharField(max_length=100, unique=True) name = models.CharField(max_length=300) description = models.TextField() class VersionRefbook(models.Model): refbook_id = models.ForeignKey('Refbook', on_delete=models.CASCADE, related_name='versions') version = models.CharField(max_length=50) date = models.DateField() When I edit a Refbook instance in the admin panel, I want the read-only list of available versions of this Refbook instance to be displayed on the same page. I know that it is possible to output them through TabularInline . And it seems that there is a read-only property here. Maybe there is a way to display just a list in a column or row separated by commas? Now, I have this code in admin.py: @admin.register(Refbook) class RefbookAdmin(admin.ModelAdmin): list_display = ['id', 'code', 'name'] I tried to create a "get_versions(self)" method in models.py in Refbook class, in which I received a queryset using related_name. But I can't display it in the admin panel. Or is it still correct to do this using the model.ModelAdmin parameters? -
How to ensure consistency between Django models and underlying databases
On our staging server we observed a runtime error stating a field is missing from a database, column our_table.our_field does not exist LINE 1: ...d"."type", "our_table"... The field was added in a latest update during some complex migration squashing process, through which we should have made some mistakes. Since manage.py showmigration did show the migration has been applied and we do not run our tests on staging/production servers, we are wondering what is the best way to detect such an error. To rephrase the question using a simpler example, how to detect inconsistency between database structure and Django models after an incorrect migration introduced by something like the following? python manage.py migrate our_app --fake I suppose I am looking for something like python manage.py check_database -
django get to every user if its latest record match given value in table
I want to filter students if his last record transaction_type match with given value. For example Student Ali has 3 record in transaction table. And if the latest records transaction_type == 'busy' I want to get this transaction otherwise I want to pass this transaction My Models like that class Type(models.Model): type = models.CharField(max_length=50) def __str__(self): return self.durum class Student(models.Model): ogr_no = models.CharField(max_length=10, primary_key=True) ad = models.CharField(max_length=50) soyad = models.CharField(max_length=50) bolum = models.CharField(max_length=100,blank=True) dogum_yeri = models.CharField(max_length=30) sehir = models.CharField(max_length=30) ilce = models.CharField(max_length=30) telefon = models.CharField(max_length=20,blank=True, null=True) nufus_sehir = models.CharField(max_length=30,blank=True, null=True) nufus_ilce = models.CharField(max_length=30,blank=True, null=True) def __str__(self): return self.ogr_no + " " + self.ad + " " + self.soyad class Transaction(models.Model): student = models.ForeignKey(Student, on_delete=models.CASCADE, related_name='islemogrenci') transaction_type = models.ForeignKey(Type, on_delete=models.CASCADE) yardim = models.ForeignKey(Yardim, on_delete=models.CASCADE, blank=True, null=True) aciklama = models.CharField(max_length=300,blank=True, null=True) transaction_date = models.DateTimeField(blank=True,null=True) transaction_user = models.ForeignKey(User, on_delete=models.CASCADE,null=True,blank=True) def __str__(self): return self.student.ad + " " + self.transaction_type.durum Note: I use Postgres as Database Engine -
Django one column values to one column concat value using annotate Subquery returns more than 1 row
hellow my models see the blow class IP(models.Model): subnet = models.ForeignKey(Subnet,verbose_name="SUBNET",on_delete=models.CASCADE,related_name="ip_set") ip = models.GenericIPAddressField(verbose_name="IP",protocol="both",unpack_ipv4=True,unique=True) asset = models.ManyToManyField(Asset,verbose_name="HOSTNAME",through="AssetIP",related_name="ip_set",blank=True,) description = models.CharField(verbose_name="DESCRIPTION",max_length=50,default="",null=True,blank=True) class AssetIP(models.Model): TYPE_CHOICES = [ ("GATEWAY-IP", "GATEWAY-IP"), ("MGT-IP", "MGT-IP"), ("PRIMARY-IP", "PRIMARY-IP"), ("OTHER-IP", "OTHER-IP"), ] ip_type = models.CharField(verbose_name="IP TYPE",max_length=30,choices=TYPE_CHOICES) ip = models.ForeignKey(IP,verbose_name="IP",on_delete=models.CASCADE,related_name="asset_ip_set") asset = models.ForeignKey(Asset,verbose_name="HOSTNAME",on_delete=models.CASCADE,related_name="asset_ip_set") class Asset(models.Model): barcode = models.CharField(verbose_name="Barcode",max_length=60,blank=True,null=True,unique=True) hostname= models.CharField(verbose_name="Hostname",max_length=30) so in this model data is blow IP Model | IP | Asset | Description | |:---- |:------:| -----:| | 10.10.10.2 | A_HOST,B_HOST,C_HOST | - | | 10.10.10.3 | A_HOST,B_HOST | - | | 10.10.10.4 | A_HOST | - | | 10.10.10.5 | A_HOST | - | AssetIP through Model | IP | Asset | IP_TYPE | |:---- |:------:| -----:| | 10.10.10.2 | A_HOST | OTHER-IP | | 10.10.10.2 | B_HOST | OTHER-IP | | 10.10.10.2 | C_HOST | OTHER-IP | | 10.10.10.3 | A_HOST | OTHER-IP | | 10.10.10.4 | A_HOST | OTHER-IP | | 10.10.10.5 | A_HOST | PRIMARY-IP | So Asset Query Result in this Result = Asset.objects.all() in this result Field Asset = { barcode: "ddd", hostname: "A_HOST", } I Want Field and Result Asset = { barcode: "ddd", hostname: "A_HOST", primary_ip : "10.10.10.5", other_ip : "10.10.10.2, 10.10.10.3, 10.10.10.4" } I Try the this query …