Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Finding database records that has the same date with specific timezone in django
So I have making a webpage that allows the end user to choose start date and end date. Then the reactjs frontend will send a POST request with a payload that containing the start date and end date chosen on the datepicker provided by the react-datepicker. After passing the start date and end date to the django server, I would like to group the records that have same date and come up with total number of records for each day then return a list of totals. Note that in the django server( settings.py ) has USE_TZ=true, TIME_ZONE='Asia\Kuala Lumpur'. Would like to have a list of totals in such format [ totalFirstDay, totalSecondDay, totalThirdDay, totalFourthDay, ... ] This is my current attempt to get my desired results def getTotalRecordsEachDay(request): ## for example request.POST['startDate'] == "2021-09-30T16:00:00.000Z" startDate = timezone.now().strptime(request.POST['startDate'], '%Y-%m-%dT%H:%M:%S.%fZ')+timedelta(days=1) ## for example request.POST['endDate'] == "2021-10-30T16:00:00.000Z" endDate = timezone.now().strptime(request.POST['endDate'], '%Y-%m-%dT%H:%M:%S.%fZ')+timedelta(days=2, microseconds=-1) totalFoundEachDay = [] sameDay = startDate.date() ## In Mode.py, createDate = models.DateTimeField(default=timezone.now) statistics = models.MemberCard.objects.filter(createDate__date__range=[startDate, endDate]) if len(statistics) > 0: noOfRecord=0 totalRecordsSameDay = 0 for item in statistics: noOfRecord+=1 if(sameDay == item.createDate.date()): totalRecordsSameDay+=1 if(noOfRecord == len(statistics)): totalFoundEachDay.append(totalRecordsSameDay) else: totalFoundEachDay.append(totalRecordsSameDay) sameDay = sameDay + timezone.timedelta(days=1) totalRecordsSameDay = 0 if(sameDay == item.createDate.date()): totalRecordsSameDay+=1 … -
IsADirectoryError while merging project with template Django
I'm fairly new to Django and I've been creating an app using the startproject and startapp calls but with a few tweaks based on TwoScoops' recommendations that follow cookiecutter. I was trying to now merge my work into a template provided Soft UI Dashboard that uses Bootstrap 5. Unfortunately, while doing that, I've run into a few conflicts which I have been successful at solving so far, but the one I''m stuck with right now is [Errno 21] Is a directory: '/Users/mashfadel/Desktop/django-soft-ui-dashboard-master/jarvisai/templates/home' Here's the traceback code: Environment: Request Method: GET Request URL: http://127.0.0.1:8000/upload/ Django Version: 3.2.8 Python Version: 3.9.1 Installed Applications: ['django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'jarvisai.home', 'jarvisai.books'] Installed Middleware: ['django.middleware.security.SecurityMiddleware', 'whitenoise.middleware.WhiteNoiseMiddleware', 'django.contrib.sessions.middleware.SessionMiddleware', 'django.middleware.common.CommonMiddleware', 'django.middleware.csrf.CsrfViewMiddleware', 'django.contrib.auth.middleware.AuthenticationMiddleware', 'django.contrib.messages.middleware.MessageMiddleware', 'django.middleware.clickjacking.XFrameOptionsMiddleware'] Traceback (most recent call last): File "/Users/mashfadel/Desktop/django-soft-ui-dashboard-master/venv/lib/python3.9/site-packages/django/core/handlers/exception.py", line 47, in inner response = get_response(request) File "/Users/mashfadel/Desktop/django-soft-ui-dashboard-master/venv/lib/python3.9/site-packages/django/core/handlers/base.py", line 181, in _get_response response = wrapped_callback(request, *callback_args, **callback_kwargs) File "/Users/mashfadel/Desktop/django-soft-ui-dashboard-master/venv/lib/python3.9/site-packages/django/contrib/auth/decorators.py", line 21, in _wrapped_view return view_func(request, *args, **kwargs) File "/Users/mashfadel/Desktop/django-soft-ui-dashboard-master/jarvisai/home/views.py", line 34, in pages html_template = loader.get_template('home/' + load_template) File "/Users/mashfadel/Desktop/django-soft-ui-dashboard-master/venv/lib/python3.9/site-packages/django/template/loader.py", line 15, in get_template return engine.get_template(template_name) File "/Users/mashfadel/Desktop/django-soft-ui-dashboard-master/venv/lib/python3.9/site-packages/django/template/backends/django.py", line 34, in get_template return Template(self.engine.get_template(template_name), self) File "/Users/mashfadel/Desktop/django-soft-ui-dashboard-master/venv/lib/python3.9/site-packages/django/template/engine.py", line 143, in get_template template, origin = self.find_template(template_name) File "/Users/mashfadel/Desktop/django-soft-ui-dashboard-master/venv/lib/python3.9/site-packages/django/template/engine.py", line 125, in find_template template = … -
Sum values based on same keys in dict and make array
Hi guys I have data like this [ { 'name': 'snow 7', 'count': 1, 'rows_processed': None, 'pipelines': 1 }, { 'name': 'snow 6', 'count': 1, 'rows_processed': None, 'pipelines': 1 }, { 'name': 'snow 6', 'count': 1, 'rows_processed': None, 'pipelines': 1 }, { 'name': 'snow 6', 'count': 2, 'rows_processed': None, 'pipelines': 2 }, { 'name': 'snow 5', 'count': 2, 'rows_processed': 4, 'pipelines': 2 }, { 'name': 'snow 4', 'count': 2, 'rows_processed': None, 'pipelines': 2 } ] and i want to sum the values of rows_processed and pipelines based on name key like for snow 6 pipelines sum will be 4 and so on, basically the final data should look like this. { "Rows Processed": [0, 0, 4, 0], "Pipelines Processed": [1, 4, 2, 2] } how can i make data like above? this is what i have done so for rows_processed = {} pipeline_processed = {} for batch in batches: for label in batches.keys(): rows_processed[label] = rows_processed.get(batch['rows_processed'], 0) + batch['rows_processed'] if batch['rows_processed'] else 0 for batch in batches: for label in batches.keys(): pipeline_processed[label] = pipeline_processed.get(batch['pipelines'], 0) + batch['pipelines'] if \ batch['pipelines'] else -
Display django intergerfield model as dropdown select with range min and max values for each option (django-filters)
Hi trying to display this model class Item(models.Model): number = models.IntegerField() like this: dropdown I am using django-filters and have the following filters.py file: class ItemFilter(django_filters.FilterSet): number = django_filters.RangeFilter() class Meta: model = Item fields = ['number'] The above works great for showing a range but I have to enter the min and max values manually What I would like to do is set predefined options with values for the min and max range of the RangeFilter Ideally, if I could set values into the below html that would be great <select data-style="btn-white" class="selectpicker"> <option>0-10</option> <option>10-50</option> <option>100-250</option> <option>250-500</option> <option>500-1000</option> <option>1000-2000</option> <option>2000+</option> </select> Any ideas would be appreciated -
Javascript- how to show table row based on checkbox
I want to display the table row based on the checkbox selection where I need to display only the particular row. I'm noob in JavaScript how could I able to achieve it. I Have tried many javascript snippet from the stackoverflow as well but it didn't worked as expected.pls.help me out to get this.Thanks in advance Here is my html <div>Country</div> <div class="row" name="country_checkbox" id="id_row" onclick="return filter_type(this);"> <ul id="id_country"> <li><label for="id_country_0"><input type="checkbox" name="country" value="NORTHAMERICA" placeholder="Select Country" id="id_country_0"> NORTHAMERICA</label> </li> <li><label for="id_country_3"><input type="checkbox" name="country" value="LATAM" placeholder="Select Country" id="id_country_3"> LATAM</label> </li> <li><label for="id_country_2"><input type="checkbox" name="country" value="ASIA" placeholder="Select Country" id="id_country_2">ASIA</label> </li> </ul> </div> <table class="datatable" id='table_id'> <thead> <thead> <tr> <th>Region</th> <th> Area </th> <th> Country </th> </tr> </thead> <tbody> <tr id="trow"> {% for i in database%} <td>i.Region</td> <td>i.Area </td> <td>i.Country</td> {% endfor %} </tr> </tbody> -
Sum values of same keys from dict and make array [closed]
Hi guys I have data like this [ { 'name': 'snow 7', 'count': 1, 'rows_processed': None, 'pipelines': 1 }, { 'name': 'snow 6', 'count': 1, 'rows_processed': None, 'pipelines': 1 }, { 'name': 'snow 6', 'count': 1, 'rows_processed': None, 'pipelines': 1 }, { 'name': 'snow 6', 'count': 2, 'rows_processed': None, 'pipelines': 2 }, { 'name': 'snow 5', 'count': 2, 'rows_processed': 4, 'pipelines': 2 }, { 'name': 'snow 4', 'count': 2, 'rows_processed': None, 'pipelines': 2 } ] and i want to sum the values of rows_processed and pipelines based on name key like for snow 6 pipelines sum will be 4 and so on, basically the final data should look like this. { "Rows Processed": [0, 0, 4, 0], "Pipelines Processed": [1, 4, 2, 2] } how can i make data like above? this is what i have done so for rows_processed = {} pipeline_processed = {} for batch in batches: for label in batches.keys(): rows_processed[label] = rows_processed.get(batch['rows_processed'], 0) + batch['rows_processed'] if batch['rows_processed'] else 0 for batch in batches: for label in batches.keys(): pipeline_processed[label] = pipeline_processed.get(batch['pipelines'], 0) + batch['pipelines'] if \ batch['pipelines'] else -
str' object has no attribute 'get Django Python
Now I have one more problem. Could you please help? Thank You in advance :) An error: AttributeError: 'str' object has no attribute 'get'. . And the code password_form = PasswordsForm(request.POST or None) if password_form.is_valid(): password = password_form.save() try: for i in password.text: value = (alphabet[i]) klucz = 10 new_value = int(value) + klucz if new_value > 70: new_value = new_value - 70 for key, value in alphabet.items(): if value == str(new_value): print(key, end='') return '' except KeyError: return ('Nie znaleziono wartości' + i + ' w słowniku!') return render(request,'kod.html', {'key': key}) return render(request, 'start.html', {'password_form': password_form}) ``` I would be grateful for answer ! Natalia -
ImportError: attempted relative import with no known parent package DJANGO
I am following a tutorial on how to work with django and i cant figure out what this error happens. This is Admin.py from django.contrib import admin from .models import Genre, Movie class GenreAdmin(admin.ModelAdmin): list_display = ('id', 'name') admin.site.register(Movie) admin.site.register(Genre, GenreAdmin) and this is models.py: from django.db import models from django.utils import timezone class Genre(models.Model): name = models.CharField(max_length=255) def __str__(self): return self.name class Movie(models.Model): title = models.CharField(max_length=255) release_year = models.IntegerField() number_in_stock = models.IntegerField() daily_rate = models.FloatField() genre = models.ForeignKey(Genre, on_delete=models.CASCADE) date_created = models.DateTimeField(default=timezone.now) There are in the same parent folder. -
How to override existing '/api/products/' to return more fields in Django-osacr-api?
Django-oscar-api-override setup I am new to Oscar Api, And I need to added extra fields to the default '/api/products' response. Additional fields to add: description, meta_title, meta_description, rating, attributes from oscar.core.loading import get_class from rest_framework import serializers from oscarapi.serializers import checkout, product from oscarapi.serializers.product import ( ProductImageSerializer, ProductLinkSerializer) class MyProductLinkSerializer(ProductLinkSerializer): images = ProductImageSerializer(many=True, required=False) class Meta(ProductLinkSerializer.Meta): fields = ('url', 'id', 'title', 'images', 'rating', 'meta_title', 'meta_description') I tried the above code from documentation to see if it overrides. But no luck. Can you please help to add additional fields to the default response ? or point me any sample project repo where you they overrided default response. Thank you in advance. -
'undefined likes' twitter like project
Recently I started working on a twitter like clone to learn some python and django. I have successfully added "tweets" and got them to display some basic text on my homepage. My issue is with the like button. I am attempting to have a like button that will display the total amount of likes on that "tweet". For now I am using a random int just to display the likes. However the button just displays "undefined Likes". I thought it was going to be pretty straight forward however i am still new to all this so any help pointing me in the right direction would be appreciated. Thanks all. views.py: import random from django.http import HttpResponse, Http404, JsonResponse from django.shortcuts import render from .models import Prediction # Create your views here. def home_view(request, *args, **kwargs): return render(request, "pages/home.html", context={}, status=200) def prediction_list_view(request, *args, **kwargs): """ REST API VIEW Consume by JavaScript or Swift/Java/iOS/Andriod return json data """ qs = Prediction.objects.all() predictions_list = [{"id": x.id, "content": x.content, "likes": random.randint(0, 122)} for x in qs] data = { "isUser": False, "response": predictions_list } return JsonResponse(data) def prediction_detail_view(request, prediction_id, *args, **kwargs): """ REST API VIEW Consume by JavaScript or Swift/Java/iOS/Andriod return json data … -
TypeError: object of type 'Listeningfilter' has no len()
this error appear when using django-filter with pagination. this my filter.py, view.py code. I need to add pagination to django-filter I display data in html table. the error appear in this Listening_filter = paginator.get_page(page_number) line. class Listeningfilter(django_filters.FilterSet): listentime = django_filters.DateFromToRangeFilter( label='By Date Range', method='filter_by_range', widget=RangeWidget(attrs={'class': 'datepicker', 'type': 'date'}) ) class Meta: model = Listening fields = [ 'listentime', 'serviceshortcode', ] def filter_by_range(self, queryset, name, value): listenTime_from = value.listenTime_from listenTime_to = value.listenTime_to return queryset.filter(transaction_time__gte=listenTime_from, transaction_time__lte=listenTime_to) def listeningReportView(request): Listening_filter = '' form = ListeningSearchForm(request.POST or None) if request.method == 'POST': listenTime_from = request.POST.get('listenTime_from') listenTime_to = request.POST.get('listenTime_to') serviceCode = request.POST.get('serviceCode') Listening_filter = Listeningfilter( request.GET, queryset = Listening.objects.filter(listentime__lte=listenTime_to, listentime__gte=listenTime_from, serviceshortcode=serviceCode).order_by('listeningid'), ) # pagination paginator = Paginator(Listening_filter , 2) page_number = request.GET.get('page') try: Listening_filter = paginator.get_page(page_number) except EmptyPage: Listening_filter = paginator.page(paginator.num_pages) if not Listening_filter: messages.error(request, "no data availabe") context = { 'form': form, 'Listening_filter': Listening_filter, } return render(request, 'charge/listening.html', context) -
Unable to see the lines in chart.js
I am trying to make a django website which will display a chart that is updated every 1sec. I dont know why but except for the lines everything else is getting update a snapshot of the graph with the console log. the code below is my jquery in the html page {% block jquery %} <script> var updateInterval = 20 //in ms var numberElements = 5 var values = [] //Globals var updateCount = 0 var endpoint = '/api/chart/data' var ctx = document.getElementById('myChart'); var gchart = new Chart(ctx, { type: 'line', data: { label: [], datasets: [{ label: 'Wholesale 24 K', data: [], fill: true, borderColor: 'rgb(245, 0, 0)', tension: 0.1, parsing: { yAxisKey: 'b1' } }, { label: 'Retail 24 K', data: [], fill: true, borderColor: 'rgb(245, 225, 0)', tension: 0.1, parsing: { yAxisKey: 's24K' } }] }, options: { interaction: { mode: 'index', } }, }) function addData(chart, label, data) { console.log(data) chart.data.labels.push(label); chart.data.datasets.forEach((dataset) => { dataset.data.push(data); }); if (updateCount > numberElements) { gchart.data.labels.shift(); gchart.data.datasets[0].data.shift(); gchart.data.datasets[1].data.shift(); } else updateCount++; chart.update(); } setInterval(ajaxcal, 1000) function ajaxcal() { $.ajax({ method: "GET", url: endpoint, success: function (data) { var lal = data.time addData(gchart, lal, data) }, error: function (error_data) { console.log(error_data) … -
Django generate template doesn't correct
Django generate wrong template, why? code: <a class="one_menu_part" href="{% url 'projects_list' %}"> <img src="{% static 'icons/projects.svg' %}" alt=""> Projects <ul class="projects_list"> {% for project in projects %} <li class="project_part"><a href="{{ project.url }}">{{ project.title }}</a></li> {% endfor %} </ul> </a> <hr> <a class="one_menu_part" href="{% url 'admin_panel:admin_panel' %}"> <img src="{% static 'icons/admin_settings.svg' %}" alt=""> Admin Setting </a> in browser: Why ul generate after tag A, but in code tag ul must generate in tag A -
Unexpected result : "detail": "Method \"GET\" not allowed."
I am learning django restframework for the first time , and I am not able to debug this error since a while , please help in debugging this issue. Thanks! HTTP 405 Method Not Allowed Allow: POST, OPTIONS Content-Type: application/json Vary: Accept { "detail": "Method \"GET\" not allowed." } Here is my code of views.py from django.shortcuts import render from rest_framework import generics, status from .serializers import RoomSerializer, CreateRoomSerializer from .models import Room from rest_framework.views import APIView from rest_framework.response import Response class RoomView(generics.ListAPIView): queryset = Room.objects.all() serializer_class = RoomSerializer class CreateRoomView(APIView): serializer_class = CreateRoomSerializer def post(self, request, format=None): if not self.request.session.exists(self.request.session.session_key): self.request.session.create() serializer = self.serializer_class(data=request.data) if serializer.is_valid(): guest_can_pause = serializer.data.get('guest_can_pause') votes_to_skip = serializer.data.get('votes_to_skip') host = self.request.session.session_key queryset = Room.objects.filter(host=host) if queryset.exists(): room = queryset[0] room.guest_can_pause = guest_can_pause room.votes_to_skip = votes_to_skip room.save(update_fields=['guest_can_pause', 'votes_to_skip']) return Response(RoomSerializer(room).data, status=status.HTTP_200_OK) else: room = Room(host=host, guest_can_pause=guest_can_pause, votes_to_skip=votes_to_skip) room.save() -
Django: QuerySet.update() returns FieldError when using Count() with filter
Given that: class User(models.Model): organization = models.ForeingKey( "Organization", related_name="users", ... ) is_active = models.BooleanField(default=True) class Organization(models.Model): user_count = models.IntegerField(default=0) When I run this, if we run line 2 or 3 exclusively, both fail: # Line: 1 active_count = Count("users", filter=Q(users__is_active=True)) # Line: 2 Organization.objects.update(user_count=active_count) # Line: 3 Organization.objects.annotate(num_users=active_count).update(user_count=F("num_users") I get the following error: FieldError: Joined field references are not permitted in this query Annotating (annotate()) instead of updating, works just fine. I couldn't find examples of this solution using Subquery() What's an alternative to this requirement? Am doing making a design mistake perhaps? -
Models Django not iterable
I have some problems with Django models, I would like to iterate data got from the textfield from the form based on model. But I can't it still an error: TypeError at /kod/start/ 'Passwords' object is not iterable Request Method: POST Request URL: http://127.0.0.1:8000/kod/start/ Django Version: 3.2.8 Exception Type: TypeError Exception Value: 'Passwords' object is not iterable Exception Location: /home/natalia/PycharmProjects/django_project/kodszyfru/views.py, line 52, in start Python Executable: /home/natalia/PycharmProjects/django_project/venv/bin/python3 Python Version: 3.8.10 Python Path: ['/home/natalia/PycharmProjects/django_project', '/usr/lib/python38.zip', '/usr/lib/python3.8', '/usr/lib/python3.8/lib-dynload', '/home/natalia/PycharmProjects/django_project/venv/lib/python3.8/site-packages'] Server time: Fri, 22 Oct 2021 16:03:53 +0000 Code models.py from django.db import models # Create your models here. class Passwords(models.Model): text = models.TextField(max_length=2000,null=True) cipher = models.CharField(max_length=64) def __str__(self): return self.text views.py def start(request): password_form = PasswordsForm(request.POST or None) if password_form.is_valid(): text = password_form.save() try: for i in text: value = (alphabet[i]) klucz = 10 new_value = int(value) + klucz if new_value > 70: new_value = new_value - 70 for key, value in alphabet.items(): if value == str(new_value): print(key, end='') return '' except KeyError: return ('Nie znaleziono wartości' + i + ' w słowniku!') return render(request, 'kod.html', {'kod': kod}) return render(request, 'start.html', {'password_form': password_form}) I would be grateful for help!! Natalia -
Apply filter to field with lookup
I have seen a couple of similar questions on StackOverflow (Troubleshooting "Related Field has invalid lookup: icontains", Django error Related Field got invalid lookup: icontains, Related Field got invalid lookup: icontains, Django: Unsupported lookup 'case_exact' for CharField or join on the field not permitted, Filtering on Foreign Keys in Django) but unfortunately the answers on those questions have not helped me. If a hotel only has four double rooms and there are already four bookings for the first week of October, I want to prevent the next user being able to make a fifth booking for the first week of October. This was working - RoomBookings.objects.filter(HotelName__icontains=hotel.HotelName, RoomType__icontains= hotel.RoomType, ArrivalDate__lt=RoomBookingsForm['DepartureDate'], DepartureDate__gt=RoomBookingsForm['ArrivalDate']) But then I changed the HotelName field in the RoomBookings model from CharField to ForiegnKey. And now I cannot figure out how to do a reverse lookup. These are my failed attempts - # queryset2 = RoomBookings.objects.filter(HotelName__HotelName__icontains=hotel.HotelName) # queryset2 = RoomBookings.objects.filter(HotelName__Hotel__HotelName__icontains=hotel.HotelName) # queryset2 = RoomBookings.objects.filter(HotelName__Hotel__HotelName_exact=hotel.HotelName) # queryset2 = RoomBookings.objects.filter(HotelName__HotelName_exact=hotel.HotelName) class Hotel(models.Model): HotelName = models.CharField(max_length=60, null=False) HotelOwner = models.CharField(max_length=60, null=True) FirstLineAddress = models.CharField(max_length=60, null=False) SecondLineAddress = models.CharField(max_length=60, null=True) PostCode = models.CharField(max_length=60, null=False) Country = CountryField(max_length=120, null=True) PhoneNumber = PhoneNumberField(null=True, blank=False, unique=True) Email = models.EmailField(max_length=254) def __str__(self): return self.HotelName class RoomType(models.Model): HotelName … -
How to add new field in model after custom migration which access model before new field?
I have custom migration file which creates entry in table user. Initial working project has these migrations: 1. 001_initial.py # creates model with some fields 2. 002_custom_user_data.py # adds data in "user" due some middle requirement after some time. Now I want to add one more column to this table as "config_data". For this I have followed below steps: 1. python manage.py makemigrations <app-name> # creates one more migration file` 003_add_config_data_field.py 2. python manage.py migrate # raise an error migrate command raises below error. Applying my_user.001_initial.py... OK Applying my_user.002_custom_user_data.py ...Traceback (most recent call last): File "/home/myhome/.local/share/virtualenvs/myproject/lib/python3.9/site-packages/django/db/backends/utils.py", line 84, in _execute return self.cursor.execute(sql, params) psycopg2.errors.UndefinedColumn: column my_user.config_data does not exist LINE 1: ..., "my_user"."address", This is because migration 002 tries to access my_user table before the add field migration(003) is migrated in the table, which is raising UndefinedColumn config_data error. Any idea how can be this resolved as these migrations should work for fresh DB as well as production dB in which till 002 is migrated earlier. Below is the migration for 002_custom_user_data.py # Generated by Django 3.2.2 from django.db import migrations from myapp.models import MyUser def create_user(apps, schema_editor): user = MyUser.objects.get_or_create(id=123) user.address = 'demo' user.save() def delete_user(apps, schema_editor): MyUser.objects.filter(id=123).delete() class … -
When I loop through from the database and render it to the page with VUE-Js v-for , it becomes disorganized
So when I loop through my data from the API, I am trying to fit the data into bootstrap rows and columns, but it keeps getting rendered wrongly. I am using the VUE-Js v-for directive to loop through the data I am getting from my Django rest API.[enter image description here][1] This is when I pass the data to the component [[1]: https://i.stack.imgur.com/UGtRp.png][1] This is when I am trying to loop through the data[ [1]: https://i.stack.imgur.com/OjsZF.png][2] This is how it renders to the page [[1]: https://i.stack.imgur.com/bRZRy.png ] -
¿Como filtrar las opciones de un campo select en base al valor de otro campo del mismo tipo en un formulario Django? [closed]
El problema que tengo es el siguiente, quiero acceder al valor seleccionado en tiempo real de un campo select en mi formulario y en base a este, filtrar las opciones para el cliente. El campo en específico es el que corresponde en el model Request al atributo product_type, el cual según la opción que seleccione a partir de un choice, se filtre el segundo campo, el de product (Product tiene una fk que apunta al product_type) mis models.py class ProductType(models.Model): name = models.CharField("Nombre", max_length=100) def __str__(self): return f'{self.name}' class Product(models.Model): name = models.CharField("Producto", max_length=250) price = models.IntegerField("Price") type = models.ForeignKey(ProductType, on_delete = models.CASCADE) def __str__(self): return f'{self.name}' class Request(models.Model): CUSTOMER_TYPE = [ ('IND', 'Individuos'), ('NEG', 'NEGOCIOS'), ] COMPANIES = [ ('CLA', 'Claro'), ('PER', 'Personal'), ('TUE', 'Tuenti'), ('MOV', 'Movistar'), ('OTR', 'Otro'), ] types = ProductType.objects.all() PRODUCT_TYPE = [] for o in types: key = o.name[:3] value = o.name t = (key,value) PRODUCT_TYPE.append(t) customer_type = models.CharField(max_length=150, choices=CUSTOMER_TYPE) product_type = models.CharField(max_length = 150, choices = PRODUCT_TYPE) product = models.ForeignKey(Product, on_delete=models.CASCADE) date_of_sale = models.DateTimeField(auto_now_add=True) request_source = models.ForeignKey(RequestSource, on_delete=models.CASCADE) seller = models.ForeignKey(User, on_delete=models.CASCADE) customer = models.ForeignKey(Customer, on_delete=models.CASCADE) #Portability current_company = models.CharField(max_length=150, choices=CUSTOMER_TYPE) mobile_to_carry = models.CharField("Número a portar", max_length=13) pin = models.IntegerField("Pin") #Internet services address_coordinates = … -
Please help: Reverse for 'all_clients' with keyword arguments '{'client_id': 3}' not found. 1 pattern(s) tried: ['clients/all_clients/$']
I am new to django and I am having trouble implementing the edit template to my project. I am encountering the following error: Reverse for 'all_clients' with keyword arguments '{'client_id': 3}' not found. 1 pattern(s) tried: ['clients/all_clients/$'] I have looked on the site for similar occurrences such as Reverse for 'plan_edit' with keyword arguments but I haven't been able to pin point the issue. I believe the issue arises when I add a hyperlink to my all_clients.html template. Also, the template pages for /clients/edit_client/?/ will load, however after submission using the save changes button the NoReserse Match error resurfaces as it attempts to load the clients/all_clients page. Any help on this matter would be greatly appreciated. See code below: models.py from django.db import models # Create your models here. class Client(models.Model): #A client is composed of the company general info text = models.CharField('Company Name',default = 'Company Name', max_length = 200) phone_num = models.CharField('Phone Number', default = '000-000-000', max_length = 12) ceo_name = models.CharField ('CEO', max_length = 50) num_employees = models.IntegerField('Number of Employees', default = 0) maintenance_schedule = models.CharField('maintenance schedule', max_length = 100) date_added = models.DateTimeField(auto_now_add=True) def __str__(self): """Return a string representation of the model.""" return self.text class Location(models.Model): #Location holds … -
Can I delete the third-party Python library `future` after moving exclusively to Python 3?
The future module (https://pypi.org/project/future/) is "the missing compatibility layer between Python 2 and Python 3." I have a Django project that was ported from Python 2 to 3 long ago, but future is still a requirement. My question is: now that the project only needs to run on Python 3, is there much danger in deleting the requirement for future? My own investigations: After deleting future from requirements.txt, the unit tests still pass. Grepping my project source, I don't see any imports of builtins, which future shadows in Python 2. The future docs say The imports have no effect on Python 3. On Python 2, they shadow the corresponding builtins, which normally have different semantics on Python 3 versus 2, to provide their Python 3 semantics. So deleting future seems pretty safe, but is there anything I'm missing? Thanks. -
+static(settings.MEDIA_URL,document_root=settings.MEDIA_ROOT) TypeError: 'module' object is not callable
here is my django project's urls.py from django.urls import path from .import views from django.conf import settings from django.conf.urls import static urlpatterns = [ path('',views.index,name='home'), path('abouts/about/',views.about,name='about'), path('abouts/contact/',views.contact,name='contact'), path('orders/cart/',views.cart,name='cart'), path('shops/dashboard/',views.dashboard,name='dashboard'), path('shops/orders/',views.orders,name='orders'), path('shops/checkout/',views.checkout,name='checkout'), ] +static(settings.MEDIA_URL,document_root=settings.MEDIA_ROOT) and the part of settings.py where I defined media url and media root import os # Default primary key field type # https://docs.djangoproject.com/en/3.2/ref/settings/#default-auto-field DEFAULT_AUTO_FIELD = 'django.db.models.BigAutoField' STATICFILES_DIRS = [ BASE_DIR/ 'static', ] STATIC_ROOT = os.path.join(BASE_DIR, 'assets') MEDIA_URL='/media/' MEDIA_ROOT = os.path.join(BASE_DIR, 'media') but the server says ile "C:\Users\ITS\Desktop\e-com\commerce\shop\urls.py", line 15, in <module> ] +static(settings.MEDIA_URL,document_root=settings.MEDIA_ROOT) TypeError: 'module' object is not callable I do this always but now it showing me this. thanks in advance for helping. -
show the particular table row based on checkbox
I want to display the table row based on the multi choice selection where I'm retrieving the data from the database there would be 1000+ rows among that I need to display only the particular row. I'm noob in JavaScript and took this snippet from How to show table rows based on checkbox selected I tried to modify the code as per the requirement but I couldn't able to figure out. I have cut the td part to reduce the code length there would be 16 columns around. pls help me out if any other JS script would be provided also it would be much helpful. <div>Country</div> <div class="row" name="country_checkbox" id="id_row" onclick="return filter_type(this);"> <ul id="id_country"> <li><label for="id_country_0"><input type="checkbox" name="country" value="NORTHAMERICA" placeholder="Select Country" id="id_country_0"> NORTHAMERICA</label> </li> <li><label for="id_country_3"><input type="checkbox" name="country" value="LATAM" placeholder="Select Country" id="id_country_3"> LATAM</label> </li> <li><label for="id_country_2"><input type="checkbox" name="country" value="ASIA" placeholder="Select Country" id="id_country_2">ASIA</label> </li> </ul> </div> <table class="datatable" id='table_id'> <thead> <thead> <tr> <th>Region</th> <th> Area </th> <th> Country </th> </tr> </thead> <tbody> <tr id="trow"> {% for i in database%} <td>i.Region</td> <td>i.Area </td> <td>i.Country</td> </tr> </tbody> <script> // checkbox selection function filter_type(box) { //alert("checked"); var cbs = document.getElementsByTagName('input'); var all_checked_types = []; for(var i=0; i < cbs.length; i++) { if(cbs[i].type == … -
Automatic reply/confirmation emails for Django CMS form
does anyone have experience with configuring/overriding the Django CMS FormPlugin to send out automatic confirmation emails?