Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Deploying the Django project in IIS
I'm having trouble deploying my Django project on IIS. I'm getting a 500 error, and it says that the FastCGI is either not pointing to the right place, is misconfigured, or the settings file might be incorrect. I'm having a hard time figuring out where the problem is. Could you guide me towards some concrete examples or tell me exactly what I need to do? I'm trying to deploy the Django project through the IIS, and I expect to be able to display my app through a web browser. -
Why is nothing displayed on the page in Django?
Here's a question, I have products on a page and each product has its own slug. This slug redirects to the personal page of the product, which displays all the necessary information about the product (name, description, images, etc). But for some reason the page is just empty, i.e. what is written in the html file is not displayed and I don't understand why. The redirect is error free and the product slug appears in the url, but there is no product information. P.s in the view, I use print to see in the terminal if I actually go to the product page and get the product name. And yes, I do get it in the terminal views.py def product_detail(request, post): product = get_object_or_404(ProductModel, slug=post) print(product.title) return render(request, 'products/detail-products.html', { 'product': product, }) urls.py from django.urls import path from products import views app_name = 'products' urlpatterns = [ path('', views.products, name='products'), path('product/<slug:post>/', views.product_detail, name='product_detail'), ] product-detail.html {% extends 'main/base.html' %} {% block title %}Detail {{ product.title }}{% endblock title %} {% block content %} <style> .product__detail__photo img { width: 60%; height: auto; background-size: cover; object-fit: cover; border-radius: 5px; } </style> <div class="product__detail"> <div class="product__image"> {% if product.product_images %} <img src="{{ … -
How do I successfully integrate Django and Flowbite framework
I followed the entire documentation of integrating Django and Flowbite on Flowbite's official site. Just when I thought I i successfully integrated the two frameworks, I noticed some flowbite components are not displaying the way they are supposed to. But for some components yes, the styling are working. This is causing me headache because the dashboard is among the components which are not displaying the way they're supposed to. But then the dashboard was set to be part of my main site. What might be the problem? Is there any straight forward procedure i can follow to achieve this integration? I tried using CDN, but it is causing issues to the functionalities of changing the site's background -
Django: count duoble nested revers Foreignkey
my models: class Course(models.Model): ... class Section(models.Model): course = models.ForeignKey(Course, on_delete=models.CASCADE, related_name='sections') ... class SubSection(models.Model): section = models.ForeignKey(Section, on_delete=models.CASCADE, related_name='subsections') registration_required = models.BooleanField(default=True) now I want to know if less than 5 subsections of a course are registration_required = False. something like: def validate(self, attrs): course = self.instance if course.sections.subsections.filter(registration_required=False).count() < 5: # do something ... what is the best way to do that ?? -
How to Retrieve Nested Form-Data in Django Rest Framework?
postman data I send this form-data in postman but request.data empty my code: class DentalClientMedicalRecordCreateAPIView(APIView): def post(self, request, *args, **kwargs): try: print(request.data) branch = request.user.branch data = request.data # Extract nested data tooth_service_data = request.data.get('tooth_service', []) print(tooth_service_data) response how to I get this multiple related entries -
Trying to match Django template table headers with values in columns when there are missing cell values
I have a Player model, an Event model, and a Pick model. Theoretically, a Player should submit a Pick for each Event, but this doesn't always happen and there may be times when a Pick is not yet submitted but will be in the following days. I have a table displaying each Player's Picks for each Event. Table header row loops through Events, then I have a regroup and loop through each Player's Picks for each table row. Below is an image of how I'd like it work. When a Pick is missing, don't print a Pick value, but skip that cell (or show a useful message to the Player): My template is pasted below, but when a Pick is missing, there aren't enough items in the queryset to match the number of table headers, and since template language is intentionally a bit naive (ie I can't break a loop, or do some other features) I am having difficulty coming up with a way to arrange this template so that an empty table cell is added. This is what my table resembles - Player 2's picks are out of alignment. The orange cells don't match the header Event, and the … -
How to resolve the error Method Not Allowed (POST) in Django?
I'm creating a POS application in Django. Currently I'm using the template bellow for adding items to a current order, modifying quantities, deletes some items that are unecessary to be in the current order, and finaly, after adding all needed items, to click on the Checkout button for validation. {% load multiply %} <!DOCTYPE html> <html> <head> <title>Order Details</title> <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0/css/bootstrap.min.css"> <script src="https://code.jquery.com/jquery-3.2.1.min.js"></script> </head> <body> <nav class="navbar navbar-expand-lg navbar-light bg-light"> <a class="navbar-brand" href="{% url 'posApp:home' %}">POS System</a> <button class="navbar-toggler" type="button" data-toggle="collapse" data-target="#navbarNav" aria-controls="navbarNav" aria-expanded="false" aria-label="Toggle navigation"> <span class="navbar-toggler-icon"></span> </button> <div class="collapse navbar-collapse" id="navbarNav"> <ul class="navbar-nav"> <li class="nav-item"> <a class="nav-link" href="{% url 'posApp:category_list' %}">Categories</a> </li> <li class="nav-item"> <a class="nav-link" href="{% url 'posApp:order_list' %}">Order list</a> </li> <li class="nav-item"> <a class="nav-link" href="{% url 'posApp:create_order' %}">Create Order</a> </li> <li class="nav-item"> <a class="nav-link" href="{% url 'posApp:add_category' %}">Add Category</a> </li> <li class="nav-item"> <a class="nav-link" href="{% url 'posApp:product_list' %}">Products list</a> </li> <li class="nav-item"> <a class="nav-link" href="{% url 'posApp:add_product' %}">Add Product</a> </li> </ul> </div> </nav> <div class="container mt-5"> <h1>Order {{ order.id }}</h1> <div class="row"> <div class="col-md-6"> <form id="add-item-form" method="post"> {% csrf_token %} <div class="form-group"> <label for="barcode">Barcode</label> <input type="text" class="form-control" id="barcode" name="barcode" placeholder="Enter Barcode" required> </div> <div class="form-group"> <label for="quantity">Quantity</label> <input type="number" class="form-control" id="quantity" name="quantity" placeholder="Quantity" min="1" value="1" … -
how to inert (not update) into a table on conflict by generating a new primary key
Currently I have two postgresql tables table1 and table2, shown below, primary key is id. table1: id | name ---------- 1 | Bob 3 | Steven table2: id | name ---------- 2 | John 3 | Jack I would like to combine these two tables by inserting table2 to table1, and table1 should look like below after the operation. Essentially, it can maintain the same primary key if there is no conflict, but when it has conflict, it will generate a new id for the incoming data from table2, and insert that as a new row in table1. In this example, Jack from table2 will be inserted as a new row with a new id of 4 (max id from table1 + 1). id | name ---------- 1 | Bob 2 | John 3 | Steven 4 | Jack Below is my current approach. Which updates the id in conflicted row in table1. INSERT INTO table1 (id, name) SELECT id, name FROM table2 ON CONFLICT(id) DO UPDATE SET id=nextval(pg_get_serial_sequence('table1', 'id')); I need help figuring out how to insert into a new role with a new id. -
django tenant local and server resolve problem
hello i develop django tenant app in localhost when i request to ebsalar.localhost:8000 every think is ok but when upload on server and use curl to check i got Could not resolve host: ebsalar.localhost local: on server: note: /etc/hosts same ... need run the same in server and local -
jQuery editable-select : validate option that is not in the list
In Django, I'm using jQuery editable-select to convert selectboxes to searchable selectboxes. https://github.com/indrimuska/jquery-editable-select/blob/master/README.md I'm searching for a way to save the value entered in the search field if it's not one of the options listed in the original dropdown list (as if it was a regular charfield) For now, If I'm saving the django form with a value not in the list, the form doesn't save and return error. Is there a way to force the saving of the form with the value entered in the widget field ? form.py class forms_bdc(forms.ModelForm): [...] bdc_description_1 = forms.ChoiceField(required=False,choices=list(models_products.objects.values_list( 'product_denomination','product_denomination')),widget=forms.Select(attrs={'id': 'bdc_editable_select_description_1','style': 'width:200px','onchange': 'populate_selected_product(this.id,this.value)'})) template.html <div style="width: 200px;">{{ form5.bdc_description_1 }}</div> #script that convert regular dropdown to editable-dropdown and trigg a function called 'populate_selected_product' <script> var selectedIDs = ['bdc_editable_select_description_1','bdc_editable_select_description_2','bdc_editable_select_description_3','bdc_editable_select_description_4','bdc_editable_select_description_5']; for (let i = 0; i < selectedIDs.length; i++) { $('#'+selectedIDs[i]).editableSelect({ effects: 'fade' }).on('select.editable-select', function (e, li) { populate_selected_product($('#'+selectedIDs[i]).attr('id'),li.text()) }); } </script> -
Django MQTT Subscriber save to database and update view
I am creating a live dashboard for race data where timings and other information will be published by multiple clients on a per lap basis. I am using Mosquitto as my broker. Guided by this solution I am able to subscribe to the different topics amd see the published results. on_message received from lap_data QOS:0 retain:False - `{"LapCompleted": 32 ... }` on_message received from weather_data QOS:0 retain:False - `{ "RelativeHumidity":0.449} I have completed the channels chat tutorial and have Redis running on WSL. Now, I would like to: add the received messages to the database update the view when a message is recieved. I hoped to me able to add records via the on_message_callback but when I try to import the models into my MQTTClient.py file I get the following error: raise AppRegistryNotReady("Apps aren't loaded yet.") django.core.exceptions.AppRegistryNotReady: Apps aren't loaded yet. If anyone was able to point me in the right directions for 1 & 2 I would be grateful. Thank you. MQTT is started via the app ready function def ready(self): if os.environ.get('RUN_MAIN'): mqtt_client = MqttRemote() mqtt_client.start() -
How do I add a Multilevel dropdown to a Django template?
I am trying to add a dropdown to my navbar in base.html that shows multiple categories from a store. Each of these categories has a sub-category associated with it. I've created a model in Django that maps this relationship like so. models.py class CategoryView(models.Model): parent = models.ForeignKey('self', related_name='children', on_delete=models.CASCADE, blank = True, null=True) title = models.CharField(max_length=100) created_at = models.DateTimeField(auto_now_add=True) def __str__(self): return self.title And I'm passing this model to the template using context processors as so def categoriesdropdown(request): catg = CategoryView.objects.filter(parent=None) context = {'catg':catg} return context Now I am trying to display these categories and sub-categories as a multilevel dropdown using bootstrap. I have tried implementing mostly all solutions from the answers here: Bootstrap 4: Multilevel Dropdown Inside Navigation Bootstrap dropdown sub menu missing https://mdbootstrap.com/docs/standard/extended/dropdown-multilevel/ But nothing seems to work. Below is the dropdown from my template. base.html <div class="nav-item dropdown"> <a href="#" id="dropdownMenuLink" data-toggle="dropdown" aria-haspopup="true" aria-expanded="false" class="nav-link dropdown-toggle">Categories</a> <ul class="dropdown-menu dropdown-menu2" aria-labelledby="dropdownMenuLink"> {% for category in catg %} <li class="dropdown-submenu"> <a class="dropdown-item dropdown-toggle" href="#" id="multilevelDropdownMenu1" data-bs-toggle="dropdown" aria-haspopup="true" aria-expanded="false">{{ category.title }}</a> <ul class="dropdown-menu2" aria-labelledby="multilevelDropdownMenu1"> {% for subcategory in category.children.all %} <li><a href="#" class="dropdown-item">{{ subcategory.title }}</a></li> {% endfor %} </ul> </li> {% endfor %} </ul> I can see that all the … -
redirect to normal django view after logging in using DRF api
I get this in my console whenever i log in, it logs in successfully, api returns 200 but then when it tries redirecting to the dashboard view, it returns 302 and redirects to the login page [09/Aug/2024 18:17:04] "GET /static/js/login.js HTTP/1.1" 200 2297 [09/Aug/2024 18:17:24] "POST /api/v1/token/login HTTP/1.1" 200 70 [09/Aug/2024 18:17:25] "GET /dashboard/ HTTP/1.1" 302 0 [09/Aug/2024 18:17:25] "GET /accounts/login/?next=/dashboard/ HTTP/1.1" 200 1451 [09/Aug/2024 18:17:25] "GET /static/js/login.js HTTP/1.1" 304 0 [09/Aug/2024 18:18:46] "GET /accounts/login/?next=/dashboard/ HTTP/1.1" 200 1451 below is my login api which authenticates the user trying to log in import json from rest_framework.decorators import api_view,permission_classes from rest_framework.response import Response from rest_framework.permissions import IsAuthenticated, AllowAny from rest_framework import status from core.models import Order, Laundry from .serializers import OrderSerializer, SignUpSerializer from django.views.decorators.csrf import ensure_csrf_cookie,csrf_exempt, csrf_protect from rest_framework.authtoken.models import Token from django.contrib.auth import authenticate,logout, login,get_user_model @api_view(['POST']) @permission_classes([AllowAny]) @ensure_csrf_cookie def user_login_token(request): """user login api""" if request.method == 'POST': email = request.data.get('Email') password = request.data.get('Password') current_user = authenticate(request, username=email, password=password) if current_user: login(request, current_user) token, created = Token.objects.get_or_create(user=current_user) response = Response({'token': token.key, 'SuperRole': current_user.is_superuser}, status=status.HTTP_200_OK) return response return Response({'error': 'Invalid credentials'}, status=status.HTTP_400_BAD_REQUEST) this is my code listening for when the user submits the form (clicks the login button) const loginForm = document.querySelector('form'); loginForm.addEventListener('submit', … -
How i learn django framework and which topic is important in django?
I'm completely beginner. I have little bit knowledge of django. Like how to create form and how to save into n database.and login and sigin I'm completely beginner. I have little bit knowledge of django. Like how to create form and how to save into n database. -
Which backend framework should we use for faster performance on very large database (e.g. Hospital Data)?
I am confused on which backend framework should we use for faster performance and response of APIs when we have a very large database. I have been using Django with MongoDB, but I could just say the API responses are very late. When I try to filter something it may take around 6-7 seconds for the response to come. -
in cmd when i create virtual env it gives no error but where i created there is no directory or folder of virtualenv
in conamd promp i see this but no folder of virtual env and from my all older projects virtualenv directory is vanished mkvirtualenv nameenv these are version outputs virtualenv --version gives this virtualenv 20.26.3 from C:\Users\aneesRiazChaudhary\AppData\Local\Programs\Python\Python312\Lib\site-packages\virtualenv_init_.py Python version 3.12.5 django-admin --version 5.0.7 -
Saving self generated image in django models.ImageField
I have a method generate_certificate(), that uses a base image from default storage in django and edits it through pillow library and saves that image to the default djnago storage and returns file path. def generate_certificate(name, certification): base_image_path = os.path.join(settings.MEDIA_ROOT, 'certificates', 'Certificate.png') font_path = os.path.join(settings.MEDIA_ROOT, 'fonts', 'font.ttf') if not os.path.exists(base_image_path): raise FileNotFoundError(f"Base certificate image not found at {base_image_path}") img = Image.open(base_image_path) d = ImageDraw.Draw(img) location = (143, 155) text_color = (100, 100, 100) font = ImageFont.truetype(font_path, 40) d.text(location, name, fill=text_color, font=font) location = (360, 215) font = ImageFont.truetype(font_path, 18) d.text(location, certification, fill=text_color, font=font) location = (200, 310) font = ImageFont.truetype(font_path, 15) d.text(location, '2024-08-07', fill=text_color, font=font) file_name = f"{name.split(' ')[0]}_{random.randint(0, 255)}.png" file_stream = BytesIO() img.save(file_stream, format='PNG') file_stream.seek(0) # Save the file to the media directory and return the relative path file_path = default_storage.save(f'certificates/{file_name}', ContentFile(file_stream.read())) return file_path # Return the relative path I am using this method in a post method view that creates a record for UserCertification model. The request payload has the all the data except the image which is generated in the view. as below: def post(self, request): try: user = request.data.get('user') certification = request.data.get('certification') score = request.data.get('score') certificate_url = generate_certificate(user, certification) print(f"Generated certificate file path: {certificate_url}") # Debugging … -
When hosting my page, websockets not workign
I'm working on a game that consists of a musical bingo. The frontend is built in ReactJS and is hosted on Vercel using the Free tier. The backend is a Django app hosted on a Render web service. I've successfully made them communicate with each other using the correct URLs provided by these hosting services. However, I need help with WEBSOCKETS, as the wss URLs don't seem to be working. The game works like this: on the home page, the musicals are drawn using a simple "Play" button and it calls the api and returns one of the 14 musical options, and the users generate a bingo card by entering their name and getting a unique combination of 4 musicals. As musicals are drawn on the main screen, I used websockets to update the bingo cards so that the squares are marked accordingly. However, now that I've hosted everything, it's not working. Thanks for reading! I´ve tried using render redis database service but i dont know how to configure it to work with this one. Idk what else can i do as this is my first time working with these -
Django how to sort by fields that don't exist
Currently, I have two models posts.models from django.db import models from django_prometheus.models import ExportModelOperationsMixin from users.models import User from category.models import Category # Create your models here. class Post(ExportModelOperationsMixin('post'), models.Model): header_image = models.ImageField(default='ancean-no-header-image.png') title = models.CharField(max_length=100) introduce = models.TextField(default='') content = models.JSONField('json', null=True, blank=True) author = models.ForeignKey(User, on_delete=models.CASCADE, db_column="author", related_name='author') category = models.ForeignKey(Category, on_delete=models.SET_NULL, db_column="category", related_name='category', null=True, blank=True) wave = models.IntegerField(default=0) # wave field like 'like post' on general SNS created_at = models.DateTimeField(null=True) updated_at = models.DateTimeField(auto_now=True) is_finish = models.BooleanField(default=False) is_public = models.BooleanField(default=False) def __str__(self): return f'{self.title} - {self.author}' category.models from django.db import models class Category(models.Model): name = models.CharField(max_length=30, unique=True) def __str__(self): return f'{self.name}' I want to create a logic that gets the number of posts per category and sorts them in descending order. "http://localhost:8000/api/category?ordering=-post_count" Through the url as above I want to make it like the result of this query. SELECT c.name, count(*) AS post_count FROM category_category c JOIN posts_post p ON (c.id = p.category) GROUP BY p.category ORDER BY count(*) DESC I want to use Django ordering, but post_count is a non-existent field(Category model), so I can't use it. I'd appreciate it if you could tell me a good way. category.views class CategoryView(GenericAPIView, ListModelMixin): queryset = Category.objects.all() serializer_class = … -
Unable to install django in virtualenv
Unable to load django in virtualenv. "pip install django" is running indefinitely In VScode (just in case it matters) I create a virtual environment and try to install django, here is the sequence of actions: virtualenv myenv myenv\Scripts\activate pip install django Last operation not completed however long I wait (screenshot) enter image description here Without a virtual environment everything is installed perfectly. -
As I am trying to use REST API to PUT method and I get 500 Internal server error? [closed]
As I am trying to build a get, post, delete, and put methods in REST API Developed with Django. The Django is connected with Angular with help of Djongo(For the need of MongoDB). Everything work fine except the put method when I use put method I get "Internal Server error 500" And here's my code Angular component: @Component({ selector: 'app-edit', standalone: true, imports: [SharedModule, CommonModule, HttpClientModule], templateUrl: './edit.component.html', styleUrl: './edit.component.scss' }) export class EditComponent { name : string = '' mobilenumber : string = '' emailid : string = '' id : string = '' constructor(private http : HttpClient){} edit() { const temp = { id: this.id, name: this.name, mobilenumber: this.mobilenumber, email: this.emailid }; const url = `http://127.0.0.1:8000/call/${this.id}`; this.http.put(url, temp).subscribe( response => console.log("Edited", response), error => console.error("Error", error) ); } } When I go to the url : http://127.0.0.1:8000/call I get "Allow: GET, POST, HEAD, OPTIONS" is the put method even allowed. If allowed how do I resolve it? Please help me with my code -
Adding new row to the Django template table
I have a simple table generated from Django template variable: {% for object in object_list %} <tr> <td class="c9">{{object.first_name}}</td> <td class="c9">{{object.last_name}}</td> <td class="c9">{{object.tel}}</td> </tr> {% endfor %} I'm making insert to this model and the server side is done, but how to add a new row in top of this table? With this method: var row = table.insertRow(0)? or can I change this variable 'object_list' and row will be added automatically? This simple solution 'var row = table.insertRow(0);' is not adding columns with CSS classes. -
Django project use "python manage.py migrate" show stderr
environment Python 3.11.7 package:asgiref==3.8.1Django==5.1psycopg2==2.9.9sqlparse==0.5.1tzdata==2024.1 this is my models.py code from django.db import models class User(models.Model): user = models.CharField(blank=False) password = models.CharField(max_length=64) group_id = models.SmallIntegerField() email = models.EmailField(unique=True, null=True) create_time = models. DateTimeField(auto_now_add=True) class working_hours(models.Model): working_choices = { 'morning': "Options1", 'noon': 'Options2', 'eveing': 'Options3', 'befor dawn':'Options4', } ordinary = models.BooleanField(default=True) time_start = models.TimeField() time_end = models.TimeField() working = models.CharField(blank=False, choices= working_choices) the command execute python .\manage.py makemigrations polls no problem but then use python manage.py migrate File "D:\public_cloud_site\mysite\manage.py", line 22, in <module> main() File "D:\public_cloud_site\mysite\manage.py", line 18, in main execute_from_command_line(sys.argv) File "D:\public_cloud_site\venv\Lib\site-packages\django\core\management_init_.py", line 442, in execute_from_command_line utility.execute() File "D:\public_cloud_site\venv\Lib\site-packages\django\core\management_init_.py", line 436, in execute self.fetch_command(subcommand).run_from_argv(self.argv) File "D:\public_cloud_site\venv\Lib\site-packages\django\core\management\base.py", line 413, in run_from_argv self.execute(*args, **cmd_options) File "D:\public_cloud_site\venv\Lib\site-packages\django\core\management\base.py", line 459, in executeoutput = self.handle(*args, **options) ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ File "D:\public_cloud_site\venv\Lib\site-packages\django\core\management\base.py", line 107, in wrapperres = handle_func(*args, **kwargs) ^^^^^^^^^^^^^^^^^^^^^^^^^^^^ File "D:\public_cloud_site\venv\Lib\site-packages\django\core\management\commands\migrate.py", line 118, in handle executor = MigrationExecutor(connection, self.migration_progress_callback) ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ File "D:\public_cloud_site\venv\Lib\site-packages\django\db\migrations\executor.py", line 18, in initself.loader = MigrationLoader(self.connection) ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ File "D:\public_cloud_site\venv\Lib\site-packages\django\db\migrations\loader.py", line 58, in initself.build_graph() File "D:\public_cloud_site\venv\Lib\site-packages\django\db\migrations\loader.py", line 235, in build_graph self.applied_migrations = recorder.applied_migrations() ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ File "D:\public_cloud_site\venv\Lib\site-packages\django\db\migrations\recorder.py", line 90, in applied_migrations return { ^ File "D:\public_cloud_site\venv\Lib\site-packages\django\db\models\query.py", line 400, in iterself._fetch_all() File "D:\public_cloud_site\venv\Lib\site-packages\django\db\models\query.py", line 1928, in _fetch_allself._result_cache = list(self._iterable_class(self)) ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ File "D:\public_cloud_site\venv\Lib\site-packages\django\db\models\query.py", line 91, in iter results = compiler.execute_sql( … -
How to perform left join and select a flag if fields exist on right table in django
I have article and bookmark tables and i want to fetch articles while getting is_bookmarked flag if the user has bookmarked the article. Article table has all the meta data related to the article and the bookmark table has user and article columns to maintain which user has bookmarked which article i.e Consider Bookmark table with columns article_id and user_id and a combined unique constraint of these. SELECT a.id AS article_id, a.title, (b.article_id IS NOT NULL) AS is_bookmarked FROM article_article a LEFT OUTER JOIN article_bookmark b ON a.id = b.article_id AND b.user_id = 1 Now i want to replicate this sql query to an django orm query, i don't want to use CASE or exists, and i'm unable to replicate this query just because of the is_bookmarked flag. I've tried FilteredRelations but couldn't get the query replicated. -
convert PMG file to PNG in python django
how to convert pmg files to png file format in python django