Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Convert sql query to django orm query
i want convert query to django orm how to? select name from devices_device ORDER BY CAST(SUBSTRING(name FROM '^[0-9]+') AS INTEGER), SUBSTRING(name FROM '[^0-9].*') -
Where should I place the logic for one entity altering the state of another entity within Django REST Framework?
Imagine a simple app where user's can post some requests (for example - they need some help, food) and other users can through chat give some reply to this request. Here are my simplified models: class UserRequest(models.Model): ACTIVE = 'active' INACTIVE = 'inactive' STATUS_CHOICES = [ (ACTIVE, 'Active'), (INACTIVE, 'Inactive'), ] user = models.ForeignKey(User, on_delete=models.CASCADE) request_text = models.TextField() status = models.CharField(max_length=8, choices=STATUS_CHOICES, default=INACTIVE) class RequestChat(models.Model): user_request = models.ForeignKey(UserRequest, on_delete=models.CASCADE) class ChatMessage(models.Model): text = models.TextField() chat = models.ForeignKey(RequestChat, on_delete=models.CASCADE) I need to implement this type of functionality: When at least one chat message is created (written to chat) - the associated request status should be changed from INACTIVE to ACTIVE. Should this logic be placed in the save() method of the ChatMessage model or should it be handled using a Django signal? Or perhaps there might be another way of doing this? Additionally, can you recommend any resources such as books, articles, or videos that provide guidance on this topic? -
Django dynamically filter objects and render in template
I produced a report that provides a count of how many musicians played each genre at a festival. the musician model has a genre field that is a foreign key to the genre table. I can successfully produce a template that renders this report, but it is hard coded in a way that is not ideal. I would like to be able to have users edit the genre table without me having to edit the view and template to account for new genres. What direction can I take this where the genres played at a festival are identified dynamically, based on the musicians that played within the daterange of the festival, then passed as context to the template? See model, template, and view below: Model: class Festival(models.Model): id = models.AutoField(db_column='Id', primary_key=True, blank=True, null=False) number = models.TextField(db_column='Number', blank=True, null=True) startdate = models.DateField(db_column='StartDate', blank=True, null=True) enddate = models.DateField(db_column='EndDate', blank=True, null=True) class Meta: managed = True db_table = 'Festival' verbose_name_plural = 'Festival' class Musician(models.Model): id = models.AutoField(db_column='Id', primary_key=True, blank=True, null=False) startdate = models.DateTimeField(db_column='StartDate', null=False) enddate = models.DateTimeField(db_column='EndDate', blank=True, null=True) genre = models.ForeignKey('Genre', models.DO_NOTHING, db_column='GenreId', null=True) class Meta: managed = True db_table = 'Musician' verbose_name_plural = 'Musician' class Genre(models.Model): id = models.AutoField(db_column='Id', primary_key=True, blank=True, … -
POST data only if you are authenticated user- django rest framework
models.py class OpeningHours(models.Model): day_of_week = models.IntegerField(choices=((0, 'Sunday'), (1, 'Monday'), (2, 'Tuesday'), (3, 'Wednesday'), (4, 'Thursday'), (5, 'Friday'), (6, 'Saturday'))) opening_time = models.TimeField() closing_time = models.TimeField() serializer.py class OpeningHoursSerializer(serializers.ModelSerializer): class Meta: model = OpeningHours fields = '__all__' read_only_fields = ("user",) views.py class OpeningHoursViewSet(viewsets.ModelViewSet): queryset = OpeningHours.objects.all() serializer_class = OpeningHoursSerializer authentication_classes = [CustomAuthentication] permission_classes = [permissions.IsAuthenticatedOrReadOnly] def perform_create(self, serializer): serializer.save(user=self.request.user) authentication.py class CustomAuthentication(authentication.BaseAuthentication): def authenticate(self, request): username = request.META.get('HTTP_USERNAME') if not username: return None try: user = User.objects.get(username=username) except User.DoesNotExist: raise exceptions.AuthenticationFailed('No such user') return (user, None) I want only authenticated user to be able to perform POST method . I have set the key as HTTP_USERNAME and value as username (which i have created in django admin) on postman header before making a post request but im still getting error: "detail": "Authentication credentials were not provided." } How so i solve this. -
Advanced filtering for filtering properties in Django
Is anyone able to help me or give me some hints regarding Django? Specifically, I'm working on a real estate sales application. I'm having trouble with handling filters in the GET method as shown in the screenshot below. I've been struggling with this for over a month and still no progress! I keep deleting code because something is always not working. Basically, when selecting, for example, the 'Listing Status: Rent', there should be a reload and all properties with the 'Rent' status should be displayed. The same goes for categories, price range, etc. Furthermore, when selecting the 'Listing Status', the subsequent filters should refresh and be listed according to the displayed properties with the 'Rent' status. Meaning, when selecting the 'Rent' status, there should be a reload and all categories assigned to properties with the 'Rent' status should be displayed, and similarly for the subsequent filters. Is anyone able to help? I've been struggling with this and I'm really frustrated already 😞 enter image description here -
Django Static Files Documentation, not working, am I missing something?
I am fairly new to django and programming too. I have seen the static question asked here severally, but I have a documentation specific question. According to the official django documentation, the static files should be put inside the app folder, then create a subfolder named static, then app, then the file. for example, I have a project called Sheecooks. Inside the sheecooks, I have several django apps and among them is the nav app. so here is how i structured my css. Sheecooks > nav>static>nav>styles.css. However, my styles were not reflecting. I tried everything that has been suggested on this platform. The 'django.contrib.staticfiles'app is installed in my settings.py and yes i checked for all the spelling mistakes. I was following the documentation but changing the polls example into nav but I didn't get it to work until I removed the nav subfolder. So what I have at the moment is sheecooks>nav>static>style.css. While this works, i am afraid that the documentations states that it "it would actually be a bad idea. Django will use the first static file it finds whose name matches, and if you had a static file with the same name in a different application, Django would … -
when I wanna add order in admin panel I see this Error
My model is : class Order(models.Model): id = ShortUUIDField(primary_key=True, unique=True, length=6, max_length=6, editable=False) user = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.CASCADE, related_name='orders') orderproducts = models.ManyToManyField(Product, through='OrderProduct') total_amount = models.DecimalField(default=00.00, max_digits=10, decimal_places=2 ,blank=False) # final order price = total items quantity*total items price order_date = models.DateTimeField(auto_now_add=True, auto_now=False) finish = models.BooleanField(default=False, blank=True, null=True) country = CountryField(blank_label="(select country)", multiple=False) city = models.CharField(max_length=100, blank=False) zip_code = models.CharField(max_length=100, blank=False) state = models.CharField(max_length=100, blank=False) street = models.CharField(max_length=100, blank=False) phone_no = PhoneNumberField(null=True, blank=False) and I get this error : AttributeError at /admin/ecommerce/order/add/ 'BlankChoiceIterator' object has no attribute 'len' Request Method: GET Request URL: http://127.0.0.1:8000/admin/ecommerce/order/add/ Django Version: 5.0.2 Exception Type: AttributeError Exception Value: 'BlankChoiceIterator' object has no attribute 'len' How can I fix this Error . When I clicked add order in admin panel I get this Error . I cloned this code from github and I think it must work -
Undefined Usernames Issue in Django Channels WebSocket Consumer
I have created django consumers.py and a frontend in html and css to disply messages sent by a user, the profile picture of the sender and the username of the sender but anytime i open the browser, the message displays well but the username appears as undefined . eg @Undefined: How are you this is my consumers.py `User = get_user_model() class DiscussionRoomConsumer(AsyncWebsocketConsumer): async def connect(self): self.room_name = self.scope['url_route']['kwargs']['room_name'] self.room_group_name = f"discussion_room_{self.room_name}" # Join room group await self.channel_layer.group_add( self.room_group_name, self.channel_name ) await self.accept() # Get or create the VirtualRoom instance based on the provided room_name virtual_room = await self.get_virtual_room() if virtual_room is not None: # Send existing messages and old messages to the new user old_messages = await self.get_old_messages(virtual_room) for message in old_messages: await self.send(text_data=json.dumps({ 'message': message['content'], 'user_id': message['user'], 'user_picture': await self.get_user_profile_picture(message['user']), })) async def disconnect(self, close_code): # Leave room group await self.channel_layer.group_discard( self.room_group_name, self.channel_name ) # Receive message from WebSocket async def receive(self, text_data): text_data_json = json.loads(text_data) message = text_data_json['message'] user_id = self.scope["user"].id # Get the VirtualRoom instance based on the extracted room name asynchronously virtual_room = await self.get_virtual_room() # Check if the VirtualRoom instance exists if virtual_room: # Save message to the database with the VirtualRoom instance asynchronously await … -
```TypeError: memoryview: a bytes-like object is required, not 'bool'``` when trying to add data to my database
I have been working with Django for a while now whenever I apply this BaseModel: class BaseModel(models.Model): created_at = models.DateTimeField(auto_now_add = True) updated_at = models.DateTimeField(auto_now = True) is_active = models.BinaryField(default = True) class Meta: abstract = True to any model for example: class MyModel(BaseModel): text = models.TextField(max_length=200) and when I make migrations and migrate everything works fine and migrates go through and then I registered my models to admin site to add some data to check if my models are working and whenever I hit save to add new data I'm getting this error: nternal Server Error: /admin/ass/ass/add/ Traceback (most recent call last): File "E:\CORE\React\CinemaReservationSystem\venv\Lib\site-packages\django\core\handlers\exception.py", line 55, in inner response = get_response(request) ^^^^^^^^^^^^^^^^^^^^^ File "E:\CORE\React\CinemaReservationSystem\venv\Lib\site-packages\django\core\handlers\base.py", line 197, in _get_response response = wrapped_callback(request, *callback_args, **callback_kwargs) ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ File "E:\CORE\React\CinemaReservationSystem\venv\Lib\site-packages\django\contrib\admin\options.py", line 715, in wrapper return self.admin_site.admin_view(view)(*args, **kwargs) ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ File "E:\CORE\React\CinemaReservationSystem\venv\Lib\site-packages\django\utils\decorators.py", line 188, in _view_wrapper result = _process_exception(request, e) ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ File "E:\CORE\React\CinemaReservationSystem\venv\Lib\site-packages\django\utils\decorators.py", line 186, in _view_wrapper response = view_func(request, *args, **kwargs) ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ File "E:\CORE\React\CinemaReservationSystem\venv\Lib\site-packages\django\views\decorators\cache.py", line 80, in _view_wrapper response = view_func(request, *args, **kwargs) ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ File "E:\CORE\React\CinemaReservationSystem\venv\Lib\site-packages\django\contrib\admin\sites.py", line 240, in inner return view(request, *args, **kwargs) ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ File "E:\CORE\React\CinemaReservationSystem\venv\Lib\site-packages\django\contrib\admin\options.py", line 1944, in add_view return self.changeform_view(request, None, form_url, extra_context) ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ File "E:\CORE\React\CinemaReservationSystem\venv\Lib\site-packages\django\utils\decorators.py", line 48, in _wrapper return … -
Why is Vercel proxy to API route not working?
I have my frontend in Vite (React, TS) and backend in Django. When I make request to backend API route from frontend, it works perfectly fine with requests to the correct API route in local, but the requests are not directed to the correct API route in production. I have my frontend deployed in Vercel and backend deployed in Render. I have the following backend API routes: api/register api/login vite.config.ts import { defineConfig } from "vite"; import react from "@vitejs/plugin-react"; // https://vitejs.dev/config/ export default defineConfig({ server: { proxy: { "/api/": { target: "http://localhost:8000", changeOrigin: true, }, }, }, plugins: [react()], }); vercel.json { "rewrites": [ { "source": "/api/:path*", "destination": "https://mydomain.onrender.com/:path*" } ] } When the client makes request to api/login, the following error message is printed: XHR POST https://mydomain.vercel.app/api/login/ [HTTP/2 404 37ms] The frontend should have sent request to https://mydomain.onrender.com/api/login/ but it sends requests to the frontend route https://mydomain.vercel.app/api/login/ How to fix this? Thanks. -
The problem of not finding React static files in Python
The back end of my project is Python and I have used RteactJS for the front end. When using the python manage.py runserver command, the project runs successfully, but it does not find the static files. setting: import os from pathlib import Path BASE_DIR = Path(__file__).resolve().parent.parent STATICFILES_DIRS = [ os.path.join(BASE_DIR, '/clientApp/build/static'), ] STATIC_ROOT = BASE_DIR / "static" STATIC_URL = '/static/' url : urlpatterns = [ path('', index, name='index'), ] + static(settings.STATIC_URL, document_root=settings.STATIC_ROOT) -
Error 400: redirect_uri_mismatch when running django project
Newbie here! I want to download all the images from a google drive folder and then show them in a basic html. I am trying to authenticate with google so I can access to the folder, but when I try I always get this error (https://i.stack.imgur.com/Dl52o.png) What it's weird is that the port changes every time I run the project. (https://i.stack.imgur.com/4YQuS.png) The server is running in the port 8000 of localhost. Here the code for the views.py from django.shortcuts import render from google.oauth2.credentials import Credentials from google_auth_oauthlib.flow import InstalledAppFlow from googleapiclient.discovery import build from googleapiclient.http import MediaIoBaseDownload from google.auth.transport.requests import Request from pathlib import Path import os # Google Drive API scopes SCOPES = ['https://www.googleapis.com/auth/drive.readonly'] # Path to credentials file credentials_path = 'credentials.json' def index(request): # Load existing credentials if available if os.path.exists('token.json'): creds = Credentials.from_authorized_user_file('token.json', SCOPES) else: # If not available, initiate OAuth 2.0 flow flow = InstalledAppFlow.from_client_secrets_file(credentials_path, SCOPES) creds = flow.run_local_server(port=0) # Save the credentials for future use with open('token.json', 'w') as token_file: token_file.write(creds.to_json()) # Build the Google Drive service service = build('drive', 'v3', credentials=creds) # Google Drive folder ID folder_id = myfolderID # Create the target directory if it doesn't exist target_dir = os.path.join(Path(__file__).resolve().parent, 'images') os.makedirs(target_dir, exist_ok=True) … -
How to Create Images Dynamically Based on User Input, AI, & Images Uploaded
I want to create an app in either Python or Next.js (unless someone has a better &/or easier suggestion for how to do it?) that generates images based on a user's input from a form. I want visitors to my site to be able to generater multiple different image sizes each using the same form data entered by the user in a form. I'd also like my users to be able to choose from various options and I’mage templates, but what is the best &/or easiest way of doing this? If the project was easy enough I'd be willing to have a go at building it myself, but only if I can find the basic component features already developed to be integrated into the app. Other features I'd like to incorporate: Coupon or social share requeired to use tool User registration & the user's history of images generated with the anbility to access the images at a short link generated dynamically QR Codes generated and embedded into the generated image Ability for user to be able to upload both a picture or avatar to embed into dynamic image, and the ability to upload a custom background image to use in … -
How to connect vercel frontend deployment to backend deployed on aws ec2 instance
The backend is correctly deployed on a specific port in ec2 instance but it's http. But the frontend is deployed on vercel which uses https and I face the mixed content error. So how do I convert the backend server to https? I had trouble deploying the frontend is deployed because of the nginx configuration issues, hence why i decided to use vercel I do have a public DNS server link to this ec2 instance but its not responsive when i run Django server. I want the backend deployed to connect to the frontend either using ec2 instance or vercel. The backend deployment is working with ec2 instance but how do i connect it to frontend deployment? -
csrf error when simulating a post request in django
the form i want to simulate <form action="{% url 'reset' %}" name="form1" id="form1" method="POST"> {% csrf_token %} <div class="py-1"> <input class="focus:outline-none w-full p-1 border border-gray-300 rounded-md placeholder:font-light placeholder:text-gray-500 placeholder:text-sm pl-2" type="text" name="username" id="" placeholder="username" required> </div> <div class="flex justify-between w-full py-4"> <div class="mr-24"> <span class="text-md text-gray-400"> Dont'have an account? </span> <a class="font-bold text-black"><a href="/signup" class="font-bold">Sign up </a></span> </div> <span class="font-bold text-md"><a href="{% url 'signin' %}"class="font-bold">sign in </a></span> </div> <button class="w-full bg-black text-white p-2 rounded-lg mb-6 hover:bg-blue-400 hover:text-white " type="submit" > submit </button> </form> noting that i'm adding a form_name attribute to the post request in js before sending it document.getElementById('form1').addEventListener('submit', function(event) { event.preventDefault(); // Prevent default form submission var form = this; var formData = new FormData(form); formData.append('form_name', 'form1'); fetch(form.action, { method: 'POST', body: formData, headers: { 'X-CSRFToken': '{{ csrf_token }}' } }) .then(response => response.json()) .then(data => { if (data.show_form2) { showForm2(data); } if (data.messages) { const messages = JSON.parse(data.messages); showMessages(messages); } }).catch(error => console.error('Error:', error)); }); and the part of view that simulate the post request data = {'username': request.user.username, 'form_name': "form1"} csrf_token = get_token(request) response = requests.post('http://127.0.0.1:8000/reset', data=data, headers={'X-CSRFToken': csrf_token}) but im getting this error Forbidden (CSRF cookie not set.): /reset please help -
Unable to get submit buttons to work using the django-formset library (nothing happens upon click)
I am using the django-formset library to design an invoicing program. When I fill out a new form and click the submit button, nothing happens. I've pored over the documentation and followed the examples but no luck. Django(5.0.2) and django-formset(1.3.8) are updated. I have a few ideas what could be causing the problem and corresponding questions but am unsure how to test them out as I this is the first time I'm working with css / bootstrap / javascript / typescript (I only have a small background in Python). Does it matter whether you load scripts in the base template or child template? Do the order of scripts matter and does it matter where in the head we're loading scripts relative to other elements? A fresh set of eyes on this would be greatly appreciated because I am stuck! I get the feeling this is something very simple I'm overlooking. models.py: class Customer(models.Model): first_name = models.CharField('First Name', max_length=55, blank=True) last_name = models.CharField('Last Name', max_length=55, blank=True) phone = models.CharField('Phone Number', max_length=10, blank=True) alt_phone = models.CharField('Alt Phone Number', max_length=10, blank=True) company = models.CharField('Company', max_length=55, blank=True) email = models.EmailField('Email', null=True, blank=True) address = models.CharField('Address', max_length=55, blank=True) city = models.CharField('City', max_length=55, blank=True) state = … -
Place a media image in the template
What I want to achieve is for the user to send their image through the form and save it in a context and display it in the template class PerfilGestion(View): def get(self,request,*args,**kwargs): return render(request,"Perfil.html",{"Form":Perfil}) def post(self,request,*args,**kwargs): Formulario = Perfil(request.POST, request.FILES) if Formulario.is_valid(): Formulario.save() Imagen = Formulario.cleaned_data["Imagen"] Nombre = Formulario.cleaned_data["Nombre"] return render(request,"Perfil2.html",{"Imagen":Imagen,"Nombre":Nombre}) else: return render(request,"listadeerrores.html",{"Form":Formulario}) But I don't know how to place it in the template -
AJAX request to Django view and python print to terminal doesn't do anything
I am working on a Django website for the nonprofit. I am on the profile images part. I am trying to upload images using the image as a button to submit. I have the file chooser that opens. Then, it submits upon finishing choosing a file. It should be saving the image uploaded to the Django database. So far, my AJAX request to the Django view, its success function works correctly. However, when I try to print to the terminal my test, nothing is printed in the python terminal. Also, the image doesn't update appropriately. # source\templates\profile-pages\child-profile.html ... <script> $(document).ready(function () { if (typeof jQuery == 'undefined') { console.error('jQuery is not loaded!'); } else { console.log('jquery is loaded'); } // Get the image and input elements var imageButton = document.getElementById("image-button"); var fileInput = document.getElementById("file-input"); // Add a click event listener to the image element imageButton.addEventListener("click", function (e) { // Simulate a click on the hidden input element e.preventDefault(); fileInput.click(); }); // Add a change event listener to the input element fileInput.addEventListener("change", function (e) { e.preventDefault(); // Get the selected file from the input element var file = fileInput.files[0]; console.log(file); console.log(typeof file); // Create a URL for the file object if … -
Django WSGI and ASGI via Passenger confusion
Hi all I have a dedicated plesk server on the internet running debian 12. I've started experimenting with Django and deploying django apps via apache and Nginx. I have successfully managed to get a simple Django app to run via mod_wsgi on apache and also passenger wsgi on both apache and nginx. With mod_wsgi its clear that the Django wsgi.py file in the project is called and the apache directive simply points to that file my first confusion is with passenger and the configuration does it ignore the project wsgi.py settings completely? The second confusion starts with ASGI I thought nginx simply passes the request over to Django and python to handle like it does in WSGI but I can't get it to work I have been trying to find a simple setup for ASGI on a dedicated server but all I get is projects running the local django server. Do I need to configure nginx? should I make a file passenger.asgi.py? there is very little documentation concerning implementing it onto a running server with domains... Any ideas examples or tutorials would be much appreciated.... -
django server protection against WebSocket Flood attack
I have a django application that works as follows: the user through an ajax request uploads a file to the server for processing -> a celery task is created to process this file -> the user receives a response in the form of some unique key -> the user establishes a websocket connection with the server using of this key (the name of the room is created based on it) -> when the processing of the file is completed, the server will send a message to the room by the key and on client whe he received the message then connection will be closed. The url for connecting via websocket connection looks like this - ws/download_result/<str:key>/ I also store the keys by which the websocket connection is established in the database, and therefore when someone tries to establish a third-party connection (if he was not on the site and did not give the file for processing and accordingly there is no key - because with each file processing a new key is created - for in order to be able to connect to the server through it and get a result) then I can check whether such a key exists … -
Filtering with AJAX in Django
In my Django project, I have a basic view where I pass all instances of the Article model and then display them in an HTML template with a for loop. I also have a Topic model, so I display all topics as buttons, also with a for loop. My goal is to filter articles by clicking a specific Topic button, so if I click "Politics," for example, then only articles connected to the "Politics" topic will be displayed instead of all articles. I want to use an AJAX request for this, but I do not have experience with it, so I am having some problems figuring out how to achieve my goal. Here is my view. I am trying to do AJAX in the same view, but I am not sure if this is correct because, in most cases that I saw, a separate view was created: def main_view(request): all_articles = Article.objects.all()[::-1] top_articles = all_articles[:10] topics = Topic.objects.all() if request.is_ajax(): topic_name = request.GET.get('topic_name') all_articles = Article.objects.filter(topics=topic_name) return JsonResponse({'all_articles': all_articles}) return render(request, "mainapp/main_refactor.html", {"all_articles": all_articles, "top_articles": top_articles, "topics": topics}) Simplified HTML template: {% for topic in topics %} <button class="topic-button" data-url="{% url 'mainapp:filter_articles' topic.name %}" data-topic-name="{{ topic.name }}">{{ topic.name }}</button> {% … -
Bar Chart Not Stacking
I have been trying to adapt this tutorial, How to Use Chart.js with Django, to my AWS billing reports. I want to tweak this graph from the tutorial: I want to "stack" the costs from the various AWS services for each month, but when I tried to stack the cost I get this chart: Here is the pertinent code I have written: monthly_cost/views.py: from django.shortcuts import render from django.db.models import Sum from rest_framework import viewsets from django.http import JsonResponse from .models import MonthlyCostReport from .serializers import MonthlyCostReportSerializer def home(request): return render(request, 'home.html') def product_cost_chart(request): colors = ['#DFFF00', '#FFBF00', '#FF7F50', '#DE3163', '#9FE2BF', '#40E0D0', '#6495ED', '#CCCCFF', '#9CC2BF', '#40E011', '#641111', '#CCCC00'] labels = [label.get('bill_billing_period_start_date').strftime('%Y-%m-%d') for label in MonthlyCostReport.objects.values('bill_billing_period_start_date').order_by( 'bill_billing_period_start_date').distinct()] datasets = [] for i, product_cost_pair in \ enumerate(MonthlyCostReport.objects.filter(bill_billing_period_start_date=labels[0]).values( 'line_item_product_code').annotate(product_cost=Sum('line_item_blended_cost')).order_by( '-product_cost')): dataset = { 'label': product_cost_pair.get('line_item_product_code'), 'backgroundColor': colors[i % len(colors)], 'data': [pc.get('product_cost') for pc in MonthlyCostReport.objects \ .filter(line_item_product_code=product_cost_pair.get('line_item_product_code')) \ .values('line_item_product_code', 'bill_billing_period_start_date') \ .annotate(product_cost=Sum('line_item_unblended_cost')).order_by('bill_billing_period_start_date')] } datasets.append(dataset) return JsonResponse(data={ 'labels': labels, 'datasets': datasets, }) templates/home.html {% block content %} <div id="container" style="width: 75%;"> <canvas id="product-cost-chart" data-url="{% url 'product-cost-chart' %}"></canvas> </div> <script src="https://code.jquery.com/jquery-3.4.1.min.js"></script> <script src="https://cdn.jsdelivr.net/npm/chart.js@2.9.3/dist/Chart.min.js"></script> <script> $(function () { var $productCostChart = $("#product-cost-chart"); $.ajax({ url: $productCostChart.data("url"), success: function (data) { console.log(data); var ctx = $productCostChart[0].getContext("2d"); new Chart(ctx, … -
What is the most appropriate way to organize files in Django?
What is the best in django? Should there be a main CSS file for all HTML page files, or should each HTML file have a special CSS file, as well as for JavaScript files in terms of performance? I am a beginner in learning Django and I do not know what is the most appropriate method or the recognized method. -
In Django how to bulk_create with a model that has a file field?
I have a model Document: class Folio(): status = models.OneToOneField(Status, on_delete=models.CASCADE, verbose_name='current status*') file = models.FileField( upload_to=create_route_file, verbose_name='PDF*', help_text='Format PDF' ) I need to create objects of it with bulk_create(), to make it with few queries. I am trying to create objects first with simple Folio() and Status(), putting them into a list and then saving it with bulk_create: status = Status() document_parameters = { 'status': status, ... } document = Document(**document_parameters) file = custom_open_file_function(route_to_file) file_name = 'name...' file.file.save(file_name, File(file)) That last line raise this error: ValueError: save() prohibited to prevent data loss due to unsaved related object 'status'. I don't wanna to do a save() there because that integrity problem with Status and because I don't want to do a query there. All the objetive with bulk_create is to do just one query to statuses and one query for documents, avoiding doing one query per document. But I don't know how to deal with that FileField. -
Python Django UpdateView: 404 not found
I'm using the built in class based views, in this case the UpdateView. The documentation doesn't give any hints towards how the urls.py must look like. Which url pattern is matched by that generic view, so that I can update a particular object (e.g. with id 1 in the database)? I tried: path("myroute/<int:pk>/", views.myUpdateView.as_view(), name="myname") The view behind views.myUpdateView is a django.views.generic.edit.UpdateView and when I navigate to let's say myroute/1/ I get a 404 error. How am I supposed to use that generic view? I was just guessing that it must somehow fetch the pk parameter from my URL, but I see no documentation for that part? Sorry for not including the template ecetera, but it's not really needed here because my question is so simple: which url pattern(s) is (are) processed by the UpdateView? Did I overlook something in the documentation? Thank you in advance!