Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Error when try to integrate payment system
I try to integrate payment system to django. I did use django-flexible-subscriptions, installed, created appropriate url, view and html. But when I created Subscription Plan and when tried to save get an error "conversion from NoneType to Decimal is not supported". Somebody knows how can I fix this error? Best regards -
How to get the day difference in a little complicated way using queryset in Django
I am using Django, and whenever the manager of a task is changed, the change is saved in the history field. The history field is saved as follows. Here, I would like to get the duration of each manager. EX: {'field_summary': {'manager': 'Michael -> Michael/Amelia', 'contact': '010-1234-1234-> 010-1234-1234/010-9876-9876'}} [models.py] Task(models.Model): task_name = models.CharField(max_length=100, blank=False) manager_name = models.CharField(max_length=100, blank=False) history = models.ForeignKey(History, on_deleted=models.SET_NULL) .... create_date = models.DateTimeField(auto_now_add=True) [views.py] task = Task.objects.filter(id='20', history__summary__icontains='manager') [statistic.html] {% for task in task %} {% for h in task.history %} {% if h.summary_json.field_summary.manager %} manager: {{ h.summary_json.field_summary.manager }} date: {{ h.create_date }}, {% endif %} {% endfor %} {% endfor %} [result] manager: Michael/Amelia -> Michael/Sophia change_date: 2022-02-25, manager: Michael -> Michael/Amelia change_date: 2021-10-12, manager: Michael/Amelia -> Michael change_date: 2021-09-23, manager: who -> Michael/Amelia change_date: 2021-05-12, manager: None -> who change_date: 2021-04-12 I want to output something like Michael: 2021.05.12 ~ today total: 316 days Amelia:2021.05.12 ~ 2021.09.23 (134), 2021.10.12 ~ 2022.02.25. (136) total: 270 days Sophia: 2022.02.25. ~ today total: 27 days queryset -> Michael, 316, Amelia, 270, Sophia, 27 -
django : rename in admin panel does not work
When i change the primary key in the admin panel and choose the save button a new recrod is created. But i want to rename the primary key. models.py: class Firma(models.Model): firma = models.CharField( primary_key=True, max_length=50, db_column='Firma', help_text='Firma', verbose_name = 'Firma', ) def __str__(self): return self.firma admin.py: class FirmaAdmin(admin.ModelAdmin): list_display = ( 'firma', ) ordering = ('firma',) I use Django 3.2. What am I doing wrong? -
why is my list cannot be convert into zip list? python
i have 2 list that i got from input in my html i want to ouput that 2 list together but when i use zip(lista, listb) no output shown {% for proc, ope in procslist %} <tr> <td style="width:10%;">{{proc.id}}</td> <td style="width:10%;">{{proc.name}}</td> <td style="width:10%;">{{proc.setcost}} / {{proc.proccost}}</td> <td style="width:10%;">{{proc.id}}</td> <td style="width:10%;">{{proc.id}}</td> <td style="width:10%;">{{proc.id}}</td> <td style="width:10%;">{{proc.settime}}</td> <td style="width:10%;"> <input type="hidden" name="opetimelist" value="{{proc.id}}" id=""> <input type="text" name="opetime-{{proc.id}}" id="" value="{{ope}}" style="width: 80%;"> </td> </tr> {% endfor %} and this is my views.py proc = '' choosenproc = request.POST.get('choosenproc') if choosenproc: proc = Proc.objects.get(Q(name__icontains=choosenproc) | Q(id__icontains=choosenproc)) flag = False if proc: if selectedproc != []: for product in selectedproc: if product.id == proc.id: flag = True break if flag == False: selectedproc.append(proc) opetimelist = request.POST.getlist('opetimelist') opetimevalue = [request.POST['opetime-{}'.format(o)] for o in opetimelist] procslist = zip(selectedproc, opetimevalue) the result it no ouput how to fix this? -
django rest framework saving data to multiple tables from a single view
I'm currently new to DRF I am looking to save data to two database tables via the viewset and I don't know how to go about it. I am using react for my frontend here is my models from django.db import models # Create your models here. class Customer(models.Model): id = models.AutoField(primary_key=True) name = models.CharField(max_length=255) phone = models.CharField(max_length=255) town = models.CharField(max_length=255) region = models.CharField(max_length=255) added_on = models.DateTimeField(auto_now_add=True) objects = models.Manager() class Order(models.Model): id = models.AutoField(primary_key=True) order_no = models.CharField(max_length=255) customer_name = models.CharField(max_length=255) phone = models.CharField(max_length=255) town = models.CharField(max_length=255) region = models.CharField(max_length=255) farmer_id = models.ForeignKey(Farmer, on_delete=models.CASCADE) price_per_kgs = models.CharField(max_length=255) kgs = models.CharField(max_length=255) packaging = models.CharField(max_length=255) transport = models.CharField(max_length=255) discount = models.CharField(max_length=255) amount = models.CharField(max_length=255) status = models.BooleanField(default=False) added_on = models.DateTimeField(auto_now_add=True) objects = models.Manager() and here is my serializer from rest_framework import serializers # Create your serializers here from barakasalessystemApp.models import Farmer, Customer, Bill, Payments, Orders class FarmerSerializer(serializers.ModelSerializer): class Meta: model = Farmer fields = "__all__" class CustomerSerializer(serializers.ModelSerializer): class Meta: model = Customer fields = "__all__" class OrdersSerializer(serializers.ModelSerializer): class Meta: model = Orders fields = "__all__" def to_representation(self, instance): response = super().to_representation(instance) response["farmer"] = FarmerSerializer(instance.farmer_id).data return response this is my views from functools import partial from django.shortcuts import render from rest_framework import viewsets, … -
how to password protect my site in django
Is is possible to password protect my whole site. I'm new to Django and i want to create a chatroom for a group of friends, but i want to have a password to get into the room. is there any tutorial out there in where i can put a password that anyone can use over my whole site? so far I have a website which can be used to input text but has no verification for passwords. all i've found are complicated tutorials for creating users and managing them. I'm looking for something simple. Thanks. -
How to view my data on the page without reload it and how to post my data on server?
I have a python script on my PC, that takes data from sensors and return it in the list like: [24 25, 32, 56] This data from different 4 sensors. Also i have a server with django site. I want to take data from sensors and display it on my html page without reloading the page. How can i do it? I listened about ajax, maybe you have helpful links to similar problem or lesson. my python-script for taking data from hardware: import serial import time wox = serial.Serial('COM3', 115200,stopbits=1) #Открыли порт while True: #if wox.inWaiting() two_sensors = wox.readline().decode("utf-8") two_sensors = two_sensors.replace("\n","") st_two_sensors = two_sensors.split(",") st_two_sensors[3] = float(st_two_sensors[3])/220000 print(st_two_sensors) temperature_0 = int(st_two_sensors[0]) temperature_1 = int(st_two_sensors[1]) voltage = st_two_sensors[2] Simple html: {% load static %} <html> <head> <meta http-equiv="Content-Type" content="text/html; Charset=UTF-8"> <!--<meta http-equiv="refresh" content="7"> --> <script type="text/javascript" src="{% static '/js/jquery-3.6.0.js' %}"></script> </head> <body> I want to have sensor data here with live updating. </body> </html> beside ajax i listened about web-sockets what would be easier? and where can i find examples Also i intrested how to transmit that data to the server, maybe some url requests? -
No retrived data in related table/model in django
i have this api that will retrieve the data of a farmer, now I retrieved the main profile but not the details in parcels. model.py from django.db import models class Farmer(models.Model): record_no = models.CharField(primary_key=True,max_length=19) control_no = models.CharField(max_length=50) fname = models.CharField(max_length=100) mname = models.CharField(max_length=100) lname = models.CharField(max_length=100) ename = models.CharField(max_length=100) sex = models.CharField(max_length=6) birthday = models.DateField(blank=True, null=True) arb = models.CharField(max_length=3) pwd = models.CharField(max_length=3) ben_4ps = models.CharField(max_length=3) ip = models.CharField(max_length=3) tribe_name = models.CharField(max_length=100) fca_mem = models.CharField(max_length=3) fca_name = models.CharField(max_length=200) house_no = models.CharField(max_length=100) street = models.CharField(max_length=100) region_code = models.CharField(max_length=2) region_shortname = models.CharField(max_length=50) region_longname = models.CharField(max_length=150) province_code = models.CharField(max_length=2) province_name = models.CharField(max_length=150) municipality_code = models.CharField(max_length=2) municipality_name = models.CharField(max_length=150) brgy_code = models.CharField(max_length=2) brgy_name = models.CharField(max_length=150) farm_size = models.DecimalField(max_digits=10,decimal_places=4) class Meta: managed = False db_table = 'farmers' class Parcels(models.Model): record_no = models.ForeignKey(Farmer,null=True, db_column='record_no',on_delete=models.CASCADE) parcel_no = models.IntegerField() parcel_farm_area = models.DecimalField(max_digits=10,decimal_places=4) type_of_ownership = models.CharField(max_length=100) presented_doc = models.CharField(max_length=100) reg_name = models.CharField(max_length=100) prov_name = models.CharField(max_length=100) mun_name = models.CharField(max_length=100) bgy_name = models.CharField(max_length=100) class Meta: managed = False db_table = 'parcels' serializers.py from rest_framework import serializers from .models import Farmers, Parcels class ParcelDetailSerializer(serializers.ModelSerializer): class Meta: model = Parcels fields = ['record_no','parcel_no','parcel_farm_area','type_of_ownership','presented_doc','reg_name','prov_name','mun_name','bgy_name'] class FarmerDetailSerializer(serializers.ModelSerializer): parcels = ParcelDetailSerializer(many=True, read_only=True) class Meta: model = Farmers fields = ['control_no','record_no','fname','mname','lname','ename','sex','birthday','arb','pwd','ben_4ps','ip','tribe_name','fca_mem','fca_name','house_no','street','region_code','region_shortname','region_longname','province_code','province_name','municipality_code','municipality_name','brgy_code','brgy_name','farm_size','parcels'] views.py from django.shortcuts import render from rest_framework.decorators … -
How to use Django AutoSlug in Custom Form
I am working on a project and using the django-autoslug package to auto generate slugs for me. The package does its job perfectly well and I like it. So far, I can edit slugs from the admin panel when I added editable=True which works well from the admin panel. Now I want a working system where users can easily edit there slug from an UpdateForm in the UpdateView. I tried the official docs but I think it is limited to the admin panel and no support for the regular custom forms. Is there any better solution that can solve this for me? A solution that can auto generate forms, and also allow my users update their slug uniquely. I'll be very grateful if I get a solution on this. Warm Regards. slug = AutoSlugField(populate_from='name', unique=True, editable=True) -
Unable to make websocket connection in django
I am trying to make a websocket connection I am using the django's channels API. For some reason the handshaking is not taking place. Maybe it has something to do with the url? This is my main routing.py file from channels.auth import AuthMiddlewareStack from channels.routing import ProtocolTypeRouter,URLRouter import chat.routing application = ProtocolTypeRouter({ 'websocket':AuthMiddlewareStack( URLRouter( chat.routing.websocket_urlpatterns ) ), }) This is my chat app routing.py from django.urls import re_path,path # from django.conf.urls import url from . import consumers websocket_urlpatterns = [ re_path(r'ws/chat/room/(?P<room_name>\w+)/(?P<username>\w+)/$',consumers.ChatRoomConsumer.as_asgi()), ] This is my chat app consumers.py file # import pytest from accounts.models import Account from .models import ChatRoom, Message from channels.generic.websocket import AsyncWebsocketConsumer import json from channels.db import database_sync_to_async import string import random # from asgiref.sync import sync_to_async class ChatRoomConsumer(AsyncWebsocketConsumer): async def connect(self): self.room_name = self.scope['url_route']['kwargs']['room_name'] self.room_group_name= 'chat_%s'%self.room_name await self.channel_layer.group_add( self.room_group_name, self.channel_name ) await self.accept() async def disconnect(self,close_code): await self.channel_layer.group_discard( self.room_group_name, self.channel_name ) async def receive(self, text_data): text_data_json = json.loads(text_data) message = text_data_json['message'] username = text_data_json['username'] room_name = text_data_json['room_name'] # print("[RECIEVED] "+room_name) print("[receiving....]"+message) await self.channel_layer.group_send( self.room_group_name, { 'type':'chatroom_message', 'message':message, 'username':username, 'room_name':room_name, } ) async def chatroom_message(self,event): message = event['message'] username = event['username'] room_name = event['room_name'] print("[SENDING....]"+message) room_obj = ChatRoom.objects.get(room_name=room_name) sender = Account.objects.get(username=username) await self.save_message(message=message,sender=sender,room_name=room_obj) await self.send(text_data=json.dumps({ 'message':message, 'username':username, … -
This is a django project . I am trying to fetch carousel image from database but it's ,only one image showing and slider not changing
00 I am trying to make a carousel slider. The picture comes from the database and is then rendered on the frontend slider. But the picture is rendering but it is creating a new slider and when I change to the next slide then it shows the same picture. What to do?? I am trying to make a carousel slider. The picture comes from the database and is then rendered on the frontend slider. But the picture is rendering but it is creating a new slider and when I change to the next slide then it shows the same picture. What to do?? my Url.py from django.urls import path from . import views urlpatterns = [ path('',views.home, name='home'), ] views.py from django.shortcuts import render from .models import Products, About, Slider, Team # Create your views here. def home(request): slider = Slider.objects.all() return render(request, 'index.html', {'slider':slider}) index.html <!-- slider --> <div id="carouselExampleCaptions" class="carousel slide" data-bs-ride="carousel"> <div class="carousel-indicators"> <button type="button" data-bs-target="#carouselExampleCaptions" data-bs-slide-to="0" class="active" aria-current="true" aria-label="Slide 1"></button> <button type="button" data-bs-target="#carouselExampleCaptions" data-bs-slide-to="1" aria-label="Slide 2"></button> </div> <div class="carousel-inner"> **{% for s in slider %} <div class="carousel-item active"> <img src="{{ s.image.url }}" class="d-block w-100" alt="..."> <div class="carousel-caption d-none d-md-block"> <h5 class="fw-bolder fs-2">{{ s.Title }}</h5> <p class="fw-bolder … -
Remove option with certain text from dropdown menu
In my Django app (using {% load crispy_forms_tags %}) I have a following dropdown menu: <div id="div_id_report_division" class="form-group"> <label for="id_report_division" class=" requiredField">Test<span class="asteriskField"></span</label> <div class=""> <select name="report_division" class="select form-control" required="" id="id_report_division"> <option value="" selected="">---------</option> <option value="1">A</option> <option value="2">B</option> <option value="3">C</option> <option value="4">D</option> <option value="5">E</option> </select> </div> </div> I wish to remove option number 5 on page load. My Javascript on post.html with everything is: <script type="text/javascript"> function on_load(){ /* option 1.: document.querySelector('id_report_division option[value=5]').remove(); option 2.: var x = document.getElementById('id_report_division'); x.remove(5); option 3.: document.querySelector('#id_report_division option[value=5]').remove(); const first = document.querySelector("[id='id_report_division']"); */ document.querySelector("[id='id_report_division' option[value=5]]").remove(); } on_load(); </script> How can I easly remove this option? It would be better if I could remove option where text is E, in case that value changes. But there will always be only one text 'E', no need to itterate. -
how to solve Direct assignment to the forward side of a many-to-many set is prohibited error?
In my code cart is a model class where products are ForeignKey and in OrderItem model class where cart is ManyToManyField. When I want to save the OrderItemForm the above error occurs. models.py class OrderItem(BaseModel): user = models.ForeignKey(User, on_delete=models.CASCADE) customer = models.ForeignKey(Customer, on_delete=models.CASCADE) cart = models.ManyToManyField(Cart, blank=True) name = models.CharField(max_length=200) district = models.ForeignKey(District, on_delete=models.CASCADE) city = models.CharField(max_length=200) postal_code = models.SmallIntegerField() area = models.TextField() phone = models.CharField(max_length=12) status = models.CharField(max_length=20, choices=STATUS_CHOICE, default="accepted",blank=True, null=True) email = models.EmailField() def __str__(self): return self.user.email Views.py def checkout(request): context={} subtotal =0 forms = OrderItemForm() context['forms'] = forms if request.user.is_authenticated: user = request.user cart = Cart.objects.filter(user=user).order_by('-id') for product in cart: subtotal += product.total_cost context['subtotal'] = subtotal customer = Customer.objects.get(user=user) if request.POST: form = OrderItemForm(request.POST) if form.is_valid(): name = form.cleaned_data['name'] district = form.cleaned_data['district'] city = form.cleaned_data['city'] postal_code = form.cleaned_data['postal_code'] area = form.cleaned_data['area'] phone = form.cleaned_data['phone'] email = form.cleaned_data['email'] for c in cart: instance = OrderItem(user=user, cart=cart, customer=customer, name=name, district=district, city=city, postal_code=postal_code, area=area, phone=phone, email=email).save() # instance.cart_for_help.add(cart) c.delete() else: messages.warning(request, form.error) return render(request, 'checkout.html', context) -
ModuleNotFoundError: No module named 'django' the commands pip install django doesn't working
The above exception was the direct cause of the following exception: Traceback (most recent call last): File "C:\Users\ACER\Dropbox\Мой ПК (LAPTOP-CEPJ3MP0)\Desktop\Platform\manage.py", line 21, in <module> main() File "C:\Users\ACER\Dropbox\Мой ПК (LAPTOP-CEPJ3MP0)\Desktop\Platform\manage.py", line 12, in main raise ImportError( ImportError: Couldn't import Django. Are you sure it's installed and available on your PYTHONPATH environment variable? Did you forget to activate a virtual environment? Python 3.9.9 pip 21.2.4 C:\Users\ACER\AppData\Local\Programs\Python\Python39\python39.zip C:\Users\ACER\AppData\Local\Programs\Python\Python39\DLLs C:\Users\ACER\AppData\Local\Programs\Python\Python39\lib C:\Users\ACER\AppData\Local\Programs\Python\Python39 C:\Users\ACER\AppData\Local\Programs\Python\Python39\lib\site-packages the commands pip install django and pip install django==0 do not working WARNING: Retrying (Retry(total=4, connect=None, read=None, redirect=None, status=None)) after connection broken by 'ConnectTimeoutError(<pip._vendor.urllib3.connection.HTTPSConnection object at 0x0000020861177880>, 'Connection to 23.88.61.104 timed out. (connect timeout=15)')': /simple/django/ WARNING: Retrying (Retry(total=3, connect=None, read=None, redirect=None, status=None)) after connection broken by 'ConnectTimeoutError(<pip._vendor.urllib3.connection.HTTPSConnection object at 0x0000020861177610>, 'Connection to 23.88.61.104 timed out. (connect timeout=15)')': /simple/django/ WARNING: Retrying (Retry(total=2, connect=None, read=None, redirect=None, status=None)) after connection broken by 'ConnectTimeoutError(<pip._vendor.urllib3.connection.HTTPSConnection object at 0x00000208611776D0>, 'Connection to 23.88.61.104 timed out. (connect timeout=15)')': /simple/django/ WARNING: Retrying (Retry(total=1, connect=None, read=None, redirect=None, status=None)) after connection broken by 'ConnectTimeoutError(<pip._vendor.urllib3.connection.HTTPSConnection object at 0x0000020861177190>, 'Connection to 23.88.61.104 timed out. (connect timeout=15)')': /simple/django/ WARNING: Retrying (Retry(total=0, connect=None, read=None, redirect=None, status=None)) after connection broken by 'ConnectTimeoutError(<pip._vendor.urllib3.connection.HTTPSConnection object at 0x0000020861186190>, 'Connection to 23.88.61.104 timed out. (connect timeout=15)')': /simple/django/ ERROR: Could not find a … -
add a column under a condition in django
This is my model class User_quiz_logs(models.Model): user_id = models.ForeignKey(User, on_delete=models.CASCADE, null=False) user_quiz_id = models.AutoField(primary_key=True) response = models.CharField('response ', max_length=300, null=False) points = models.IntegerField('points', null=True) state_quiz = models.BooleanField('state', default=False) tiene un atributo puntos que quiero sumar si corresponde a un mismo persona Example 1 A 1 true 141 2 A 1 true 141 3 A 1 true 141 4 B 5 true 165 5 C 1 true 165 The person with id 141 the total sum of his points would be 3 and id 165 would be 6 total points. -
How to show only the value as text without reflecting the series on the stacked bar chart (apexchart)
I'm creating a stacked bar chart using apexchart in django. There are 5 data series, and the number of ongoing series is significantly larger than the data of other series(data type=digit), so when viewed as a stacked bar graph, the data of series except ongoing does not look thin. So, I want to output only the data value as "ongoing: value" above each bar without reflecting the ongoing series on the chart. There are very few cases like mine. I've been looking for a workaround for days, but I can't get it to work. [dashboard.html] <script> var options3 = { series: [ { name: 'I', data: {{ I | safe }} }, { name: 'S', data: {{ S | safe }} }, { name: 'P', data: {{ P | safe }} }, { name: 'E', data: {{ E | safe }} }, { name: 'ongoing', data: {{ ongoing | safe }} }, ], chart: { type: 'bar', height: 550, stacked: true, }, plotOptions: { bar: { dataLabels: { position: 'center', }, } }, dataLabels: { style: { fontSize: '10px', colors: ["#304758"] } }, stroke: { width: 1, colors: ['#fff'] }, title: { text: 'I-S-P-E chart', offsetY: 0, align: 'center', }, … -
Modified Output Data in to_representation method in django drf
can I return a list in the to_representation method in Django Rest Framework I need to modify the output in the serializer here is a recent output { "id": 1, "display_sequence": 2 } I need to modify the recent output to [ { "id": 1 "display_sequence": 2 }, { "id" : 2 "display_sequence": 1 } ] so the second data I got from the query filter based on the container id and target_container_id instance = Container.objects.filter(id__in=[self.container_id, self.target_container_id]) if I return to serializer I got this error Got AttributeError when attempting to get a value for field `display_sequence` on serializer `ContainerSequenceSwapSerializer`. The serializer field might be named incorrectly and not match any attribute or key on the `list` instance. Original exception text was: 'list' object has no attribute 'display_sequence'. how to I can return yo expected output? here are my views Views class ContainerViewSet(viewsets.ModelViewSet): """Container ViewSet for CRUD operations.""" queryset = Container.objects.all() def get_serializer_class(self): return ContainerSerializerV1 @action(methods=["patch"], detail=True, url_path="swap-sequence") def swap_sequence(self, request, pk): # serializer = ContainerSequenceSwapSerializer(data=request.data) container = self.get_object() serializer = ContainerSequenceSwapSerializer(container, data=request.data, context={'container': container}) if serializer.is_valid(raise_exception=True): # display data here content = serializer.data return Response(data=content, status=status.HTTP_200_OK) Serializer class ContainerSequenceSwapSerializer(serializers.ModelSerializer): """Serializer for Container sequence swap detail action.""" display_sequence = serializers.IntegerField() … -
Django cannot set domain name
I want to set domain name from cloudflare to django. I set settings.py like this. ALLOWED_HOSTS = ["10.x.x.x","20.x.x.x","myweb.com"] which 10.x.x.x is private ip address and 20.x.x.x is public ip address. The public ip is in Firewall NAT. I run Django server by use command python manage.py runserver myweb.com:8000 It show error like this. Error: [Errno 11001] getaddrinfo failed If I run with public ip like this command. python manage.py runserver 20.x.x.x:8000 It show error like this. Error: That IP address can't be assigned to. If I run with private ip it have no error. python manage.py runserver 10.x.x.x:8000 I set domain in cloudflare myweb.com to public ip 20.x.x.x. when open http://myweb.com:8000 it not found my website. How to set domian for Django? -
Query working in development but not in production Django
I have a query which is something like that: log_entry = LogEntry.objects.filter(Q(date__range=[start_date, end_date]) & Q( student_id__id__icontains=student) & Q(instructor_id__id__icontains=instructor) & Q(aircraft_id__id__icontains=aircraft)) log_entry_dual = LogEntry.objects.filter(Q(date__range=[start_date, end_date]) & Q( student_id__id__icontains=student) & Q(instructor_id__id__icontains=instructor) & Q(aircraft_id__id__icontains=aircraft) & Q(solo_flight=False)) and the view part which is: start_date = request.GET.get('start_date') if not start_date: start_date = dt.now().date() end_date = request.GET.get('end_date') if not end_date: end_date = dt.now().date() student = request.GET.get('student') if not student: student = '' instructor = request.GET.get('instructor') if not instructor: instructor = '' aircraft = request.GET.get('aircraft') if not aircraft: aircraft = '' Now, the weird part is that this query and view works perfectly in development environment (it filters the results based on my input, so an empty field shows all the data based on the other filters) but in production (I am on heroku) doesn't work. I mean, it works ONLY if I choose ALL the fields of the query and I don't leave any blank input. I have postgresql in both development and production. Any clue about what I am doing wrong? -
Possible to filter a queryset by its ForeignKey related_name objects?
I have a simple model: class Object(models.Model): name = CharField() root = ForeignKey("self", null=True, blank=True, on_delete=models.SET_NULL) I create a few objects: parent1 = Object.create(name="parent1") o1 = Object.create(name="1", root=parent1") parent1.object_set.all() # Returns queryset with o1 Is it possible to filter a queryset by its ForeignKey's related_name objects (i.e. object_set)? Something like: Object.objects.filter(object_set__name="1") # To return parent1 I get the following error: Cannot resolve keyword 'object_set' into field. I understand I could do Object.object.get(name="1").root but that results in additional queries which could really add up in my specific use case. -
Mac OS python django commands not working
I am getting blank output for all commands like runserver, migrate, makemigrations. Unable to find anything on google. -
how can i use uwsgi listen 80 port directly while deploying the django?
I am learning django, and now i have some trouble here. django cant receive the http packet but uwsgi packet from uwsgi server when i write the configure file like this, it works. [uwsgi] http = xxx.xxx.xxx.xxx:9999 chdir = /home/ZoroGH/code/django/mysite1 wsgi-file = mysite1/wsgi.py process=4 threads=2 pidfile=uwsgi.pid daemonize=uwsgi.log master=true i can visit the IP:9999. however, i cant change the port to 80, the log file says Permission Denied. then i enter sudo -i . in this mode ,the bash can't konw the uwsgi command.so i am here looking for help. how can i use uwsgi listen 80 port directly? i have made some search that some solutions are to use the nginx to pass the http to uwsgi service, but now i just want to only use the uwsgi to test my site. can it work? i looked the document of uwsgi, it says never to use root mode to execute the uwsgi service, but to use the uid & gid ? sadly, i konw nothing about the uid & gid. help me please -
Can I separate the model file into multiple files in Django? [duplicate]
I am new to Django, as I understand that the model file contains all model classes that are related to the component. But over time when the project becomes more complex, the model file is too huge and not readable, like this: class A(models.Model): title = models.CharField(max_length=255) class F(models.Model): title = models.CharField(max_length=255) class B(models.Model): title = models.CharField(max_length=255) class C(models.Model): title = models.CharField(max_length=255) class D(models.Model): title = models.CharField(max_length=255) class E(models.Model): title = models.CharField(max_length=255) ... Can I divide these classes into multiple files? like: File1 class A(models.Model): title = models.CharField(max_length=255) class F(models.Model): title = models.CharField(max_length=255) class B(models.Model): title = models.CharField(max_length=255) File2 class C(models.Model): title = models.CharField(max_length=255) class D(models.Model): title = models.CharField(max_length=255) class E(models.Model): title = models.CharField(max_length=255) Same question for views and serializers files. -
How to run a single unit test in Django
I run my tests with command "python3 manage.py test" it works fine, but it run all tests. When I try to run test by pushing a button "Run Test"(green triangle) there is an error: Error ImportError: Failed to import test module: app_shop Traceback (most recent call last): File "/usr/lib/python3.8/unittest/loader.py", line 154, in loadTestsFromName module = __import__(module_name) ModuleNotFoundError: No module named 'djcaching.app_shop' How can I solve this problem? My structure: djcaching app_shop tests app_users tests djcaching settings -
Template won't render each field in MultiValueField
In attempting to construct a subclass of MultiValueField called TagField, I'm not sure how to go about rendering each widget of the form field. There are suppose to be 4 x TextInput elements. I tried {{ field }} in the template initially, but it only renders the first TextInput widget. When that didn't render all four inputs, I tried {% for input in field %}, and that still only renders the first input element. What else must be done to get all four input elmenets rendered in the template? class TagField(MultiValueField): def __init__(self, *args, **kwargs): super().__init__(*args, **kwargs) self.require_all_fields = False self.help_text = kwargs["help_text"] for i in range(4): field = CharField(**{ "min_length": 1, "max_length": 25, "widget": TextInput( attrs={"class": "question_input_field"} ), "validators":[ RegexValidator("[<>`':;,.\"]", inverse_match=True) ] }) if i == 0: field.attrs.update({ 'required': True, "error_messages": { 'incomplete': "Provide at least 1 tag for your question" } }) else: field.required = False self.fields.append(field) def compress(self, data_list): data_list = set([tag.lower().strip() for tag in data_list]) return data_list