Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
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! -
Django Filters NameError: name 'group' is not defined [closed]
When i am trying to render a view,i try to check by filter if the group is null or not. I already defined "group" in models as Foreignkey but it gives me the error.How can i solve it? Error File "/root/server/accounts/filters.py", line 33, in filter_queryset group == null NameError: name 'group' is not defined Views.py class GrouppArticleViewSet(viewsets.ModelViewSet): permission_classes = (IsAuthenticated,) queryset = Article.objects.all().order_by('-timestamp') serializer_class = ArticleSerializer filter_backends = [GroupArticlesFilterBackend] Filters.py class GroupArticlesFilterBackend(filters.BaseFilterBackend): def filter_queryset(self, request, queryset, view): return queryset.exclude( group == null ).filter( group__groupmembers_set__author=request.user ).distinct() Models.py class Article(models.Model): id = models.UUIDField(primary_key=True, default=uuid.uuid4, editable=False) author = models.ForeignKey(User,on_delete=models.CASCADE,related_name='articles') group = models.ForeignKey(Group,on_delete=models.CASCADE,null=True,blank=True,related_name='grouparticle') caption = models.CharField(max_length=250) -
Django Form - How to create a custom form template with a loop for one field?
I'm creating a web app which uses Django's templating engine. Having said that, one of my models is called Order. The Order model, aside from the other models, also uses a model Food - this is a ManyToMany relationship. Food model uses model Category to define food categories (which should contain food categories like Pizza, Burgers, Wine, Beers, etc.) - this is a ManyToMany relationship, as well. Now, I'm trying to create a form where the user will be shown a form with separated categories. As of now, all of the foods from the Food model are just shown one by one, one below another one. They are not categorized in the form template. Currently, they are shown by default, as a simple list of foods where user can choose any of them. I want the user to choose any foods they want, but display them categorically (all of the pizzas under the Pizza category, all of the burgers under the Burgers category, etc.). My models.py looks like this: class Category(models.Model): """ Model for food categories """ name = models.CharField(max_length=100) description = models.TextField(max_length=300) date_created = models.DateTimeField(auto_now=True) def __str__(self) -> str: return f"{self.name} / {self.description[0 : 50]}..." class Food(models.Model): """ Model … -
How to limit number of clients in django channels' room
I wish to limit the number of users in a room to 2 because I am making a socket game were two palyers can play a tic-tack-toe or a connect-4 game so I a trying to find some way of limiting only 2 players in one room. Down below is my comsumers.py from channels.generic.websocket import WebsocketConsumer from asgiref.sync import async_to_sync import json class GameRoom(WebsocketConsumer): def connect(self): self.room_name = self.scope['url_route']['kwargs']['room_code'] self.room_group_name = 'room_%s' % self.room_name print(self.room_group_name) async_to_sync(self.channel_layer.group_add)( self.room_group_name, self.channel_name ) self.accept() I have removed some of the less necessary methods from this question -
django database bug inccorect printing choice field
so i am trying to take data from admin panel and one field is choice field (male and female). when i registered users with female and male type in my dashboard everyone have only 1 value which is female so i need to fix it but how i dont know here is my code about views models and dashboard. models.py class Id(models.Model): first_name = models.CharField(max_length=100, null=True) CHOICES = [('Male', 'Female'), ('Female', 'Male')] gender = models.CharField(max_length=30, choices=CHOICES) def __str__(self): return self.first_name this is views def home(request): context = { 'posts': Id.objects.all(), 'title': 'Home' } return render(request, 'blog/home.html', context) def about(request): return render(request, 'blog/about.html', {'title': 'About'}) and last this is my home.html (dashboard where all my users data will showing up {% extends 'blog/base.html' %} {% block content %} {% for post in posts %} <article class="media content-section"> <div class="media-body"> <div class="article-metadata"> <a class="mr-2" href="#">{{ post.first_name }}</a> </div> <p class="article-content">{{ post.gender}}</p> </div> </article> {% endfor %} {% endblock content %} -
How to stream pdf response as file attachment?
I have a model models.py class Dibbs(models.Model): name = models.CharField(max_length=20) views.py def index(request): dibbs_obj = Dibbs.objects.all() context ={'dibbs_obj':dibbs_obj} return render(request,"index.html",context) template: {% for i in dibbs_obj %} <td data-label="name"><a href="{% url 'display_pdf' %}">{{ i.name }}</a></td> {% endfor %} There is the exact pdf file of name in the media/uploads/ folder. So, I created another view function to stream the pdf file as file response when I click on the name in the template def display_pdf(request,id): buffer = io.BytesIO() buffer.seek(0) return FileResponse(buffer, as_attachment=True, filename='') How to properly use this FileResponse function so that it opens the link of the same name? (In this case, the data that is in the name have its corresponding pdf file as name.pdf in the media/uploads/ folder)