Django community: Django Q&A RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
In Django, how to delete exclusive many-to-many objects for a parent object?
My Django App has an Organisation model. An organisation may be identified by many aliases but these aliases may not be unique to that organisation. For example: Imperial College London (imperial.ac.uk) - may have an alias of ICL. The ICL Group (icl-group.com) - may share the same alias of ICL. In order to cater for this I have defined a ManyToMany relationship: class Organisation(models.Model): ... aliases = models.ManyToManyField(OrgAlias) ... Currently, when I delete an organisation, I need to manually check all of it's associated aliases and delete those that aliases aren't attached to another organisation. Is there a way to automatically cascade deletions of aliases that are exclusive to the organisation being deleted. I briefly explored pre_delete signals. If this is the way to go, can anyone provide an example? Alternatively if there is a better route, would appreciate the guidance. -
Cannot access style sheet in static django
I'm trying to deploy my django project using cpanel I have manage to show the HTML successfully but the style in static folder cannot be accessed in stderr.log I got this error message Not Found: /static/assets/default/css/style.css in setting.py I have static set like this STATIC_URL = '/static' STATICFILES_DIRS = ( # location of your application, should not be public web accessible './static', ) in the HTML I use this to access the style sheet <script src="{% static 'posApp/assets/default/css/style.css' %}"></script> I have the folder like this -pos -setting.py -posApp -templates -login.html -static -posApp -assets -default -css -style.css I have tried looking online my problem and also comparing my website in cpanel and my website that I run locaclly using localhost and could not find the answer why I get this error -
How to restore SQLite database backup in PostgreSQL with Django, encountering circular dependency and foreign key constraint issues
I have a large amount of data in SQLite and I recently created a backup. Now, I want to restore this backup into a PostgreSQL database. However, I am facing circular dependency and foreign key constraint problems during the restoration process. My project is developed using Django. What is the recommended approach to take a backup from the SQLite database and restore it in a PostgreSQL database while addressing circular dependency and foreign key constraint issues? Are there any specific steps or considerations to keep in mind when performing this task with Django? -
Exception Type: NoReverseMatch
i have a signup.html with this view: signup view 1 signup view 2 and activation view when user trying to create account after clicking in submit(signup) they should get a email which is tHis image:verification email but im getting this error: the error i got -
DRF Response returns string with formatting characters (newline and space) but is not actually formatting
data = { "data": [ {"example":"a","id": 1}, {"example":"b","id": 2}, {"example":"c","id": 3}, ], "numItem": 3 } JsonResponse(data, json_dumps_params={"indent":4}) Returns this Response(json.dumps(data, indent=4), content_type='application/json') Returns this And json_data = json.dumps(data, indent=4) return Response(json.loads(json_data), content_type='application/json') Returns This I see that Response is returning a string. Meaning json.dumps(data, indent=4) actually returns string and I am just passing the stringed json with \n and space (formatting). But why does the formatting work properly with JsonResponse? How could I make Response also returns formatted json and displayed correctly? And why is the the json string passed not being displayed with actual newline. -
Failed to establish a new connection: [Errno 111] Connection refused Django_in_Docker + FastAPI_in_Docker
I deploy 2 applications in different Docker container: 1 application-Django 2 application-FastAPI I have view function "view_request" in my Django-app, which make request to FastAPI app. From my browser Chrome I make request to Django endpoint, which run "view_request" function in Django, which make request to FastAPI app. Then I have this: ConnectionError HTTPConnectionPool(host='127.0.0.1', port=8100): Max retries exceeded with url: / (Caused by NewConnectionError('<urllib3.connection.HTTPConnection object at 0x7f146c6a61c0>: Failed to establish a new connection: [Errno 111] Connection refused')) FastAPI app This container run by command: docker run -d --name fast_api -p 8100:8000 fast_api Dokerfile: FROM python:3.8.10-slim # WORKDIR /code # COPY ./requirements.txt /code/requirements.txt # RUN pip install --no-cache-dir --upgrade -r /code/requirements.txt # COPY ./app /code/app # CMD ["uvicorn", "app.main:app", "--host", "0.0.0.0", "--port", "8100"] file main.py: from fastapi import FastAPI app = FastAPI() @app.get("/") def root(): return { "message": ( "Hello World !!!!!!" "This message from FastApi!" ) } if __name__ == '__main__': uvicorn.run(app, host='127.0.0.1', port=8100) Django app This container run by command: docker run --name sim_app -it -p 8000:8000 sim_app Dokerfile: FROM python:3.8.10-slim RUN mkdir /app COPY requirements.txt /app RUN pip3 install -r /app/requirements.txt --no-cache-dir COPY simple_app/ /app WORKDIR /app CMD ["python3", "manage.py", "runserver", "0:8000"] file views.py: def view_request(request): template = … -
publish django project where i use websocket
While my django project is working in local, when I try to publish it with dajngo and nginx, it still works but cannot connect to websocket. **/etc/nginx/sites-available/oasis ** server { listen 80; server_name 34.224.212.102; location / { include proxy_params; proxy_pass http://unix:/home/ubuntu/Youtube_video_downloader/myproject.sock; proxy_set_header Host $host; proxy_set_header X-Real-IP $remote_addr; } location /ws/ { proxy_pass http://unix:/home/ubuntu/Youtube_video_downloader/myproject.sock; proxy_http_version 1.1; proxy_set_header Upgrade $http_upgrade; proxy_set_header Connection "upgrade"; proxy_set_header Host $host; proxy_redirect off; } } **/etc/systemd/system/gunicorn.service ** Unit] Description=Gunicorn service After=network.target [Service] User=ubuntu Group=www-data WorkingDirectory=/home/ubuntu/Youtube_video_downloader ExecStart=/home/ubuntu/.local/share/virtualenvs/Youtube_video_downloader-SjipcW-q/bin/gunicorn access-logfile - --workers 3 --bind unix:/home/ubuntu/Youtube_video_downloader/myproject.sock video_downloader.wsgi:application [Install] WantedBy=multi-user.target -
Using wagtail crx and making custom templates but also using child pages
Hi I have a question on how to be able to use wagtail crx extension I want to still use wagtail crx but create custom templates for 3 to 4 sections of my site more or less want to add forms on the 3 other pages I haven’t tried it yet I was asking if there was such an ability before I start and if anyone has any examples to share on how to do it -
Django ORM - How to concatenate or Group ManyToMany field values in queryset
I am building my first Django App, am very new to it and have come undone trying to handle instances where a field has multiple values in a queryset. My specific example is that I am trying to fetch all unique machine_name's with their most recent handover_id and the handover model's associated fields. ct_limitations is a ManyToManyField in the handover model and contains multiple values - Whilst I am expecting only 5 unique machines, one of which has two ct_limitations, I get a new row for each ct_limitaion value as below: MySQL Screenshot Any assistance or pointers would be greatly appreciated My code as follows: Models.py from django.db import models from django.contrib.auth.models import User # Machine Type class MachineType(models.Model): machine_type = models.CharField(max_length=50, blank=True) def __str__(self): return str(self.machine_type) # Purpose class Purpose(models.Model): purpose = models.CharField(max_length=50, blank=True) def __str__(self): return self.purpose class Meta: # Add verbose name verbose_name_plural = 'Purposes' # Status class Status(models.Model): status = models.CharField(max_length=50, blank=True) def __str__(self): return self.status class Meta: # Add verbose name verbose_name_plural = 'Statuses' # CT Limitations class CTLimitations(models.Model): ct_limitations = models.CharField(max_length=50, blank=True, verbose_name='CT limitations') def __str__(self): return self.ct_limitations class Meta: # Add verbose name verbose_name_plural = 'CT limitations' # Machine class Machine(models.Model): machine_name = … -
django.urls.reverse doesn't work as expected
I set urls at project level: urlpatterns = [ url(r'^$', homepage_view, name='index'), ] urlpatterns += [ ... url(r'^system_notifications/$', SystemNotificationsView.as_view(), name='system_notifications'), url(r'^script_runner/$', ScriptRunnerView.as_view(), name='script_runner'), ] ... And there is no urls set at app level. SystemNotificationsView and ScriptRunnerView are placed in the same app. View: class ScriptRunnerView(View): def get(self, request: HttpRequest, *args, **kwargs) -> HttpResponse: return {} When I try in test do this: reverse('script_runner') I got: django.urls.exceptions.NoReverseMatch: Reverse for 'script_runner' not found. 'script_runner' is not a valid view function or pattern name. but reverse('system_notifications') works well. How to set urls for script_runner correctly? -
NextJS Images replaces each other
I got so strange problem with NextJS Images. I use Django as my backend server and fetching data and Image URLs from Django in my NextJS project. Look import React, { FC, Suspense } from 'react'; import Link from 'next/link'; import Loader from '../Loader'; interface ProducerClientProps {} async function getProducers() { let res = await fetch(`http://localhost:8000/api/market/producers`); return res.json(); } const ProducerClient: FC<ProducerClientProps> = async ({}) => { const data = await getProducers(); return ( <aside className="min-w-max flex flex-col gap-5"> <div className="grid grid-cols-2"> {data.map((producer: Producer) => ( <div className="flex justify-center"> <Link href={`/producers/${producer.slug}`} className="flex items-center" > <div className="hover:scale-105 transition-transform duration-100 p-5"> <Image src={producer.image === null ? '/' : producer.image} alt={producer.title} width={80} height={80} style={{ objectFit: 'contain' }} /> </div> </Link> </div> ))} </div> </aside> ); }; export default ProducerClient; So in this code my Images replaces each other sometimes and even doubles. Like if I have Image_1.png, so I could see Image_1.png instead of Image_2.png in mapped data. Feels like observer effect, because when I make breakpoints in DevTools - everything works fine. Optimized Image Unoptimized Image (how it should look) Then I have Carousel component. import Image from 'next/image'; import React, { FC, useState } from 'react'; import Loader from '../Loader'; interface … -
celery issue while running periodic task via admin dashboard
I have setup celery on my server and tasks are running fine if we send them by command line but from admin dashboard the task hits are not coming in the celery worker logs. How can we fix it? i tried to run a periodic task from the admin dashboard -
Django. Console error 404 wpad.dat windows
Django console: Not Found: /wpad.dat [23/Jun/2023 12:31:18] "GET /wpad.dat HTTP/1.1" 404 2537. This error is sent to the console every 10 seconds I have not found any information on this error how to remove/fix this error -
Updating the file contents of a Django FileField during upload results in I/O error
I'm trying to encrypt the contents of a file that is being uploaded. This is the relevant code snippet: class AppFile(models.Model): app_file = models.FileField(upload_to=upload_to, validators=[validate_file_size]) encrypted_data_key = models.CharField(max_length=500, blank=True) def encrypt_file_with_data_key(self, data_key): cipher = Fernet(data_key) with self.app_file.open(mode='rb') as file: file_data = file.read() encrypted_data = cipher.encrypt(file_data) with self.app_file.open(mode='wb') as encrypted_file: encrypted_file.write(encrypted_data) def save(self, *args, **kwargs): if self._state.adding is True: # New image being uploaded encrypted_data_key, data_key = self.generate_data_key_from_vault() self.encrypted_data_key = encrypted_data_key # Encrypt the uploaded image file self.encrypt_file_with_data_key(data_key) super().save(args, kwargs) I prefer this approach as this is agnostic of the StorageProvider being used. I also want to avoid detaching the file to a temporary folder, and re-attach it after encryption. However, this results in the following error: Traceback (most recent call last): File "/Users/jeroenjacobs/.pyenv/versions/myapp/lib/python3.11/site-packages/django/core/handlers/exception.py", line 55, in inner response = get_response(request) ^^^^^^^^^^^^^^^^^^^^^ File "/Users/jeroenjacobs/.pyenv/versions/myapp/lib/python3.11/site-packages/django/core/handlers/base.py", line 197, in _get_response response = wrapped_callback(request, *callback_args, **callback_kwargs) ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ File "/Users/jeroenjacobs/.pyenv/versions/myapp/lib/python3.11/site-packages/django/views/generic/base.py", line 84, in view return self.dispatch(request, *args, **kwargs) ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ File "/Users/jeroenjacobs/.pyenv/versions/myapp/lib/python3.11/site-packages/django/views/generic/base.py", line 119, in dispatch return handler(request, *args, **kwargs) ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ File "/Users/jeroenjacobs/.pyenv/versions/myapp/lib/python3.11/site-packages/django/views/generic/edit.py", line 184, in post return super().post(request, *args, **kwargs) ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ File "/Users/jeroenjacobs/.pyenv/versions/myapp/lib/python3.11/site-packages/django/views/generic/edit.py", line 153, in post return self.form_valid(form) ^^^^^^^^^^^^^^^^^^^^^ File "/Users/jeroenjacobs/.pyenv/versions/myapp/lib/python3.11/site-packages/django/contrib/messages/views.py", line 12, in form_valid response = super().form_valid(form) ^^^^^^^^^^^^^^^^^^^^^^^^ File "/Users/jeroenjacobs/.pyenv/versions/myapp/lib/python3.11/site-packages/django/views/generic/edit.py", line 135, in … -
Python, django. Hierarchy in a tree-like structure
I'm using Python and Django. How can I create a web page that displays the employee hierarchy in a tree-like structure? For example: Employee-1 (Manager -) Employee-2 (Manager:Employee-1) Employee-3 (Manager :Employee-2) Employee-4 (Manager:Employee-3) Employee-5 (Manager :Employee-1) Employee-6 (Manager:Employee-5) Employee-7 (Manager :Employee-6) Employee-8 (Manager:Employee-5) Currently, my code looks like this: models.py: class Employee(models.Model): name = models.CharField(max_length=100) position = models.CharField(max_length=100) hire_date = models.DateField() salary = models.DecimalField(max_digits=8, decimal_places=2) manager = models.ForeignKey('self', on_delete=models.CASCADE, related_name='subordinates') How can views.py and the employee_hierarchy.html template look like? And where is the best place to implement the logic: in the model, view, or template? Thank you in advance! I tried the following code in views.py: def employee_hierarchy(request): employees = Employee.objects.select_related('manager').all() return render(request, 'employees/employee_hierarchy.html', {'employees': employees}) employee_hierarchy.html: <body> <h1>Employee Hierarchy</h1> <ul> {% for employee in employees %} {% include 'employees/employee_item.html' with employee=employee %} {% endfor %} </ul> </body> employee_item.html: <li>{{ employee.name }} ({{ employee.position }}) - Manager: {% if employee.manager %}{{ employee.manager.name }}{% endif %}</li> {% if employee.subordinates.all %} <ol> {% for subordinate in employee.subordinates.all %} {% include 'employees/employee_item.html' with employee=subordinate %} {% endfor %} </ol> {% endif %} I obtained the following result: Employee-2 - Manager: Employee-1 Employee-3 - Manager: Employee-2 Employee-3 - Manager: Employee-2 Employee-4 - Manager: Employee-1 … -
Django MPTT get descendants subquery
I am trying to get the same queryset I would get if I used get_queryset_descendants(queryset, include_self=True) without losing the queryset (keeping it as a subquery). Because of how get_queryset_descendants works, the queryset is being resolved and is not being a part of a subquery. If I do this, Model.objects.filter(id=1) is not being used as a subquery - I won't be able to use OuterRef("pk") descendants = Model.tree.get_queryset_descendants( Model.objects.filter(id=1), include_self=True, ) print(str(descendants.query)) # id 1 is not part of query Here's a sample of the models I use import django import mptt class Model1(mptt.models.MPTTModel): objects = django.db.models.Manager() tree = mptt.managers.TreeManager() class Model2(django.db.models.Model): model1 = django.db.models.ForeignKey(Model1) I'd like to do something like this: from django.db.models import ( Count, IntegerField, Subquery, ) model1_with_visible_model2 = Model1.objects.annotate( visible_model2_count=Subquery( ( Model2.objects .filter( model1__id__in=( # instead of just model1=OuterRef("pk") Model1.tree.get_queryset_descendants( Model1.objects.filter( # id=6347, # No error id=OuterRef("pk"), # This is my goal ).all(), include_self=True, ) ).values_list("id", flat=True), is_visible=True, ) .distinct() .values("model1") .annotate(count=Count("pk")) .values("count") ), output_field=IntegerField(), ), ) I am not using model1=OuterRef("pk") because model2 instances (even though not directly related to the parent model1 instance) should still be counted as long as they are related to a descendant of the parent model1 instance. -
Got 404 error after adding SSL certificate
I use Django, Docker-compose to create this project. It worked properly before i started to connect SSL certificate. In every page i get 404 error. Nginx wants to get html file but I can't underctend were I should find it. In nginx log i found the following errors: [error] 31#31: *4 open() "/etc/nginx/html/.well-known/acme-challenge/Lyi2pfq05iW1lx8c75fguhZ38nOnzLEY6jE7Dwh49x4" failed (2: No such file or directory), client: 18.223.43.49, server: plantsfinder.net, request: "GET /.well-known/acme-challenge/Lyi2pfq05iW1lx8c75fguhZ38nOnzLEY6jE7Dwh49x4 HTTP/1.1", host: "plantsfinder.net", referrer: "http://plantsfinder.net/.well-known/acme-challenge/Lyi2pfq05iW1lx8c75fguhZ38nOnzLEY6jE7Dwh49x4" "GET /plants/deciduous/ HTTP/1.1" 404 555 "-" "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/114.0.0.0 Safari/537.36" "-" 2023/06/22 15:50:19 [error] 31#31: *7 "/etc/nginx/html/plants/deciduous/index.html" is not found (2: No such file or directory), client: 5.29.13.184, server: plantsfinder.net, request: "GET /plants/deciduous/ HTTP/1.1", host: "plantsfinder.net" I do not understand were this html files should be. URL from django.urls import path from . import views app_name = 'plants' urlpatterns = [ path('<str:category>/', views.plants_list, name='plants_list'), ] view function: def plants_list(request, category): """Creates plant selection pages.""" template = 'plants/finder.html' filters = request.GET plant_type_model = PLANTS_TYPES[category] category_verbose_name = plant_type_model._meta.verbose_name_plural.title() plants = plant_type_model.objects.all() filters_min_max = {} if filters: plants, filters_min_max = filter_plants(plants, filters) page_obj, pagination = get_pagination(request, plants, PLANTS_PER_PAGE) context = { 'request': request, 'plant_category': category, 'category_verbose_name': category_verbose_name, 'plants': page_obj, 'fields': plant_type_model.fields, 'filters': filters_min_max, … -
how to run a python selenium celery task as asnyc task when celery is up and ready to work in Windows?
I need to run a celery task when the Celery is started (at start up) and it's ready to work in a Django environment. I have more than 5 celery tasks and those are running parallel without problem. but when i call Selenium task below, other tasks are paused and after Selenium task is done, other 5 tasks continue their work. selenium task must works as async forever in a While True: ... block code and this task tries to login to a website and do something on logged-in account. the selenium task should not have pause impact on other tasks are running. this selenium task just should be called one time. itself has While True:... loop code. celery.py: import os, redis from celery import Celery from celery.schedules import crontab celery_app = Celery('ea_games') celery_app.config_from_object('django.conf:settings', namespace='CELERY') celery_app.control.discard_all() celery_app.control.purge() celery_app.autodiscover_tasks() BASE_REDIS_URL = os.environ.get('REDIS_URL', 'redis://localhost:6379') celery_app.conf.broker_url = BASE_REDIS_URL celery_app.control.discard_all() celery_app.control.purge() tasks.py: ## when Celery is launched and it's ready to work, it will run the ```task_get_selenium_token``` task. @worker_ready.connect def at_start (sender, *args, **kwargs): with sender.app.connection() as conn: sender.app.send_task("ea_app.tasks.task_get_selenium_token", args, connection=conn) @celery_app.task def task_get_selenium_token(): get_token() ## this python function works permanently in a ```While True:...``` code. Note: i tried to do it with celery-beat. … -
Why does Railway tell me it can't find the start command
I'm doing a tutorial on MDN and I'm getting to the implementation part. I need to upload my GitHub project to Railway. Only Railway gives me this error: Using Nixpacks Nixpacks build failed ╔═══════════════════════════════ Nixpacks v1.9.0 ══════════════════════════════╗ ║ setup │ python310, gcc ║ ║──────────────────────────────────────────────────────────────────────────────║ ║ install │ python -m venv --copies /opt/venv && . /opt/venv/bin/activate ║ ║ │ && pip install -r requirements.txt ║ ║──────────────────────────────────────────────────────────────────────────────║ ║ start │ ║ ╚══════════════════════════════════════════════════════════════════════════════╝ Error: No start command could be found I have to admit that I'm a beginner and I'm also working on Windows, and I haven't had a chance to test the server in production locally (gunicorn doesn't run on windows). Can you tell me what I'm doing wrong? Thanks. MDN tutorial: https://developer.mozilla.org/en-US/docs/Learn/Server-side/Django/Deployment GitHub repository: https://github.com/mihaiparpalea/locallibrary I followed the instructions in the tutorial exactly. -
Automate Company selection after login in Quickbooks
I have to authenticate QuickBooks in flask. all things are working proper. But once generate AUTH URL run that URL in browser, then need to select company. is there any way to skip company selection or automate company select. I don't want to select company. enter image description here I don't want this screen, How can I select company auto? -
How to make complex query? | ChartJS and Django
I have a chart created using Chart JS library below: My models.py below: class Organization(models.Model): name = models.CharField(max_length=250, unique=True) def __str__(self): return self.name class AppealForm(models.Model): form_name = models.CharField(max_length=100) def __str__(self): return self.report_form_name class Appeal(models.Model): organization = models.ForeignKey(Organization, on_delete=models.SET_NULL, blank=True, null=True) appeal_form = models.ForeignKey(AppealForm, on_delete=models.CASCADE, blank=True, null=True) appeal_number = models.CharField(max_length=100, blank=True, null=True) applicant_first_name = models.CharField(max_length=100, blank=True, null=True) applicant_second_name = models.CharField(max_length=100, blank=True, null=True) date = models.DateField(blank=True, null=True) appeal_body = models.TextField() Script of Chart JS used to create choosen line graph: new Chart(chartTwo, { type: 'line', data: { labels: ['january', 'february', 'march', 'april', 'may', 'june', 'july', 'august', 'september', 'october', 'november', 'december'], datasets: [ { label: 'written', data: [ Math.floor(Math.random() * 100), Math.floor(Math.random() * 100), Math.floor(Math.random() * 100), Math.floor(Math.random() * 100), Math.floor(Math.random() * 100), Math.floor(Math.random() * 100), ], borderColor: "green", backgroundColor: "green", }, { label: 'oral', data: [ Math.floor(Math.random() * 100), Math.floor(Math.random() * 100), Math.floor(Math.random() * 100), Math.floor(Math.random() * 100), Math.floor(Math.random() * 100), Math.floor(Math.random() * 100), ], borderColor: "blue", backgroundColor: "blue", }, ] }, options: { responsive: true, scales: { y: { min: -20, max: 120, } } }, }) Qestion: how the query will look like for this graph using AppealForm model? P.s. I want to get a count of each AppealForm model … -
Saving images from Django Quill Editor to Amazon S3?
I'm working on a Django project and using the Quill Editor for rich text editing. I want to allow users to insert images into the editor and save them to an Amazon S3 bucket. I have successfully set up the integration with S3 for other file uploads, but I'm unsure how to handle the image upload specifically from the Quill Editor. I am using Django Admin along with Django Quill Editor, specifically the QuillField(), in my project. I would like to store images uploaded through the Quill Editor directly in an Amazon S3 bucket. Can someone please guide me on how to configure and implement this functionality? I would appreciate any instructions or code examples related to configuring S3 and handling image uploads from the Quill Editor in Django Admin. -
Suggest Front-End Technology for Django monolith Site to Webservice architecture Conversion
Converting Django monolith Site to Webservice architecture. Which front-end tecnology I sould use. Few in my mind are Angular: Framework, with most of the features inbuilt, but steep learning curve React: Liberary, easy to start with, lots of package available Vue: Quick and easy implemenation. Major selection factors are easy to implement and future prospects Please suggest I tried with angular, found it steep learning curve, vue.js is good but not very popular and react.js is library, which require additional package installation for site to work. -
Django: ordering numerical and string value with order_by
My problem is, that obviously the data is ordered by UTF-8 codes since it's a Charfield, with the predictable results .. it sort the data like this; My Data is: 1,8,7,2a, 4, 2, 11, 10... I want this ordered list: 1,2,2a,4,7,8,10,11 .. I really don't know how I can order this properly .. -
Typeerror at /blog/: expected string or bytes-like object, got 'QuerySet'
I am Trying To Create A Basic Blog Website with multiple urls working in django. For the Blog Page I have created a Custom template tag which will return the first few words from the content data of blog from Models. But when i am trying to execute it always displaying the same error 'expected string or bytes-like object, got 'QuerySet' This Is My :Models.py from django.db import models # Create your models here. class blogdata(models.Model): post_id=models.AutoField(primary_key=True) title=models.CharField(max_length=50,default="") heading=models.CharField(max_length=500 ,default="") content=models.CharField(max_length=900 ,default="",null=True) date=models.DateField() thumbnail=models.ImageField(upload_to='static/',default="") def __str__(self): return self.title This is my post_tags.py import re from django import template from ..models import blogdata register=template.Library() @register.simple_tag def FewFirst(): my_str=blogdata.objects.values_list('content') result = re.findall(r'\w+', my_str)[:10 ] result = " ".join(result) return result Note: Directory structure and file names are correct idk the main reason behind this error