Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Access a view variable within a template
I have a context variable which is dynamic because of a loop I perform: context['categories'] = choices.CATEGORIES for category_type, category in context['categories']: context[category_type] = Article.objects.filter(category=category_type).count() But in the template it just prints the category type instead of the number which is on the variable but I also need type for a link: {% for type, category in categories %} <a href="{% url 'app:category' type %}">{{category}}</a> {{type}} {% endfor %} How can I access this dynamic variable in a for loop? -
django TypeErrorin admin panel bug with database (expected a number but got)
hello i'm trying to make model manytomany field. my main goal is to write a model where i can assing my users human skills. for instance, i have skills[Good judgment, Patience with others, Strong communication] and i want to assign this 3 skill to user when i am doing that i am getting error like this. Field 'id' expected a number but got <Id: luka>. luka is one of my user which i created from admin panel. this is my models file class Skills(models.Model): skill_name = models.CharField(max_length=30) def __str__(self): return self.skill_name class Id(models.Model): first_name = models.CharField(max_length=100, null=True) human_skills = models.ManyToManyField(Skills, related_name="SkillsNames") def __str__(self): return self.first_name and when i am saving this is error: -
When I run my Django app using python manage.py runserver on a different pc I get a sqlite3.OperationalError: unable to open database file
Error message 'cudart64_110.dll'; dlerror: cudart64_110.dll not found 2021-09-03 13:07:38.728939: I tensorflow/stream_executor/cuda/cudart_stub.cc:29] Ignore above cudart dlerror if you do not have a GPU set up on your machine. 2021-09-03 13:07:44.525563: W tensorflow/stream_executor/platform/default/dso_loader.cc:64] Could not load dynamic library 'nvcuda.dll'; dlerror: nvcuda.dll not found 2021-09-03 13:07:44.525916: W tensorflow/stream_executor/cuda/cuda_driver.cc:326] failed call to cuInit: UNKNOWN ERROR (303) 2021-09-03 13:07:44.533594: I tensorflow/stream_executor/cuda/cuda_diagnostics.cc:169] retrieving CUDA diagnostic information for host: LAPTOP-673JJ4RS 2021-09-03 13:07:44.533921: I tensorflow/stream_executor/cuda/cuda_diagnostics.cc:176] hostname: LAPTOP-673JJ4RS 2021-09-03 13:07:44.535340: I tensorflow/core/platform/cpu_feature_guard.cc:142] This TensorFlow binary is optimized with oneAPI Deep Neural Network Library (oneDNN) to use the following CPU instructions in performance-critical operations: AVX AVX2 To enable them in other operations, rebuild TensorFlow with the appropriate compiler flags. System check identified no issues (0 silenced). Exception in thread django-main-thread: Traceback (most recent call last): File "C:\Users\soggi\AppData\Local\Programs\Python\Python39\lib\site-packages\django\db\backends\base\base.py", line 219, in ensure_connection self.connect() File "C:\Users\soggi\AppData\Local\Programs\Python\Python39\lib\site-packages\django\utils\asyncio.py", line 26, in inner return func(*args, **kwargs) File "C:\Users\soggi\AppData\Local\Programs\Python\Python39\lib\site-packages\django\db\backends\base\base.py", line 200, in connect self.connection = self.get_new_connection(conn_params) File "C:\Users\soggi\AppData\Local\Programs\Python\Python39\lib\site-packages\django\utils\asyncio.py", line 26, in inner return func(*args, **kwargs) File "C:\Users\soggi\AppData\Local\Programs\Python\Python39\lib\site-packages\django\db\backends\sqlite3\base.py", line 209, in get_new_connection conn = Database.connect(**conn_params) sqlite3.OperationalError: unable to open database file The above exception was the direct cause of the following exception: Traceback (most recent call last): File "C:\Users\soggi\AppData\Local\Programs\Python\Python39\lib\threading.py", line 954, in _bootstrap_inner self.run() File "C:\Users\soggi\AppData\Local\Programs\Python\Python39\lib\threading.py", line … -
Django - how to get id of get_or_create model instance?
assuming the following code: new_file, created = Files.objects.get_or_create( descriptor=somevalue, file_path=somevalue, file_name=somevalue, s3_backend=somevalue ) if created: new_file_id = ??? where << new_file, created >> is a tuple formed out of the model instance and a bool. At my if statement I only want to retrieve the id of new_file as string not as model instance. How can I do that? Thanks in advance -
Django/Python used two model in one html
I created movies website, using Django , I have two model first one is class Movie(models.Model): title = models.CharField(max_length=100) slug = models.SlugField(max_length=255, unique=True, db_index=True, verbose_name="URL") title_english = models.CharField(max_length=100) descritpion = models.TextField(max_length=1000) image = models.ImageField(upload_to="movies") category = models.CharField(choices=CATEGORY_CHOICES,max_length=10) language = models.CharField(choices=LANGUAGE_CHOICES,max_length=30) status = models.CharField(choices=STATUS_CHOICES,max_length=10) year_of_production = models.TextField(max_length=1000) view_count = models.IntegerField(default=0) and second is class Series(models.Model): title = models.CharField(max_length=100) slug = models.SlugField(max_length=255, unique=True, db_index=True, verbose_name="URL") title_english = models.CharField(max_length=100) descritpion = models.TextField(max_length=1000) image = models.ImageField(upload_to="movies") category = models.CharField(choices=CATEGORY_CHOICES,max_length=10) language = models.CharField(choices=LANGUAGE_CHOICES,max_length=30) status = models.CharField(choices=STATUS_CHOICES,max_length=10) year_of_production = models.TextField(max_length=1000) view_count = models.IntegerField(default=0) in view.py def home(request): user = request.user # Movies_obj = models.Movie.objects.all().order_by('-id')[:10] Movies_obj = models.Movie.objects.filter(category__in=['A']).order_by('-id')[:10] Movies_main_slider = models.Movie.objects.filter(category__in=["M"]).order_by('-id')[:10] Movies_main_suggest = models.Movie.objects.filter(status__in=["Suggest"]).order_by('-id')[:10] serial_obj = Serial seriali = models.Serial.objects.all().order_by('-id')[:10] return render(request,'index.html',{'user':user,'movies':Movies_obj,"main_slider":Movies_main_slider, "favorite":Movies_main_suggest,"serils":seriali}) def details(request,post_slug): movies_obj = Movies get_movie = Movies.objects.filter(slug = post_slug) return render(request,'Movie/movie_details.html',{"movies":get_movie}) also have two HTML file , index.html and movie_details.html , but when i add new Series not working in movies_details.html in movies_details i am using {% for i in movies %} {{ i.descritpion }} {% endfor %} and when i add series not working ,only movie models working , what is best way to used two model in one html ? created new html for series model ? -
How to implement audit trail in django?
I need to maintain the audit trail of all the actions and the user responsible for them, in Django. How should I implement it? It will also be great if I have the ability to revert my system to a previous state and replay the actions during an audit. One way is to add some sort of log in every API call. Is there more scalable way? And how to achieve database reversion? -
Which is Better Framework, in terms of handling Large Volume of Data, among Django, Flask, and FastAPI?
I want to know which python framework among Django, Flask, and FastAPI will be best in terms of performance (compute) and speed (latency), for building an API which will be able to handle database with millions if not not billions of records. So far I have studied that FastAPI is fastest in terms of speed (TechEmpower Benchmarks) but I want to know if it can handle high volume of data. -
How to implement OPA with Django microservices?
I am starting a project where there'll be a bunch of microservices in Django. I want to implement a separate Authentication and Authorization system that all the microservices will talk to for end-user auth. So, my doubts are: What approach should I take? I have looked at OPA and it seems promising but I can't seem to figure out the implementation. I also looked at some other authorization systems like Google's Zanzibar. Is it any good? -
How much people can Django's developement server handle (is suitable for 6 or 7 user at the time)?
I´m currently working on a project using Django, and everything seems to be working fine using the developement server for testing the app in one device (the same device where the command runserver is executed), and this Django project is configured with Xampp's MySQL But now I would like to test my app in several devices for acquiring information from several different users as the project main purpose is to captured certain data (the user write it manually). Would be about 6 or 7 people, so, can I move my project to a desktop computer (by example) and test my app with that amount of people using only the developement server ? or this number of users is more than the developement server can handle ? -
Access json _embedded and _links objects in Django template
I am working on a tool to print out API content (json) to an Django template, but I cannot seem to find out how I can access the _embedded and _links. Hope soneone can help views.py def get_certificate_view(request): certificates = xolphin.get_certificate_requests() context = { 'certs': certificates, } return render(request, "CreateCsr/certificates.html", context) myfunc.py: def get_certificate_requests(): api_url = "https://test-api.xolphin.com/v1/requests" r_get = requests.get(api_url, headers=headers).text data = json.loads(r_get) return data['_embedded']['requests'] my template view: {% for item in certs %} <h3>Item</h3> <p>{{item}}</p> <p>{{ item.id }}</p> <p>{{ item.domainName }}</p> <p>{{ item.validations }}</p> {% endfor %} Result of {{item}} = {'id': 960000021, 'domainName': 'test21.ssl-test.nl', 'company': 'Xolphin B.V.', 'dateOrdered': '2016-05-23T10:43:40+0200', 'validations': {'organization': {'status': False}, 'whois': {'status': False}, 'docs': {'status': False}, 'phone': {'status': False}, 'dcv': {'status': False}}, '_links': {'self': {'href': '/v1/requests/960000021'}}, '_embedded': {'product': {'id': 24, 'name': 'EV', 'brand': 'Sectigo', '_links': {'self': {'href': '/v1/products/24'}}}}} I know I can look through it in the function, but I want to loop through them inside my template view. hope that someone can help. I also know that their is an Xolhpin Python package but I don't want to relay on other packages so I want to use the API itself. Thanks in advance. Dave -
connect Django with react.js
enter code here function App() { return ( <div className="App"> <header className="App-header"> <img src={logo} className="App-logo" alt="l ogo" /> <p> Edit <code>src/App.js</code> and save to reload. </p> <a className="App-link" href="https://reactjs.org" target="_blank" rel="noopener noreferrer" > Learn React </a> <h1>wow sucess</h1> </header> </div> ); } I am working on Django project. so I built UI with html and bootstrap .now I want work with reactjs so how i impalement similar or existing ui in react and how I send httprequest and response from view to template -
How can we listen continous without running seperate file for RabbitMQ
In python Django micro-service, we are using rabbitMQ for internal communication,Now i have to run two terminal for a single service run manage.py run receive.py for consuming How can we combine this together to listening and run project. -
Django manage.py runserver returns a list of subcommands
How do I use "manage.py" instead of "python manage.py"? It used to work, but now it just returns a list of subcommands. Windows 10; PyCharm; Python 3.9; Environment variables are set: "PYTHONPATH": "\Python\Python39; \Python\Python39\DLLs; \Python\Python39\Lib;" manage.py has shebang: "#!/usr/bin/env python" venv in PyCharm is set to: "...\<project_folder>\venv\Scripts\python.exe" -
Django REST filering result
Is there some auto filtering feature in Django REST? Some build in functionality to filter using parameters in url? Or maybe is there some handy way to use optional parameter? -
HTML changes not reflecting on website in Django app using Ubuntu 20.0, Nginx, and Gunicorn
I'm hosting my Django website with Digital Ocean using Ubuntu 20.0. I deployed my app successfully. I have now been making changes to my HTML files. After running git pull origin master, I restarted both Gunicorn and Nginx. The changes are reflected in development but not in production. What could be the problem? -
how do i create a csv file, upload it to database and make it downloadable for users using django? [closed]
i'm an absolute beginner in django so please help me. i am working on a data quality management app, basically a user uploads their csv file, i evaluate it then fix the errors and let the user download the file again, but in order to not modify their original file, after the evaluation, i need to create another csv file where i only copy the good data. but when i create it, it ends up in the current folder with my views and urls etc files which i don't want, also i don't know how to upload it to my sqlite database and how to render it to my html page. -
I can't send embedded images in mail with django
i'm trying to send an email confirmation after an user created an account on my website. The problem is that, the email doesn't contains the images that i setted up on .html file and i don't know how am i supposed to send them: In view function: link = "http://localhost:3000/verify/" + user.verifyToken html_messages = render_to_string('emailTemplate.html',{"nume":request.data['nume'], "prenume":request.data['prenume'], "verifyLink":link}) plain_message = strip_tags(html_messages) mail.send_mail( 'Activate your account', plain_message, settings.EMAIL_HOST_USER, [request.data['email']], html_message=html_messages ) That's how i loaded the images in emailTemplate.html: <td style="padding:0;Margin:0;font-size:0px" align="center"><img class="adapt-img" src="images/34711630659742615.png" alt style="display:block;border:0;outline:none;text-decoration:none;-ms-interpolation-mode:bicubic" width="428"></td> <td style="padding:0;Margin:0;font-size:0px" align="center"><img src="images/90241630659912039.png" alt style="display:block;border:0;outline:none;text-decoration:none;-ms-interpolation-mode:bicubic" width="200"></td> If i open the .html file in my browser it looks fine but when i send it to e-mail it doesn't contains any image. Does anyone know what am i supposed to do? Thank you! -
Can't connect Postgres container with Django container on Docker
I have two images: 1. PostgreSQL, 2. Django application. I am trying to connect django with postgres via networking Here is my DATABASE_URL DATABASE_URL=postgres://postgres:somepassword@0.0.0.0:5432/music and my docker-compose.yml version: "3.1" services: db: image: postgres environment: POSTGRES_USER: postgres POSTGRES_PASSWORD: qweytr21 POSTGRES_DB: music ports: - 5432:5432 web: build: music-releases/ ports: - 8000:8000 depends_on: - db command: pipenv run python manage.py migrate So when i run docker-compose up. Postgres shows that it is listening this address listening on IPv4 address "0.0.0.0", port 5432 But Django (psycopg2-binary) shows error django.db.utils.OperationalError: could not connect to server: Connection refused Is the server running on host "0.0.0.0" and accepting TCP/IP connections on port 5432? As you can see psycopg searchs true host and port and postgres also is listening on that host and port. I have already searched for another answer but they don't work. Any help PLEEEASE!!! -
How to find all dates between 2 dates in django?
I want to find all dates between 2 dates the first date is unique_dates[0] the value of unique_dates[0] is 2021-08-30 and the second date is datetime.date.today() unique_dates = list({a.date for a in attendances}) date = datetime.date.today() How to do this ? -
Insert large data into Django database
How do I optimally add large datasets to Django? My current workflow looks like this: Scrapy -> DRF -> Celery -> (Transform data) -> Django ORM -> PostgresQL I was thinking of using something like this: Scrapy -> Kafka -> (Transform data) ? -> Python Consumer (Spark?!?) -> PostgresQL I care about the high efficiency of the solution. Up to 20 million upserts (update if exists else intest) are made daily. -
Dynamically creating tables using SQLite and django
I am given a task for a web im developing currently. The task is to dynamically create tables as long as the 'save' button is pressed in my web. I am using SQLite for my database. Currently, my codes allow me to do the necessary saving to the existing tables but I am unsure of how to do the following task. Example: I have the fields of 'name' and 'something'. So user type Test for name field and Hello for something field. Upon saving, this name is stored in a existing table and register under a id of 1. At the same time, i want to be able to create a new table with its own field. This table will be named as example_(id). So in this case it will be example_1. Im a beginner in Django and SQL so if anyone can guide/help me in any way, thank you! -
Is there a way to perform django admin like list filtering in django generic ListView?
I'm trying to add filtering for a django list view something like Here is my view class SaleView(ListView): model = SaleBill template_name = "sales/sales_list.html" context_object_name = "bills" ordering = ["-time"] paginate_by = 10 and my template {% extends "base.html" %} {% load widget_tweaks %} {% block title %} Sales List {% endblock title %} {% block content %} <div class="row" style="color: #ea2088; font-style: bold; font-size: 3rem;"> <div class="col-md-8">Sales List</div> <div class="col-md-4"> <div style="float:right;"> <a class="btn ghost-blue" href="{% url 'new-sale' %}">New Outgoing Stock</a> </div> </div> </div> <br> <table class="table table-css"> <thead class="thead-inverse align-middle"> <tr> <th width="10%">Bill No</th> <th width="15%">Customer</th> <th width="15%">Stocks Sold</th> <th width="10%">Quantity Sold</th> <th width="10%">Total Sold Price</th> <th width="15%">Sale Date</th> <th width="25%">Options</th> </tr> </thead> {% if bills %} <tbody> {% for sale in bills %} <tr> <td class="align-middle"> <h3>{{ sale.billno }}</h3> </td> <td class=""> {{ sale.name }} <br> <small style="color: #909494">Ph No : {{ sale.phone }}</small> </td> <td class="align-middle">{% for item in sale.get_items_list %} {{ item.stock.name }} <br> {% endfor %}</td> <td class="align-middle">{% for item in sale.get_items_list %} {{ item.quantity }} <br> {% endfor %}</td> <td class="align-middle">{{ sale.get_total_price }}</td> <td class="align-middle">{{ sale.time.date }}</td> <td class="align-middle"> <a href="{% url 'sale-bill' sale.billno %}" class="btn ghost-pink">View Bill</a> <a href="{% url 'delete-sale' sale.pk … -
Limiting file types for a specific DocumentChooserBlock() Block in Wagtail Steamfield
I'm trying to limit query results for a specific DocumentChooserBlock inside of a wagtail stream field block. I already know that you can limit file types for DocumentChooser for a page type by using hooks, but I would like to avoid limiting possible file types page wide in case I need them for other StreamField blocks. Are there any possible ways to implement what I am trying to achieve here? -
How i read the django log.debug() output and store in variable for display in my templates?
In logging setting i have set the output in console, and i want to read the console output for example a = log.debug("hello") print(a) But i tried this its return None -
Django ckeditor - How to create thumbnail of uploaded images by default
In settings.py I have CKEDITOR_IMAGE_BACKEND = 'pillow' but a thumbnails have not been created automatically. In docs v.6.1.0: Set CKEDITOR_IMAGE_BACKEND to one of the supported backends to enable thumbnails in ckeditor gallery. By default no thumbnails are created and full size images are used as preview. Supported backends: pillow: Uses Pillow How should I do it? Thanks!