Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Render a django template without a django app
I am very new to Django. I have the following Django template, and I would like to render it to display the username variable. How can I do this without setting up an entire Django app structure? <html> <body> hello <strong>{{username}}</strong> your account is activated. </body> </html> I've seen this question, but when I run the code there, I get an error message: ImproperlyConfigured: No DjangoTemplates backend is configured. -
Nginx configuration for both front-end and back-end in same file
I have an app hosted on a server with Nginx and Gunicorn. This app’s frontend is built using React while the backend Django. I do understand how to configure Nginx and Unicorn for a Django app. But what I want is every request to the ‘/admin/’ and ‘/api/‘ should be sent gunicorn, but every other request to the root url and others should be sent to the react app to handle. I have the below configuration for Nginx to serve Django but I don’t know how to go about it for the frontend and back-end in one configuration file. # /etc/nginx/sites-available/myapp server { listen 80; server_name myapp.com www.myapp.com location = /favicon.ico { access_log off; log_not_found off; } location /static/ { root /home/ubuntu/myapp; } location / { include proxy_params; proxy_pass http://unix:/run/gunicorn.sock; } } Thank you for your assistance -
how to filter in the django admin-site through created fields
class Ron(models.Model): ron_id=models.AutoField(primary_key=True,verbose_name='identificador') ron_nombre=models.CharField(max_length=50,verbose_name='Nombre') ron_descripcion=models.CharField(max_length=1000,verbose_name='Descripcion') fk_ron_clasi_tipo=models.ForeignKey('ClasificacionTipo',on_delete=models.CASCADE,verbose_name='Clasificacion y Tipo') fk_ron_anej=models.ForeignKey('Anejamiento',on_delete=models.CASCADE,related_name='ron_anejamiento',verbose_name='Añejamiento') fk_ron_grado_alco=models.ForeignKey('GradoAlcohol',on_delete=models.CASCADE,related_name='ron_grado_alcohol',verbose_name='Grado Alcohol') fk_ron_color=models.ForeignKey('Color',on_delete=models.CASCADE,related_name='ron_color',verbose_name='Color') fk_ron_prove=models.ForeignKey('Proveedor',on_delete=models.CASCADE,related_name='ron_proveedor',verbose_name='Proveedor') fk_ron_lugar=models.ForeignKey('Lugar',on_delete=models.CASCADE,related_name='ron_lugar',verbose_name='Origen',limit_choices_to={'lugar_tipo':'parroquia'}) I have this model, in the fk_ron_lugar I have limited options so that only the parishes can be selected in the adminsite, but I would like to generate a kind of filter where you have three fields, first choose the state, then the municipalities of the state you referred to, and finally the parishes of said municipality, and when you save, the parish ID is used+ -
The group_send in channel_layers from django does not work when running multiple times
I was learning about django-channels and wanted to create a basic timer that tells me every second, or rather sends a response to the react frontend/ client every sec as to many seconds has it been since a certain button has been clicked. But it seems that the group_send method of the channel_layer runs only the first time, but in my code the time update of the timer is in the consumer class, which i cannot access if the group_send method does not work. Here is the consumer.py file import json import asyncio from channels.generic.websocket import AsyncWebsocketConsumer from django.utils import timezone class HelloConsumer(AsyncWebsocketConsumer): async def connect(self): # Join the hello_group when a WebSocket connection is established await self.channel_layer.group_add('hello_group', self.channel_name) await self.accept() async def disconnect(self, close_code): # Leave the hello_group when a WebSocket connection is closed await self.channel_layer.group_discard('hello_group', self.channel_name) async def receive(self, text_data): # Handle the received message if text_data == 'hello': # Update the last_hit timestamp self.scope['last_hit'] = timezone.now() else: await self.send(text_data=json.dumps({'error': 'Invalid message'})) async def send_hello_message(self, event): # Send hello message to the client while True: print('hehe2') last_hit = event.get('last_hit', None) if last_hit: seconds_ago = (timezone.now() - last_hit).seconds await self.send(text_data=f'Hello World hit {seconds_ago} seconds ago') else: await self.send(text_data='Hello World … -
Specifying css file for admin
I am trying to change styles for displaying my model in Django Admin: class ContentAdmin(MyAdmin): ... class Media: css = { 'all': ('css/myadmin.css',) } The file myadmin.css is located in static/css/. When running locally, the following appears in the console when loading the admin page: "GET /static/css/myadmin.css HTTP/1.1" 404 1804 It looks like the request is going to the correct location where the file is resides. So, why isn't it found? -
DUPLICATION FINDING FOR ROW BASE ON COLUMN
Looking at the table in the image we could see that the row for SNO 1 with Reference number PAP123 is a duplicate of the row for SNO 3 with Reference number PAP123. We could see that the duplication happens in the CUTTING column and that is why under the DUPLICATION column for both SNO 1 and SNO 3 there is a "True" condition and in parentheses the CERTIFICATE No. and BATCH for its duplicate is indicated together with the column in which the duplicate is happening. We could also see that under the WEEDING column duplication happens for SNO 2 and SNO 4 but it is not marked as duplicate because the REFERENCE NO. are not the same. Now I want to use this same logic to modify the code below so that the output will look for duplicates like in the table of the image. For duplicate to happen a row needs to have at least a column value repeated and the value should fall under the same column. Also, the Reference no. for both rows should be the same. duplicate_mask = combined_data.duplicated(subset=[ 'SLASHING BEFORE LINING & PEGGING', 'CUTTING OF PEGS', 'LINING & PEGGING', 'PLANTAIN /ECO TREE-HOLING', 'COCOA-HOLING', … -
How to fix "nginx: [emerg] "upstream" directive is not allowed" in Nginx with Django?
I want to use Django, Python, Nginx. I made the /etc/nginx/sites-availabe/microdomains.conf file like this: upstream django { server unix:///home/christian/microdomains/microdomains.sock; } server { listen 80; server_name ubuntuchristian; charset utf-8; # max upload size client_max_body_size 75M; # Django media and static files location /media { alias /home/christian/microdomains/media; } location /static { alias /home/christian/microdomains/static; } # Send all non-media requests to the Django server. location / { uwsgi_pass django; include /home/christian/microdomains/uwsgi_params; } } However, when testing, it generates the error: (md) christian@ubuntuchristian:~/microdomains$ sudo nginx -t -c /etc/nginx/sites-available/microdomains.conf nginx: [emerg] "upstream" directive is not allowed here in /etc/nginx/sites-available/microdomains.conf:1 nginx: configuration file /etc/nginx/sites-available/microdomains.conf test failed Any suggestions to handle this error? I need that the nginx works fine. -
Django Channels WebSocket Connection Returns 404 Not Found
I'm working on a Django project with Django Channels to handle WebSocket connections. I've set up my routing and consumers, but when I try to open a WebSocket connection from my JavaScript code, I get a 404 Not Found error. Here's my JavaScript code: var chatSocket = new WebSocket( 'ws://' + window.location.host + '/ws/chat/'); And here's my Django Channels routing: # routing.py from django.urls import re_path from . import consumers websocket_urlpatterns = [ re_path(r'ws/chat/$', consumers.ChatConsumer.as_asgi()), ] When I try to open the WebSocket connection, I get this error in the console: GET http://localhost:8000/ws/chat/ 404 (Not Found) I've also configured Django Channels to use Redis as the channel layer in my settings: # settings.py CHANNEL_LAYERS = { 'default': { 'BACKEND': 'channels_redis.core.RedisChannelLayer', 'CONFIG': { "hosts": [('127.0.0.1', 6379)], }, }, } I've checked and double-checked my routing and everything seems to be in order. What could be causing this error? How can I debug this issue? Any help would be appreciated. -
Django save() is not properly saving my object
I have two models one named Post and the other Journey. Each Journey contains a query set of Post objects. When I add a post to the posts of Journey and save both the new Post and the Jounrey, the post does save properly but the Journey doesn't. The Post is beign properly created because in my JourneyView it is displayed after it is created but when I refresh the Post no longer appears as part of the Journey. I checked the database manually and the new post is saved and the object does exist it is just not being saved as part of the Journey. This is the function I am using to create the post: #Create post @api_view(['POST']) def post_create(request): form = PostForm(request.POST) attachment = None attachment_form = AttachmentForm(request.POST, request.FILES) #journeys = Journey.objects.filter(created_by_id=request.user.id) #journey = Journey.objects.get(id = post.journeyID) if attachment_form.is_valid(): attachment = attachment_form.save(commit=False) attachment.created_by = request.user attachment.save() if form.is_valid(): post = form.save(commit=False) post.created_by = request.user post.save() journey = Journey.objects.get(id = post.journeyID) #journey.posts.set(journey.posts.all()) journey.save() #save_Journey(post.journeyID) if attachment: post.attachments.add(attachment) user = request.user user.posts_count = user.posts_count + 1 user.save() serializer = PostSerializer(post) return JsonResponse(serializer.data, safe=False) else: return JsonResponse({'error': 'add somehting here later!...'}) I already tried using a for loop to save … -
How to obtain a queryset from unrelated models in Django
I am developing a website on car spare parts. The main model is Part, which has different parent models, such as Category and Brand. I want to automatically generate the menu from my database. If I had one level menu, "Category", this is pretty straightforward. I just select all categories, which have at least one part in them, and pass them to the template in the context: category_list = Category.objects.annotate(num_parts=Count('parts')).filter(num_parts__gt=0) context['category_list'] = category_list return context But now I want my menu to be two-level, consisting of categories and brands: Wheels Toyota Ford Renault Radiators Ford Mersedes Or course, I don't want to obtain empty menu options, where are no parts. Please give me a hint, how can I do this! -
get multiple query params with the same key in drf django-filter
I am going to use django-filter to perform filtering in Django models everything is fine but i have two problems 1.In the url, I must send the brand name or do not send the brand name at all, if I send the brand name empty, an error will occur -> how can i fix it? http://127.0.0.1:8000/api/products/filtered_data/?brand_name=nike -> correct http://127.0.0.1:8000/api/products/filtered_data/ -> correct http://127.0.0.1:8000/api/products/filtered_data/?brand_name= -> { "brand_name": [ "Select a valid choice. is not one of the available choices." ] } 2.To get multiple brands, I have to send the brand name several times, but I want to make it possible to send the brand names with ',' http://127.0.0.1:8000/api/products/filtered_data/?brand_name=nike&brand_name=guchi -> i have to send brand names like this http://127.0.0.1:8000/api/products/filtered_data/?brand_name=nike,guchi -> i want to send brand names like this views.py: class ProductFilter(filters.FilterSet) brand_name = filters.ModelMultipleChoiceFilter(queryset=Brand.objects.all(),) class Meta: model = Product fields = ["has_discount","brand_name","available"] class filtered_data(ListAPIView): authentication_classes = [] permission_classes = [] queryset = Product.objects.all() serializer_class = ProductSerializer filterset_class = ProductFilter models.py: class Brand(models.Model): name = models.CharField(max_length=100) def __str__(self): return self.name class Product(models.Model): category = models.ManyToManyField(Category, related_name='cat_product') name = models.CharField(max_length=200) has_discount = models.BooleanField(default=False) brand_name = models.Foreignkey(Brand, on_delete = models.CASCADE) brand_image = models.ImageField(null=True,blank=True,upload_to='product') create = models.DateTimeField(auto_now_add=True) available = models.BooleanField(default=True) discount = models.IntegerField(blank=True, null=True) -
If we provide a physical path of the backend and frontend, is it possible to deploy using WordPress apis
i have backend code in django and frontend code i want to deploy on wordpress i gave path of my frontend and backend If we provide a physical path of the backend and frontend, is it possible to deploy using WordPress apis. -
django OneToOneField to abstract object
i want a field be OneToOneField to an abstract object, the abstract will be never used, instead will be used subclasses: from django.db import models class Abs(models.Model): useType = True absName = models.CharField(max_length=10, default='mickey', blank=True) class Meta: abstract = True from django.db import models from .abs import Abs class Sub(Abs): useType = False name=models.CharField(max_length=10, default='', blank=True) from django.db import models from .abs import Abs class ParentClass(models.Model): abs = models.OneToOneField(Abs, on_delete=models.CASCADE) but when make makemigrations i receive following error: books.ParentClass.abs: (fields.E300) Field defines a relation with model 'Abs', which is either not installed, or is abstract. books.ParentClass.abs: (fields.E307) The field books.ParentClass.abs was declared with a lazy reference to 'books.abs', but app 'books' doesn't provide model 'abs'. If Abs was a real object all works fine, but Abs should never be a real object, so i thought should be abstract, it's only a basket to common info/methods, an interface. Is there a way to do that? Many thanks -
Django - dynamic filtering multiple querysets
I want to make a monthly breakdown of expenses by type of expenses. I would like to enter the start date and end date dynamically through the filter form, so that I don't have to duplicate the code for each month. For each type of expense I created a separate queryset (more than 20). Here is the view.py def monthly_analysis_november(request): accountant = Expenses.objects\ .filter(date__gte = "2023-11-01", date__lte = "2023-11-30", type_of_expense = "accountant expenses")\ .annotate(price=Sum(F('quantity')*F('price_per_unit')))\ .aggregate(total_accountant=Sum('price')) interest_rates = Expenses.objects\ .filter(date__gte = "2023-11-01", date__lte = "2023-11-30", type_of_expense = "interest rates")\ .annotate(price=Sum(F('quantity')*F('price_per_unit')))\ .aggregate(total_interest_rates=Sum('price')) phones = Expenses.objects\ .filter(date__gte = "2023-11-01", date__lte = "2023-11-30", type_of_expense = "phones")\ .annotate(price=Sum(F('quantity')*F('price_per_unit')))\ .aggregate(total_phones=Sum('price')) oil = Expenses.objects\ .filter(date__gte = "2023-11-01", date__lte = "2023-11-30", type_of_expense = "oil")\ .annotate(price=Sum(F('quantity')*F('price_per_unit')))\ .aggregate(total_oil=Sum('price')) leasing = Expenses.objects\ .filter(date__gte = "2023-11-01", date__lte = "2023-11-30", type_of_expense = "leasing")\ .annotate(price=Sum(F('quantity')*F('price_per_unit')))\ .aggregate(total_leasing=Sum('price')) other_expenses = Expenses.objects\ .filter(date__gte = "2023-11-01", date__lte = "2023-11-30", type_of_expense = "other")\ .annotate(price=Sum(F('quantity')*F('price_per_unit')))\ .aggregate(total_other_expenses=Sum('price')) ... Here is the model.py I've created class Expenses(models.Model): date = models.DateField() place_of_expense = models.ForeignKey(ConstructionSite, on_delete=models.CASCADE, blank=True, null=True) TYPE_OF_EXPENSE_CHOICES = ( ("oil", "oil"), ("leasing", "leasing"), ("material", "material"), ("land leasing", "land leasing"), ("spare parts", "spare parts"), ("tools and equipment", "tools and equipment"), ("services", "services"), ("accountant expenses", "accountant expenses"), ("interest rates", "interest rates"), ("phones", "phones"), ("other", … -
Django REST Framework: Custom Validator for Image URL Not Working as Expected
I'm currently working on a Django REST Framework project where I have a ProjectModel with both an image_file field (for uploaded images) and an image_url field (for externally hosted images). Additionally, I have a custom validator (ImageURLValidator) to validate the image_url field. The models and serializer classes look like this: models.py: from django.db import models class ProjectModel(models.Model): image_file = models.ImageField( null=True, blank=True, upload_to='project/%Y/%m/%d' ) image_url = models.URLField( null=True, blank=True ) serializers.py: from rest_framework import serializers from .validators import ImageURLValidator from .models import ProjectModel class ProjectSerializer(serializers.ModelSerializer): image_url = serializers.URLField( required=False, allow_null=True, allow_blank=True, validators=[ImageURLValidator()] ) class Meta: model = ProjectModel fields = ['id', 'image_file', 'image_url'] validators.py import requests from rest_framework import serializers from django.core import validators from django.utils.translation import gettext_lazy as _ class ImageURLValidator: def __call__(self, value): if not value.startswith(('http://', 'https://')): raise serializers.ValidationError( _("URL must start with 'http://' or 'https://'") ) try: validators.URLValidator()(value) except serializers.ValidationError: raise serializers.ValidationError( _("Invalid URL format") ) # Fetch content from URL and check image format response = None try: response = requests.get(value) response.raise_for_status() # Check for error status except requests.exceptions.RequestException as e: raise serializers.ValidationError( _("Error fetching content from URL: %(error)s") % {'error': str(e)} ) content_type = response.headers['content-type'] if not content_type.startswith(('image/')): raise serializers.ValidationError( _("URL must point to an … -
Dynamically change used database table while django app is running?
I want to create a service that has a page to configure a data base table (columns and types) and that allows to CRUD lines in it via the page. The content of that table should then be used for comparison with payload of rest api call. I am quite new to django and don't know if that approach is possible with the django ORM. What I saw so far is that one defines the database scheme hardcoded and I didn't see how I can make my concept running with this. If not I am thinking about representing and managing this dynamically created table via a json or likewise object that is stored in an object database. -
Basic Django Chat Using Sockets Not Sending To The Browser
If anybody can help with this conundrum. This is the django socket server for an absolutly un authenticated chat, everything is working upto saving the entry to the database. But the send event is not reaching the browser. import asyncio import websockets from asgiref.sync import sync_to_async from django.core.management.base import BaseCommand, CommandError from pages.models import Message clients = [] class Command(BaseCommand): help = "Start Web Sockets" def handle(self, *args, **options): global clients @sync_to_async def update(data): print('** Saving **') message = Message(message=data) message.save() async def handler(websocket): while True: data = await websocket.recv() print('** Received **') clients.append({'websocket': websocket}) await update(data) print('** Broadcasting **') for client in clients: this_websocket = client['websocket'] await this_websocket.send(data) print('** Sent **') async def main(): async with websockets.serve(handler, "localhost", 8765): await asyncio.Future() # run forever asyncio.run(main()) In the browser I have the following code submit works as it triggers the socket server to respond and save the data to the database, yet it dosn't send anything to the browser. $(document).ready(function(){ // Open Web Socket websocket = new WebSocket("ws://localhost:8765/"); // Display Submitted Messages websocket.addEventListener('message', function (event) { console.log('** Recieved Message **'); var html = '<div class="s-chat__message">' html += event.data; html += '</div>'; }); // Submit A Message $('#message').submit(function(evt){ evt.preventDefault(); websocket.send($('#id_message').val()); $('#message-input').val(''); … -
limiting choices shown in a the template
I have a list of time choices for booking a table in my model, when user want to book a table he will selec the time from the choices, but i want that as user select the time this time won't be shown again as available until the booking has been canceled or marked as "used". My model... class BookingTable(models.Model): TIME_CHOICES =[ (time(8,0), '08:00'), (time(9,0), '09:00'), (time(10,0), '10:00'), (time(11,0), '11:00'), (time(12,0), '12:00'), (time(13,0), '13:00'), (time(14,0), '14:00'), (time(15,0), '15:00'), (time(16,0), '16:00'), (time(17,0), '17:00'), (time(18,0), '18:00'), (time(19,0), '19:00'), (time(20,0), '20:00'), (time(21,0), '21:00'), ] table = models.ForeignKey(Table, on_delete=models.CASCADE) user = models.OneToOneField(get_user_model(), on_delete=models.CASCADE) time = models.TimeField(default='00:00', choices=TIME_CHOICES) def get_absolute_url(self): return reverse("list_tables") def __str__(self) -> str: return self.user.username + "-" + self.table.name class Meta: constraints = [ models.UniqueConstraint(fields=['table', 'time'], name='table_time') ] The view for booking table class BookTableView(LoginRequiredMixin, CreateView): model = BookingTable template_name = 'book_table.html' fields = ['time'] context_object_name = 'booking' def form_valid(self, form): user_bookings = BookingTable.objects.filter(user_id=self.request.user.id) if len(user_bookings) == 0: form.instance.user = self.request.user table = self.get_object(Table.objects) table.save() form.instance.table = table return super().form_valid(form) else: return render(self.request, 'booking_fail.html') -
I can't use get_foo_display in django template
I use 'choice set' in my model but I can't show their labels in template In model: class Malpractice_Detail(models.Model): DayTime_Choice={ ('morning','صبح'), ('noon','ظهر'), ('night','شب'), } Damage_Choice={ ('1','عدم آسیب'), ('2','آسیب به بیمار'), ('3','آسیب به پرسنل'), ('4','آسیب به تجهیزات پزشکی'), } malperactice_choice={ ('1','خطاهای دارویی'), ('2','خطاهای احیاء قلبی-ریوی'), ('3','خطادرتزریقات وخونگیری'), ('4','خطادر ثبت اطلاعات وثبت پرونده'), ('5','خطاهای مراقبتی وبالینی'), ('6','اشتباهات پاراکلینیکی'), ('7','اشتباهات جراحی'), ('8','خطاهای تشخیصی پزشک'), ('9','اشتباهات تجهیزاتی'), ('10','اشتباهات مدیریتی') } hospital=models.ForeignKey('Accounting.hospital', verbose_name='بیمارستان',null=True, on_delete=models.DO_NOTHING) name=models.CharField(max_length=50,verbose_name="نام شخصی که خطا از او سرزده",null=True, blank=True) unit=models.ForeignKey('Accounting.unit', verbose_name='بخش',null=False, on_delete=models.DO_NOTHING) time=models.CharField(max_length=10,choices=DayTime_Choice,null=False,blank=False,verbose_name='زمان وقوع') type=models.CharField(max_length=50,choices=malperactice_choice,null=True,blank=True,verbose_name="نوع خطا") date=models.DateField("تاریخ رخداد خطا", auto_now=False, auto_now_add=False) role=models.ForeignKey('role', verbose_name='سمت خطاکار',null=False,blank=False, on_delete=models.DO_NOTHING) damage=models.CharField(max_length=1,verbose_name='آسیب وارد شده',choices=Damage_Choice,default=1,null=False,blank=False) st_happened=models.TextField(max_length=1000,verbose_name='شرح خطای رخ داده',null=False,blank=False) decisions=models.TextField(max_length=1000,verbose_name='تصمیمات اتخاذ شده',null=True,blank=True) cause_of_accident=models.TextField(max_length=1000,verbose_name='دلیل رخداد خطا',null=True,blank=True) solution=models.TextField(max_length=1000,verbose_name='پیشنهاد و راهکار',null=True,blank=True) user=models.ForeignKey(User, on_delete=models.DO_NOTHING) reporting_datetime=models.DateTimeField(auto_now_add=True) is_seen=models.BooleanField(verbose_name='دیده شده',default=False,null=True,blank=True) has_followup=models.BooleanField(verbose_name='شرح پیگیری دارد',default=False,null=True,blank=True) has_feedback=models.BooleanField(verbose_name='شرح بازخورد دارد',default=False,null=True,blank=True) def __str__ (self): return str(self.st_happened) class Meta: ordering=['-reporting_datetime'] In View: def Index(request): form=Malpractice_Detail.objects.select_related('Hospital','Unit','Role').filter(user=request.user).values('unit__name','date','role__Name','damage','st_happened','is_seen','has_followup','has_feedback') return render(request,"malpractice/index.html",{'form':form}) In template: show damage code but not show damage label {% for item in form %} <td>{{item.date|to_jalali:'%Y/%m/%d'}}</td> <td>{{item.damage}}</td>## This show number of choice <td>{{item.get_damage_display}}</td> ##Not show label <td>{{item.st_happened}}</td> I reed many post about this and try solutions but don't work for me please help me for solve this problem -
"Optimizing Django Form/Table Reload for Improved Performance and Minimizing Page Reloads"
1-I'm encountering challenges with page reloading and performance optimization in my Django project. The primary issues involve the reload behavior of a form or table, where the entire page refreshes upon submission. i want only table elements or data will refresh or reload not the whole page will reload.. 2- the second issue is that it is taking too much time to reload or fetch or run queries can we make it faster.. this is my views.py- def Home(request): # Get the filtered data using RocCharge model from filters.py myfilter = Orderfilter(request.GET, queryset=RocCharge.objects.all().select_related('RocCharge')) # Logic for clearing all filter buttons if request.method == 'GET' and 'remove_filter' in request.GET: filter_name = request.GET['remove_filter'] myfilter.form[filter_name].initial = None elif 'remove_all_filters' in request.GET: for filter_name in myfilter.form.fields: myfilter.form[filter_name].initial = None # Showing or getting applied filters data combined_data = myfilter.qs.values( 'srn_no', 'charge_id', 'charge_holder_name', 'date_of_creation', 'date_of_modification', 'date_of_satisfaction', 'amount', 'address', 'existing_old', 'cin__state', 'cin__city', 'cin__company_name', 'cin__company_cin', 'cin__sector', 'cin__industry', ) from_date = request.GET.get('fromdate') to_date = request.GET.get('Todate') if from_date and to_date: combined_data = combined_data.filter(date_of_creation__gte=from_date, date_of_creation__lte=to_date) # download data logic/func.................................. if 'download_xlsx' in request.GET: filtered_data = myfilter.qs.values( 'charge_holder_name', 'date_of_creation', 'date_of_modification', 'date_of_satisfaction', 'amount', 'existing_old', 'cin__state', 'cin__city', 'cin__company_name', 'cin__company_cin', 'cin__sector', 'cin__industry' ) # Convert the filtered data to a DataFrame df = pd.DataFrame.from_records(filtered_data) … -
I am trying to create a virtual environment but its not working. even it exists there
Getting this error I tried at least 20 times but didn't work getting this error. activate : The term 'activate' is not recognized as the name of a cmdlet, function, script file, or operable program. Check the spelling of the name, or if a path was included, verify that the path is correct and try again. At line:1 char:1 activate + CategoryInfo : ObjectNotFound: (activate:String) [], CommandNotFoundException + FullyQualifiedErrorId : CommandNotFoundException Suggestion [3,General]: The command activate was not found, but does exist in the current location. Windows PowerShell does not load commands from the current location by default. If you trust this command, instead type: ".\activate". See "get-help about_Command_Precedence" for more details. PS C:\djangopracticeset\main\mainenv\scripts> -
Django: Concatenate two manytomany fields in one single field and save it in the database
I have these two models: class Person(models.Model): name = models.CharField(max_length=200) class Project(models.Model): project_info = models.CharField(max_length=200) project_manager = models.ManyToManyField(Person, related_name="project_manager") project_collaborator = models.ManyToManyField(Person, related_name="project_collaborator") I want to save in the database the field "project_info" with this concatenated value: "project_manager & project_collaborator". I tried to override the save method of the Project model: def save(self, *args, **kwargs): self.project_info = self.project_manager + '&' + self.project_collaborator super().save(*args, **kwargs) but it returns me the error "unsupported operand type(s) for +: 'ManyRelatedManager' and 'str'". -
SMTP.starttls() got an unexpected keyword argument 'keyfile' with django 3.2.23 and python 3.12.1
I'm trying to configure my web app to send confirmation emails after registration. I'm using Django 3.2.23 and Python 3.12.1 and my settings are : if 'DEVELOPMENT' in os.environ: EMAIL_BACKEND = 'django.core.mail.backends.console.EmailBackend' DEFAULT_FROM_EMAIL = 'boutiqueado@example.com' else: EMAIL_BACKEND = 'django.core.mail.backends.smtp.EmailBackend' EMAIL_USE_TLS = True EMAIL_PORT = 587 EMAIL_HOST = 'smtp.gmail.com' EMAIL_HOST_USER = os.environ.get('EMAIL_HOST_USER') EMAIL_HOST_PASSWORD = os.environ.get('EMAIL_HOST_PASS') DEFAULT_FROM_EMAIL = os.environ.get('EMAIL_HOST_USER'). I'm having this error message : TypeError at /accounts/signup/ SMTP.starttls() got an unexpected keyword argument 'keyfile' Request Method: POST Request URL: https://boutique-ado-mike-8ab1d2bb405e.herokuapp.com/accounts/signup/ Django Version: 3.2.23 Exception Type: TypeError Exception Value: SMTP.starttls() got an unexpected keyword argument 'keyfile' Exception Location: /app/.heroku/python/lib/python3.12/site-packages/django/core/mail/backends/smtp.py, line 67, in open Python Executable: /app/.heroku/python/bin/python Python Version: 3.12.1 Python Path: ['/app/.heroku/python/bin', '/app', '/app/.heroku/python/lib/python312.zip', '/app/.heroku/python/lib/python3.12', '/app/.heroku/python/lib/python3.12/lib-dynload', '/app/.heroku/python/lib/python3.12/site-packages'] Server time: Thu, 14 Dec 2023 09:57:01 +0000 I checked the EMAIL_HOST_USER and EMAIL_HOST_PASS and both are ok. The pass provided by gmail had spaces but I removed the spaces in the pass. The app is in production and all the vars are in heroku config vars. How can I solve this. I tryed to change EMAIL_USE_TLS = True to EMAIL_USE_SSL = True and port to 465 but the error persists. help please!!! -
Not able insert into Django modeling
my input is using JSON post request { "rawdata": [ { "id": "89729999", "name": "testname", "product": "testproduct", "modified_at": "2023-12-14T03:00:00.000Z", "modified_by": "personname", "asset": { "configname": ["testconfig"], "serialnumber": ["testserialnumber"] "owner": ["owner1","owner2"] } } ] } model.py class Host(models.Model): id = models.CharField(primary_key=True, max_length=15) name = models.CharField(max_length=80) product = models.CharField(max_length=50) modified_at = models.DateTimeField() modified_by = models.CharField(max_length=50) class Hostinfo(models.Model): fk = models.ForeignKey(Host, on_delete=models.CASCADE) ## id parameter_section = models.CharField(max_length=40) parameter = models.CharField(max_length=80) parameter_index = models.IntegerField() ## index value = models.CharField(max_length=200, null=True) modified_at = models.DateTimeField() modified_by = models.CharField(max_length=50) view.py @api_view(('POST',)) def hostrequest(request): data=request.data.get('rawdata') print(data) try: for item in data: host=Host() host.cmdbid = item['cmdbid'] host.name = item['name'] host.product =item['product'] host.modified_at= item['modified_at'] host.modified_by= item['modified_by'] host.save() hostparameter = Hostinfo() for parameter_section in item: if parameter_section != "cmdbid" and parameter_section != "name" and parameter_section != "product" and parameter_section != "modified_at" and parameter_section != "modified_by": detailData = item[parameter_section] for parameter in detailData: parameters = detailData[parameter] for parameter_index in parameters: value = parameters[parameter_index] hostparameter.fk += item['cmdbid'] hostparameter.parameter_section += parameter_section['parameter_section'] hostparameter.parameter += parameter['parameter'] hostparameter.parameter_index += parameter_index['parameter_index'] hostparameter.value += value['value'] hostparameter.save() response_data={"error":False,"Message":"Updated Successfully"} return JsonResponse(response_data,safe=False,status=status.HTTP_201_CREATED) except: response_data={"error":True,"Message":"Failed to Update Data"} return JsonResponse(response_data,safe=False) i executed view script without any issue but i'm only able insert value into host. But not able insert into Hostinfo. Anyone could … -
How can i configure Django-Cors-Header properly
I deployed my django app on fly.io. When accessing api endpoints with swagger, I get this error in the console; " The page at 'https://bookinventory.fly.dev/' was loaded over HTTPS, but requested an insecure resource 'http://bookinventory.fly.dev/api/view/1'. This request has been blocked; the content must be served over HTTPS. Cors has been installed with settings from the docs. I have set; CORS_ALLOW_ALL_ORIGINS = True CSRF_TRUSTED_ORIGINS = [ 'https://bookinventory.fly.dev', 'http://bookinventory.fly.dev'] And the middleware and installed apps has all ben configured for cors