Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
How to fetch different data into different sections in html ? (DJANGO)
I have a page on which there are different bootstrap accordians, i have different models stored in the database, Now i want to fetch them in a proper order ? class CaseStudy_list(models.Model): CaseStudy_id = models.IntegerField(primary_key=True) title = models.CharField(max_length=255) def __str__(self): return self.title class CaseStudy_parts(models.Model): #accordians case_study = models.ForeignKey(CaseStudy_list, on_delete=models.CASCADE) CaseStudy_part_id = models.AutoField(primary_key=True) CaseStudy_order = models.IntegerField(default="") CaseStudy_title_accordian = models.CharField(max_length=255) def __str__(self): return self.CaseStudy_title_accordian class CaseStudy_content(models.Model): #column 1 - text area case_study = models.ForeignKey(CaseStudy_list, on_delete=models.CASCADE) content_title = models.CharField(max_length=255, default="") content_text = models.TextField(blank=True) content_link = models.TextField(blank=True) def __str__(self): return self.content_title class CaseStudy_Media(models.Model): #column 2 - Media Area case_study = models.ForeignKey(CaseStudy_list, on_delete=models.CASCADE) content_img = models.ImageField(upload_to='casestudy/images', default="") class CaseStudy_buttons(models.Model): content = models.ForeignKey(CaseStudy_content, on_delete=models.CASCADE) button_id = models.CharField(max_length=255) button_label = models.CharField(max_length=255) <div class="page-layout"> <div class="accordion" id="accordionPanelsStayOpenExample"> <div class="accordion-item"> <h6 class="accordion-header"> <button class="accordion-button" type="button" data-bs-toggle="collapse" data-bs-target="#panelsStayOpen-collapseOne" aria-expanded="true" aria-controls="panelsStayOpen-collapseOne"> {{content.section_title}} </button> </h6> <div id="panelsStayOpen-collapseOne" class="accordion-collapse collapse show"> <div class="accordion-body"> <div class="container-area"> <div class="col-content"> <div class='introduction-content'> <h3>CASESTUDY ID - {{casestudy_obj.id}} </h3><br> <h3>TITLE - {{ casestudy_obj.title }} </h3> <br> <h3>OBJECTIVE - {{content.content_text}}</h3> </div> </div> <div class="col-data"> <img src="{{content.content_img.url}}"> </div> </div> </div> </div> </div> <div class="accordion-item"> <h2 class="accordion-header"> <button class="accordion-button collapsed" type="button" data-bs-toggle="collapse" data-bs-target="#panelsStayOpen-collapseTwo" aria-expanded="false" aria-controls="panelsStayOpen-collapseTwo"> DATA COLLECTION </button> </h2> <div id="panelsStayOpen-collapseTwo" class="accordion-collapse collapse"> <div class="accordion-body"> <div class="container-area"> <div class="col-content"> <div class='introduction-content'> … -
Django sorting by Date, Name
I am new in Django, and I want to sort my querys by date or name. I did it but I additonally want to do an option to change it on website. I coudln't find an answer anywhere how to do it. Am I going wrong way? I tried do do it like that: {% block content %} <h1 class="tytul">Lokalizacja plików</h1> <div class="naglowek"> <div class="card card-body"> <p>Wyszukaj plik</p> <form method="get">{{myFilter.form}} <button class="button" type="submit"> Wyszukaj </button> </form> <div class="sortowanie">Wybierz po czym sortować: <select class="sort"> <option>Nazwa</option> <option>Data</option> </select> </div> </div> </div> HTML {% for plik in obj %} <div class="row"> <div class="com"> {{plik.nazwa}} </div> <div class="com"> {{plik.data}} </div> <div class="com"> {{plik.lokalizacja}} </div> <div class="przy"> <a href="{% url 'download' plik.lokalizacja %} " class="button">pobierz</a> </div> </div> {% endfor %} </div> {% endblock %} I am trying to do and option to change sorting by date and name by user -
Django App with Automation File Upload from user local system
I want to create a website based on python and django in backend and bootstrap, css, jquery and javascript in the frontend, the functionality will be like user will provide a "Source_Path" from his local system irrespective of the os used by the user, it will upload all the files from that folder in our django project! Is this possible? Can we make this automation I have tried using os it is working in my local, but in production it is not working! I have deployed using apache2 web server. Any suggestion can help! -
Raise Validation error in the forms.py when the header/row is empty or not correct wording
I have been trying to solve this issue for a while and am stumped, this issue is a bit unique in a sense that the csv file that I am checking the header for is from a file upload in the forms.py. What I mean is that the csv file being checked does not exist in any directory so you can't just open a specific file, just from my research of other solutions, they all seem to be about an existing file in a directory rather than a file upload. So, the header must = "IP Address", and the form will submit without an issue, when the file header is equal to " " or != "IP Address", when the form gets submitted the Django debug window comes up. I am struggling with inputting a validation error or implementing a redirect. If you have any useful links, documentation, or would like to solve, please feel free I would appreciate it a lot. import csv import io import pandas as pd from typing import Any from django import forms from django.core.exceptions import ValidationError from django.core.validators import FileExtensionValidator from api.utils.network_utils import NetworkUtil from .models import BlockedList forms.py class CSVForm(forms.Form): csv_file = forms.FileField(required=True, … -
NoReverseMatch error when trying to make a Django Python website
i don't really know what im doing so i'll provide as much context as i can lol. Have to make a "business solution" for school and wanted to do a website built with django as i kind of know a bit about python. Made a design using figma, used some ai tool to convert that into html/css code. Moved that all over to python and initially the website had some functionality, the index page looked as it should've looked and there were buttons, but as soon as i tried adding functionality to the buttons my site kind of died. After starting the website locally instead of seeing anything i get a NoReverseMatch error. Updated views.py and urls but still can't figure out what the overall issue is, and i presume this issue will be persistent with every other button until i can nail exactly why it's not working. Attached is the error, my directory, views.py code, urls.py code, and html code. images Again i don't really know what im doing so i just asked chatgpt, lead me around in circles and never went anywhere lol -
Django admin panel not loading css/js on digitalocean server
Running into a problem where in my localhost things are working great with this structure: localhost But on digitalocean server I got this structure: server Notice how on the server I got an extra static folder called 'staticfiles'. On my localhost it's working great but at the server level my admin panel can't seem to find the right css/js because it is looking for the files inside the static folder. These are my settings file: `BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(file))) STATIC_URL = '/static/' STATIC_ROOT = os.path.join(BASE_DIR, 'staticfiles') STATICFILES_DIRS = [ os.path.join(BASE_DIR, 'static'), ]` I am not using a droplet but the app platform option. Any ideas to help me? -
How to connect Django with mongodb Atlas
I'm creating a Django connection with mongodb Atlas, but I get the following error message when using the makemigrations command: django==4.0 Python==3.10.12 djongo==1.3.6 pymongo==4.7.3 #! settings.py DATABASES = { 'default': { 'ENGINE': 'djongo', 'NAME': 'syscandb', 'ENFORCE_SCHEMA': False, 'CLIENT': { 'host': 'mongodb+srv://<user>:<senha>@clusterak.mp9ylv1.mongodb.net/syscandb?retryWrites=true&w=majority' } } } In MOngo Atlas it guides like this: mongodb+srv://<username>:<password>@clusterak.mp9ylv1.mongodb.net/?retryWrites=true&w=majority&appName=clusterak I tested successfully via python like this: "mongodb+srv://<username>:<password>@clusterak.mp9ylv1.mongodb.net/?retryWrites=true&w=majority&authSource=admin" (venv) rkart@rkart-B-ON:/home/jobs/micakes/syscan$ python3 manage.py makemigrations No changes detected Traceback (most recent call last): File "/home/jobs/micakes/syscan/manage.py", line 24, in main() File "/home/jobs/micakes/syscan/manage.py", line 20, in main execute_from_command_line(sys.argv) File "/home/jobs/micakes/syscan/venv/lib/python3.10/site-packages/django/core/management/init.py", line 425, in execute_from_command_line utility.execute() File "/home/jobs/micakes/syscan/venv/lib/python3.10/site-packages/django/core/management/init.py", line 419, in execute self.fetch_command(subcommand).run_from_argv(self.argv) File "/home/jobs/micakes/syscan/venv/lib/python3.10/site-packages/django/core/management/base.py", line 386, in run_from_argv connections.close_all() File "/home/jobs/micakes/syscan/venv/lib/python3.10/site-packages/django/db/utils.py", line 213, in close_all connection.close() File "/home/jobs/micakes/syscan/venv/lib/python3.10/site-packages/django/utils/asyncio.py", line 25, in inner return func(*args, **kwargs) File "/home/jobs/micakes/syscan/venv/lib/python3.10/site-packages/django/db/backends/base/base.py", line 305, in close self._close() File "/home/jobs/micakes/syscan/venv/lib/python3.10/site-packages/djongo/base.py", line 208, in _close if self.connection: File "/home/jobs/micakes/syscan/venv/lib/python3.10/site-packages/pymongo/database.py", line 1342, in bool raise NotImplementedError( NotImplementedError: Database objects do not implement truth value testing or bool(). Please compare with None instead: database is not None -
Firefox can’t establish a connection to the server at ws://127.0.0.1:port
I built a chat app that users will be able to call, sending texts and pictures each other. when i click on call button, I should see my stream and the second user that I am calling to. I just can see my camera and can not see my contact. if another user tries to call me it will happen the same again. How to fix the problem? error on console: **Firefox can’t establish a connection to the server at ws://127.0.0.1:8000/ws/call/username/** `# chat/consumers.py from channels.generic.websocket import AsyncWebsocketConsumer import json class ChatConsumer(AsyncWebsocketConsumer): async def connect(self): self.room_name = self.scope\['url_route'\]\['kwargs'\]\['username'\] self.room_group_name = f'chat\_{self.room_name}' # Join room group await self.channel_layer.group_add( self.room_group_name, self.channel_name ) await self.accept() async def disconnect(self, close_code): # Leave room group await self.channel_layer.group_discard( self.room_group_name, self.channel_name ) async def receive(self, text_data): # Handle incoming WebSocket messages text_data_json = json.loads(text_data) message = text_data_json['message'] # Broadcast message to room group await self.channel_layer.group_send( self.room_group_name, { 'type': 'chat_message', 'message': message } ) async def chat_message(self, event): # Send message to WebSocket message = event['message'] # Send message to WebSocket await self.send(text_data=json.dumps({ 'message': message })) ` decorators.py `from functools import wraps from django.shortcuts import redirect from django.urls import reverse from authentication.models import BasicUserProfile def basic_user_login_required(view_func): @wraps(view_func) def _wrapped_view(request, … -
Django FormField that creates several inputs and maps them to model fields
I am using django-modeltranslation to have certain fields of my models in multiple languages. For example, I translate the name field, which leads to several fields in the model and database, like name, name_en, name_gr, etc.. Now I want the user to be able to edit the name and it's translations in a form. And I want the user to be able to select the language they want to edit, so I want to render all fields (i.e. name_en, name_gr) and add some JS to show only one of them and select others. Now I could easily add both fields to the form, add them to a template and add the JS. However I have several forms with these multilingual fields and would prefer to find a generic solution as custom form field. So something like this: class MultilingualForm(ModelForm): name = MultilingualField() class Meta: model = SomeModel fields = ["name"] However I cannot think of a way on how to map a custom form field to several model fields. I this even possible? -
How do I add more left to each iteration of my FOR using Django Language Template + HTML?
I'm having problems making a code in HTML + DLT for printing documents (Delivery Note). What happens is that the customer needs the products to be next to each other. I will ite the products through For, where the first product would have left:8mm and the second would be added 40mm. However, if there are more than 2 products, the third always overlaps the second! I would need that with each iteration of my FOR, more LEFT be added to <span>, starting with 8mm and increasing from 40mm to 40mm. Full code: <div style="font-family:none;"> <style> @import url('https://fonts.googleapis.com/css2?family=Libre+Barcode+39&display=swap'); @page {margin:0;font-family: Arial !important;} html * {font-family: Arial } table{border-collapse: collapse;table-layout: fixed} .padding-td {padding:0.3cm} .check-box {width:0.2cm;height:0.2cm;border:1px solid;margin-right:0.1cm} table td{color:#000;border:1px solid;vertical-align: initial;} .cell_azul{background: #d8e1f2;font-size: 7pt;} .right{text-align: right;} .center{text-align: center;} .cell_cinza{background: #f5f5f5;height:26px;} .cell_branco{background: #fff;} .cert{width:1.42cm;height:1.85cm;border:solid 1px} .contact-text{margin-left:auto;font-size:14px;margin-top:0.1cm} .table-texts{display:flex;flex-direction:row;font-size:13px;height:0.7cm} .size-texts {font-size: 10px } .absolutes {position: absolute;padding: inherit;text-align: left;font-size: 14px;font-weight: bold} </style> {% for delivery_note in delivery_notes %} <div style="min-width: 21cm;min-height: 29.5cm;background: #fff;padding-top: 5mm;padding-left: 15mm;page-break-after: always;position:relative"> <!--DESCRIPCIÓN DE HORMIGON--> {% with 8 as initial_left %} {% for product_note in delivery_note.products_note %} {% if forloop.first %} <span class="absolutes" style="top:54mm;left: {{ initial_left }}mm;width: 10cm; font-size: 14px;font-weight: bold;"> {{ product_note.product.name }} </span> {% else %} {% with initial_left|add:forloop.counter0|add:forloop.counter|add:40 as left_addition … -
how get -> ( path of the photo file for face-picture-comparator module (pypi.org) in django project root in file utils.py )?
in Windows 10 enterprise , vscode 1.88.0 , Django==5.0.3 , face-picture-comparator==0.0.4 , face-recognition==1.3.0 , face_recognition_models==0.3.0. How can I give the face-picture-comparator module the path of the photo stored in the sqlite database and in the static folder in my Django project root in file -> utils.py ? Consider utils.py in django project root folder: from face_picture_comparator import load_img from face_picture_comparator import comparation from face_picture_comparator import plot import os from django.conf import settings from django.contrib.staticfiles import finders from django.templatetags.static import static def get_face_compare_result(image, image_compare): # result = finders.find(image_compare) # print(result) image_compare = load_img.get_image_file(???) image = load_img.get_image_file(???) # message_result = comparation.confront_faces_message(image, image_compare) # message_result = comparation.confront_faces_message(image, image_compare) comparison_result = comparation.confront_faces( image, image_compare) return comparison_result my error : FileNotFoundError: [Errno 2] No such file or directory: '/static/images/user_profile_image_authenticate/barjawandsaman%2540gmail.com/barjawandsamangmail.com-3140735494931184150742764881890058937-imageProfileAuthenticate.PNG' [17/Jun/2024 14:14:07] "POST /home/api/v1/authenticating_manager_login_by_face/ HTTP/1.1" 500 132469 spot : i search many questions in this forum and other forums in google but i did not find my answer because in this module (face-picture-comparator - pypi.org) i can not find path for image file that here is my input in utils.py -> image = load_img.get_image_file(???) and this module in pure python in other python project is working currectly and do not have problems !!! and my problems … -
Django 5.0, Display flash message in form and retain input values
I have an email submission form with 3 input fields: #forms.py class ContactForm(forms.Form): name = forms.CharField( widget=forms.TextInput(attrs={"placeholder": "* Your name"}) ) email = forms.EmailField( widget=forms.TextInput(attrs={"placeholder": "* Your email address"}) ) message = forms.CharField( widget=forms.Textarea(attrs={"placeholder": "* Your message"}) ) When a user submits the form, a flash message appears below the submit button confirming that the message has been sent. #contact.html <section id="form"> <form action="" method="post"> <h3>Send me an email</h3> {% csrf_token %} {{ form|crispy }} <input type="submit" value="Send"> {% if messages %} {% for message in messages %} <div class="text-center alert alert-{{ message.tags }}" > {{ message|safe }} </div> {% endfor %} {% endif %} </form> </section> #views.py class ContactPageView(SuccessMessageMixin, FormView): form_class = ContactForm template_name = "contact.html" success_url = reverse_lazy('contact') # Return back to the page containing the form success_message = "Your message has been sent. Thankyou." def form_valid(self, form): email = form.cleaned_data.get("email") name = form.cleaned_data.get("name") message = form.cleaned_data.get("message") # Displays in console full_message = f""" Email received from <{name}> at <{email}>, ________________________ {message} """ send_mail( subject="Email from client using website form", message=full_message, from_email=settings.DEFAULT_FROM_EMAIL, recipient_list=[settings.NOTIFY_EMAIL], ) return super().form_valid(form) The form works fine except that I would like the input values retained after the form has been submitted and with the … -
{{% if user.is_authenticated %}} is not working properly it always shows the authenticated block and not else block
.................urls.py.......... from django.contrib import admin from django.urls import path, include from user import views as user_view from django.contrib.auth import views as auth_views from django.views.generic import TemplateView from django.conf import settings from django.conf.urls.static import static urlpatterns = [ path('admin/', admin.site.urls), path('', include('dashboard.urls')), path('register/', user_view.register, name = 'user-register'), path('profile/', user_view.profile, name = 'user-profile'), path('', auth_views.LoginView.as_view(template_name = 'user/login.html'),name='user-login'), path('logout/', TemplateView.as_view(template_name = 'user/logout.html'),name='user-logout' ), ] + static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT) ...........views.py........ from django.shortcuts import render, redirect from django.contrib.auth.forms import UserCreationForm from .forms import CreateUserForm from django.contrib.auth.models import User from django.contrib.auth.decorators import login_required def register(request): if request.method == 'POST': form = CreateUserForm(request.POST) if form.is_valid(): form.save() return redirect('user-login') else: form = CreateUserForm() context = { 'form': form, } return render(request, 'user/register.html',context) def profile(request): return render(request, 'user/profile.html') .........nav.html........ <nav class="navbar navbar-expand-lg navbar-info bg-info"> {% if user.is_authenticated %} <div class="container"> <a class="navbar-brand text-white" href="{% url 'dashboard-index' %}">NTPC Inventory</a> <button class="navbar-toggler" type="button" data-toggle="collapse" data-target="#navbarSupportedContent" aria-controls="navbarSupportedContent" aria-expanded="false" aria-label="Toggle navigation"> <span class="navbar-toggler-icon"></span> </button> <div class="collapse navbar-collapse" id="navbarSupportedContent"> <ul class="navbar-nav mr-auto"> <li class="nav-item active"> <a class="nav-link text-white" href="{% url 'dashboard-index' %}">Dashboard <span class="sr-only">(current)</span></a> </li> </ul> <ul class="navbar-nav ml-auto"> <li class="nav-item active"> <a class="nav-link text-white" href="profile.html">Admin Profile <span class="sr-only">(current)</span></a> </li> <li class="nav-item"> <a class="nav-link text-white" href="{% url 'user-logout' %}">Logout</a> </li> </ul> <!-- problem is not … -
Is there any way to add a file using an external button to my Kartik Krajee Bootstrap File Input?
I am working on a Django project where I use bootstrap. I added this plugin https://plugins.krajee.com/file-input/plugin-options. I have a modal where I use the file input, now is there any way to add file/files to the file input using an external button? (for example: I have a button to generate my Offer PDF, and when is generated I want to be auto added to my file input and be able to see it. This is part of my HTML code: <div class="form-group row hidden" id="email_files_container_{{ action }}"> <div class="col"> <input type="file" component="2" file_type="email" id="id_email_files_{{ action }}" name="email_files[]" class="flow-files" multiple="multiple"> </div> </div> <div class="form-group row"> <button id="id_file_pdf" type="button" class="btn btn-primary">{% trans 'Ataseaza Fisierul PDF' %}</button> </div> and this is part of my JavaScript Code: function AddFilePDF(myFileInput, object_type, object_id) { $.ajax({ url: '/popup/get_email_pdf/' + object_type + '/' + object_id + '/', type: 'GET', success: function(response) { if (response.pdf) { var pdf = response.pdf const blob = new Blob([pdf.file], { type: pdf.file_mime }); const newFile = new File([blob], pdf.file_name, { type: pdf.file_mime }); myFileInput.fileinput('addToStack', newFile); } }, error: function(xhr, status, error) { console.error('Error:', error); } }); } I tried this way and it is adding the file to the stack, but i cannot … -
Python Django access fields from inherited model
Hi I have a question related to model inheritance and accessing the fields in a Django template. My Model: class Security(models.Model): name = models.CharField(max_length=100, blank=False) class Stock(Security): wkn = models.CharField(max_length=15) isin = models.CharField(max_length=25) class Asset(models.Model): security = models.ForeignKey(Security, on_delete=models.CASCADE,blank=False) My views.py context["assets"] = Asset.objects.all() My template: {% for asset in assets %} {{ asset.security.wkn }} ... This gives me an error as wkn is no field of security. Any idea how I can solve this? Thanks in advance! -
purpose of using daphne with django channels
why is the primary purpose of using daphne with django channels , if we can already do the asgi configuration ourselves ? like what is the relationship between ASGI & daphne server if you could provide a clear explanation that would be very helpful -
How to play different audios on a single <audio> tag Django app
i'm making a music streaming website. In the homepage i have a carousel with songs and i want to play them onclick on a single HTML tag. how can i make? Do i have to write a javascript function? if yes, how it has to be? this is my HTML: <div class="main-carousel" data-flickity='{"groupCells":5 , "contain": true, "pageDots": false, "draggable": false, "cellAlign": "left", "lazyLoad": true}'> {% for i in songs %} <div class="carousel-cell"> <section class="main_song"> <div class="song-card"> <div class="containera"> <img src="{{i.image}}" id="A_{{i.id}}" alt="song cover"> <div class="overlaya"></div> <div> <a class="play-btn" href="...?" id="{{i.id}}"><i class="fas fa-play-circle fa-2x"></i></a> {% if user.is_authenticated %} <div class="add-playlist-btn"> <a id="W_{{i.song_id}}" title="Add to Playlist" onclick="showDiv(this)"></a> </div> {% endif %} </div> </div> </div> <div> <p class="songName" id="B_{{i.id}}">{{i.name}}</p> <p class="artistName">{{i.artist}}</p> </div> </section> </div> {% endfor %} </div> <audio preload="auto" controls id="audioPlayer"> <source src=...?> </audio> my models.py: class Song(models.Model): song_id = models.AutoField(primary_key=True) name = models.CharField(max_length=50) artist = models.CharField(max_length=50) album = models.CharField(max_length=50, blank=True) genre = models.CharField(max_length=20, blank=True, default='Album') song = models.FileField(upload_to="songs/", validators=[FileExtensionValidator(allowed_extensions=['mp3', 'wav'])], default="name") image = models.ImageField(upload_to="songimage/", validators=[FileExtensionValidator(allowed_extensions=['jpeg', 'jpg', 'png'])], default="https://placehold.co/300x300/png") data = models.DateTimeField(auto_now=False, auto_now_add=True) slug = models.SlugField(unique=True) def __str__(self): return self.name class Meta: ordering = ['name'] -
Images not displaying in my for loop Django
i'm making a music streaming website and i want to display the songs in the homepage. I'm using a for loop in songs and everything is working ( but the images are not displaying and i see this . How can i fix it? This is models.py: class Song(models.Model): song_id = models.AutoField(primary_key=True) name = models.CharField(max_length=50) artist = models.CharField(max_length=50) album = models.CharField(max_length=50, blank=True) genre = models.CharField(max_length=20, blank=True, default='Album') song = models.FileField(upload_to="media/songs/", validators=[FileExtensionValidator(allowed_extensions=['mp3', 'wav'])], default="name") image = models.ImageField(upload_to="media/songimage/", validators=[FileExtensionValidator(allowed_extensions=['jpeg', 'jpg', 'png'])], default="https://placehold.co/300x300/png") data = models.DateTimeField(auto_now=False, auto_now_add=True) slug = models.SlugField(unique=True) def __str__(self): return self.name class Meta: ordering = ['name'] and this is the html: {% for i in songs %} <div class="carousel-cell"> <section class="main_song"> <div class="song-card"> <div class="containera"> <img src="{{i.image}}" id="A_{{i.id}}" alt="song cover"> <div class="overlaya"></div> <div> <a class="play-btn" href="{{i.preview_url}}" id="{{i.id}}"><i class="fas fa-play-circle"></i></a> {% if user.is_authenticated %} <div class="add-playlist-btn"> <a id="W_{{i.song_id}}" title="Add to Playlist" onclick="showDiv(this)"></a> </div> {% endif %} </div> </div> </div> <div> <p class="songName" id="B_{{i.id}}">{{i.name}}</p> </div> <p class="artistName">{{i.singer1}}</p> </section> </div> {% endfor %} -
Django ORM Query aggregate datetime + timeoffset and filter on new value
I've the following table structure (note localised start time): id start_time offset score 1 2024-06-14 02:03:00.000 +0200 +1000 15 2 2024-06-14 02:04:00.000 +0200 +1000 15 3 2024-06-14 02:05:00.000 +0200 +1000 12 4 2024-06-14 02:06:00.000 +0200 +1000 10 I'm trying to come up with a query that fetch all the entries, where start time localised at column offset is greater than a given date. So far i tried something on the line of: from django.db.models import F, ExpressionWrapper from django.db import models from django.db.models.functions import TruncDate from datetime import datetime import pytz utc = pytz.timezone('UTC') localized_start_time = ExpressionWrapper( TruncDate('start_time', tzinfo=utc) + F('offset'), output_field=models.DateTimeField() ) result = MyModel.objects.annotate( localized_start_time=localized_start_time ).filter( localized_start_time=datetime.now() ) however when running the output query, i'm getting: operator does not exist: date + character varying Hint: No operator matches the given name and argument types. You might need to add explicit type casts. Any clue on how to add localised start time using the value on column offset? Unfortunately, i cannot change the way data is store since it's a production database and the impact would be too big. -
Django - Separate DBs for write and read & tests issue
I have set-up separate databases for read operations and for write operations. In my DEV environment this points to the same database but under different alias. In PROD environment this gets overwritten to point to 2 separate databases which are connected between each other and basically hold the same data. Nonetheless, while the configuration works correctly when using my Django web app (starting the webserver, playing around with the logic using my browser), my unit tests, which are creating/modifying and then asserting changes in model instances, are not able to run at all. The error I get when starting my unit tests is: ValueError: Cannot force both insert and updating in model saving. My set-up looks like this: settings.py DATABASES = { "default": { "ENGINE": "django.db.backends.mysql", "NAME": "django", "USER": "dj", "PASSWORD": "mypassword", "HOST": "127.0.0.1", "PORT": "3306", }, "read_db": { "ENGINE": "django.db.backends.mysql", "NAME": "django", "USER": "dj", "PASSWORD": "mypassword", "HOST": "127.0.0.1", "PORT": "3306", }, "write_db": { "ENGINE": "django.db.backends.mysql", "NAME": "django", "USER": "dj", "PASSWORD": "mypassword", "HOST": "127.0.0.1", # localhost because otherwise client is trying to connect via socket instead of TCP IP "PORT": "3306", }, "root": { "ENGINE": "django.db.backends.mysql", "NAME": "root", "USER": "xxx", "PASSWORD": "zzz", "HOST": "127.0.0.1", "PORT": "3306", }, } DATABASE_ROUTERS = … -
Raw input being recorded but data is not saving throwing "this field is required" error
For context, I've essentially got a form whereby the user fills in job details and can choose who was on the job from an existing list of workers and input their hours, rates, and total wages. I've implemented a script so the user can 'add' more workers to the form. The main issue is that the data is not saving specifically for the hours and rates field even though the wages field is, so I cannot submit the whole form. Given the JS is client-side it is more likely a django problem, I've tested it anyway by getting rid of my script. Wage Model: class EmployeeWage(models.Model): job = models.ForeignKey(Operating_Budget, on_delete=models.CASCADE, null=True, blank=True) worker = models.ForeignKey(EmployeeRecord, on_delete=models.CASCADE, null=True, blank=True) wages = models.DecimalField(max_digits=10, decimal_places=2) hours = models.DecimalField(max_digits=10, decimal_places=2, default=0) rates = models.DecimalField(max_digits=10, decimal_places=2,default=0) This is my Wage form: class WorkerWagesForm(forms.ModelForm): worker = forms.ModelChoiceField(queryset=EmployeeRecord.objects.all(), label="") wages = forms.DecimalField(label="", max_digits=10, decimal_places=2) hours = forms.DecimalField(label="", max_digits=10, decimal_places=2) rates = forms.DecimalField(label="", max_digits=10, decimal_places=2) class Meta: model = EmployeeWage fields = ('worker', 'wages', 'hours', 'rates') class JobWorkerWageFormSetBase(BaseInlineFormSet): def clean(self): super().clean() for form in self.forms: if form.cleaned_data.get('hours') is None: form.add_error('hours', 'Hours are required.') if form.cleaned_data.get('rates') is None: form.add_error('rates', 'Rates are required.') WorkerWagesFormSet = inlineformset_factory(Operating_Budget, EmployeeWage, formset = JobWorkerWageFormSetBase, … -
is model is woring attrs
raise dj_exc_value.with_traceback(traceback) from exc_value File "C:\Users\97326\AppData\Roaming\Python\Python310\site-packages\django\db\backends\utils.py", line 85, in _execute return self.cursor.execute(sql, params) File "C:\Users\97326\AppData\Roaming\Python\Python310\site-packages\django\db\backends\sqlite3\base.py", line 416, in execute return Database.Cursor.execute(self, query, params) django.db.utils.IntegrityError: NOT NULL constraint failed: new__Movie_movie.movie_download_file class movie(models.Model): movie_name=models.CharField(max_length=300) movie_descrition=models.TextField() movie_catagory_title=models.CharField(max_length=100,choices=catagory_title,default=0) movie_type=models.CharField(max_length=103, choices=catagory,default=0) movie_select=models.CharField(max_length=103, choices=topt,default=0,blank=True) movie_upload_time=models.DateTimeField(auto_now_add=True) movie_title_image=models.ImageField(upload_to='movie/movieTitle',blank=True) movie_file=models.URLField(max_length=3000,blank=True,default=None) movie_download_file=models.URLField(max_length=3000,blank=True,default=None) def __str__(self): return self.movie_name -
'payments' is not a registered namespace
I think I did a good job mapping the URL, so please check it out from django.urls import path from . import views app_name = 'payments' urlpatterns = [ path('request/<int:order_id>/', views.payment_request, name='payment_request'), path('success/', views.payment_success, name='payment_success'), path('fail/', views.payment_fail, name='payment_fail'), path('checkout/', views.checkout_view, name='checkout'), ] def checkout_view(request): return render( request, 'checkout.html', ) <form method="post" action="{% url 'payments:checkout' %}"> {% csrf_token %} {{ form.as_p }} created app_name = 'payments' -
i have uploded my django proejct on cloudfare through gunicorn but i seems like my css is not loading in it
Static files (CSS, JavaScript, Images) https://docs.djangoproject.com/en/5.0/howto/static-files/ Static files (CSS, JavaScript, Images) STATIC_URL = '/static/' This is where you put your uncollected static files STATICFILES_DIRS = [ BASE_DIR / 'static', ] This is where collected static files will be placed STATIC_ROOT = BASE_DIR / 'staticfiles' Default primary key field type https://docs.djangoproject.com/en/5.0/ref/settings/#default-auto-field i want to make the css visible in my software -
django edit.py ProcessFormView() question
class ProcessFormView(View): """Render a form on GET and processes it on POST.""" def get(self, request, *args, **kwargs): """Handle GET requests: instantiate a blank version of the form.""" return self.render_to_response(self.get_context_data()) def post(self, request, *args, **kwargs): """ Handle POST requests: instantiate a form instance with the passed POST variables and then check if it's valid. """ **form = self.get_form()** if form.is_valid(): return self.form_valid(form) else: return self.form_invalid(form) # PUT is a valid HTTP verb for creating (with a known URL) or editing an # object, note that browsers only support POST for now. def put(self, *args, **kwargs): return self.post(*args, **kwargs) In that part, there is no part that is imported by inheriting self.get_form(), self.form_valid() so I am curious as to how to import it and just use it. Is that incomplete code? To use it normally, should I use "ProcessFormView(View, ModelFormMixin)" like this? The Django version I use is 4.1.5 I wonder why it suddenly appeared. The concept of inheritance clearly exists, but I have my doubts as to whether this is in violation of this. As an example, you can see that other codes inherit very well. `class BaseDeleteView(DeletionMixin, FormMixin, BaseDetailView): """ Base view for deleting an object. Using this base class …