Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Extract related fields or Keys instead of value using request.POST.get method in Django
I have 2 tables in Django db.sqlite3 database both having state_id as a common field on the basis of which I had to map the districts for respective states in dropdown using Jquery state_database id state_id state_name 3 3 Uttarakhand 2 2 Punjab 1 1 Haryana district_database id state_id district_id district_name 1 1 1 Sonipat 2 1 2 Rohtak 3 1 3 Amabala 4 1 4 Sirsa 5 2 5 Amritsar 6 2 6 Ludhiana 7 3 7 Pantnagar 8 3 8 Almora For Doing so, I had to assign the common field / state_id as value in HTML like value= '{{state.state_id}}' <select class="form-control" id="state_from_dropdown" name="state_from_dropdown" aria-label="..."> <option selected disabled="true"> --- Select State --- </option> {% for state in StatesInDropdown %} <option value= '{{state.state_id}}'> {{state.state_name}} </option> {% endfor %} </select> <select class="form-control" id="district_from_dropdown" name="district_from_dropdown" aria-label="..."> <option selected disabled="true"> --- Select District --- </option> {% for disitrict in DistrictsInDropdown %} <option value= '{{disitrict.state_id}}'> {{disitrict.district_name}} </option> {% endfor %} </select> Views.py def inputconfiguration(request): if request.method == "POST": StateName=request.POST.get('state_from_dropdown') DistrictName=request.POST.get('district_from_dropdown','') print(StateName, DistrictName) return render(request, 'configure_inputs.html') Instead of Getting Actual Fields/Names which appears in the dropdown, I get the values of ID's, but I want the names of states and districts instead of their … -
How to Save form Data to Database in Django?
I am trying to save form data from Django template to Django Model. Its not throwing any error but its not saving the data as well Could you please let me know what could be the problem and how should I solve? Here is my Django form template: <form method="POST" class="review-form" autocomplete="on"> {% csrf_token %} <div class="rating-form"> <label for="rating">Your Overall Rating Of This Product :</label> <span class="rating-stars"> <a class="star-1" href="#">1</a> <a class="star-2" href="#">2</a> <a class="star-3" href="#">3</a> </span> <select name="rating" id="rating" required="" style="display: none;"> <option value="">Rate…</option> <option value="3">Average</option> <option value="2">Not that bad</option> <option value="1">Very poor</option> </select> </div> <textarea cols="30" rows="6" placeholder="What did you like or dislike? What did you use this product for?" class="form-control" id="review" name="description"></textarea> <div class="row gutter-md"> <div class="col-md-12"> <input type="text" class="form-control" placeholder="Your Name - This is how you'll appear to other customers*" id="author" name ="name"> </div> </div> <button type="submit" class="btn btn-dark">Submit Review</button> </form> My Forms.py class ReviewForm(forms.ModelForm): class Meta: model = Reviews fields = ('rating', 'description', 'display_name') My Views: def reviews(request, slug): if request.method == "POST": if request.user.is_authenticated: form = ReviewForm(request.POST) if form.is_valid(): review = form.save(commit=False) review.product = Products.objects.get(slug=slug) review.user = request.user review.display_name = request.name review.description = request.description review.rating = request.rating print(review) review.save() messages.success(request, "Review saved, Thank you … -
unresolved reference 'Recruiter'
I'm using PyCharm I don't know what type of error is this here is the model.py class Recruiter(models.Model): user = models.ForeignKey(User, on_delete=models.CASCADE) mobile = models.CharField(max_length=15, null=True) image = models.FileField(null=True) gender = models.CharField(max_length=10, null=True) company = models.CharField(max_length=100, null=True) type = models.CharField(max_length=15, null=True) status = models.CharField(max_length=20, null=True) def _str_(self): return self.user.username -
I want to POST data and add it to JSON
jsonData = { "2022":{ "03":{ "5":"로제파스타" ,"17":"테스트" } ,"08":{ "7":"칠석" ,"15":"광복절" ,"23":"처서" } ,"09":{ "13":"추석" ,"23":"추분" } } } } function drawSche(){ setData(); var dateMatch = null; for(var i=firstDay.getDay();i<firstDay.getDay()+lastDay.getDate();i++){ var txt = ""; txt =jsonData[year]; if(txt){ txt = jsonData[year][month]; if(txt){ txt = jsonData[year][month][i]; dateMatch = firstDay.getDay() + i -1; $tdSche.eq(dateMatch).text(txt); } } } } I'm a Korean developer. Please understand that I'm not good at English. Javascript is also inexperienced and is preparing for a small project.😅 It's my first time writing stackoverflow, so I don't know if I'm writing well.🤔 Anyway, I want to add it to jsondata using the previous input tag. I'm using Django, too. If it helps, I want to use Django, too. It's a question that I desperately want to solve. Please help me😭 -
django: how to save ModelForm data with foregin key?
I'm face an issue while saving data to database! let me explain..... I'm trying to make a app like blog... & there is a comment section. There have three fields for submit comment.... name, email & message. but when someone submit an comment it should save into database for a specific blog post, so I've defined a foreign key on comment model. but its not work! whenever I submit it show NOT NULL constraint failed error! even if I change this table null=True then it doesn't show any error but it don't save any foregin key! please help me! models.py from django.db import models from ckeditor.fields import RichTextField class Event(models.Model): title = models.CharField(max_length=255) description = RichTextField() thumb = models.ImageField(upload_to="events") amount = models.IntegerField() location = models.CharField(max_length=255) calender = models.DateField() def __str__(self): return self.title class Comment(models.Model): event = models.ForeignKey(Event, on_delete=models.CASCADE) username = models.CharField(max_length=255, null=False, blank=False) email = models.EmailField(max_length=255, null=False, blank=False) message = models.TextField(null=False, blank=False) date = models.DateField(auto_now_add=True) def __str__(self): return self.username forms.py from django.forms import ModelForm, TextInput, EmailInput, Textarea from .models import Comment class CommentForm(ModelForm): class Meta: model = Comment fields = ["username", "email", "message"] widgets = { "username": TextInput(attrs={"placeholder":"Name *"}), "email": EmailInput(attrs={"placeholder":"Email *"}), "message": Textarea(attrs={"placeholder":"Message"}) } views.py from django.shortcuts import redirect … -
Django creates a JSON list from the model and related models
I have these two models: class LetterGroups(models.Model): id = models.AutoField(primary_key=True) name = models.CharField(max_length=256) personnel_id = models.ForeignKey(Personnel, on_delete=models.CASCADE,db_column='personnel_id') class Meta: db_table = 'letter_groups' ordering = ['id'] permissions = (("letters", "letters"),) class LetterGroupMembers(models.Model): id = models.AutoField(primary_key=True) group_id = models.ForeignKey(LetterGroups, on_delete=models.CASCADE,db_column='group_id') personnel_id = models.ForeignKey(Personnel, on_delete=models.CASCADE,db_column='personnel_id') class Meta: db_table = 'letter_group_members' ordering = ['id'] permissions = (("letters", "letters"),) and I try to create JSON like this (model and all related fields in the child model): [ { "id": 1, "name": "group 1", "lettergroupmembers": [ { "id": 1, "name": "member 1" }, { "id": 2, "name": "member 2" } ] }, { "id": 2, "name": "group 2", "lettergroupmembers": [ { "id": 3, "name": "member 3" }, { "id": 4, "name": "member 4" } ] } ] I already use something like this, but I can't create the correct JSON. groups = json.dumps( obj=list(LetterGroups.objects.all().values('id', 'name', 'lettergroupmembers__id', 'lettergroupmembers__name')), cls=DjangoJSONEncoder, ensure_ascii=False ) How I can create JSON with all related fields in the child model? -
How to get multiple values on same username on templates of Django?
Why i am not getting any values on bills, i am trying the upload the number of bills which has been ordered the users but i am getting empty values, can anyone help me def orderList(request): if request.method == "POST": status = request.POST.get("order") tableNo = request.POST.get("tableNO") order = Order.objects.get(user = request.user) order.ordered = status order.table_num=tableNo order.save() order = Order.objects.filter(user = request.user) print(order) context = { 'order' : order, } return render(request, 'user_accounts/order_item.html',context) ``` [enter image description here][1] [enter image description here][2] [enter image description here][3] [enter image description here][4] [1]: https://i.stack.imgur.com/UkEO4.png [2]: https://i.stack.imgur.com/t8SjM.png [3]: https://i.stack.imgur.com/2Qfeq.png [4]: https://i.stack.imgur.com/jnWbV.png -
Can set LineString in Geo Django
I want to draw line string on a leaflet map. I set line string data on the model but it draws out of the map. Can't draw a map on exact coordinates. View: Import JSON from a JSON file class ImportGisView(LoginRequiredMixin, View): template_name = "maps/import_gis.html" form_class = GISImportForm def post(self, request, *args, **kwargs): project = get_object_or_404(Project, slug=kwargs["slug"]) form = self.form_class(request.POST, request.FILES) if form.is_valid(): file = form.cleaned_data['file'] gis_file = file.read() decoded_gis_file = gis_file.decode('utf8') gis_data = ast.literal_eval(decoded_gis_file) for features in gis_data['features']: geometry = features['geometry'] type = geometry['type'] if type == 'LineString': line = GEOSGeometry(json.dumps(features['geometry'])) line.transform(4326) projectmap = ProjectMap( project=project, line=line, ) projectmap.save() context = { "project": project, "form": form, } return render(request, self.template_name, context) Model: class ProjectMap(models.Model): project = models.ForeignKey( Project, on_delete=models.SET_NULL, null=True ) line = models.LineStringField(null=True, blank=True) Admin: from django.contrib import admin from leaflet.admin import LeafletGeoAdmin from taiga.maps import models @admin.register(models.ProjectMap) class ProjectMapAdmin(LeafletGeoAdmin): list_display = ('project','line') Line Data JSON: { "type":"FeatureCollection", "features":[ { "type":"Feature", "geometry":{ "type":"LineString", "coordinates":[ [ 92.15286395100009, 21.15305210400004 ], [ 92.15272080000005, 21.153023500000074 ], [ 92.15221290000005, 21.15301990000006 ] ] }, "properties":{ "NAME":"test 1" } }, { "type":"Feature", "geometry":{ "type":"LineString", "coordinates":[ [ 92.15125660000007, 21.15309780000007 ], [ 92.15169850000007, 21.152142600000047 ], [ 92.15222090000003, 21.15283560000006 ], ] }, "properties":{ "NAME":"Test 2" } } ] … -
Django - Calling function in ListView or model to change model bolean status
I want to call a function - from a model or from a Listview that will change Order.isDone status - TRUE or FALSE after clicking the button in template. Model.py: class Order(models.Model): isDone = models.BooleanField(default=False, verbose_name='Zrealizowane') views.py: class OrderListView (ListView): model = Order template_name = 'orders/orders_list.html' ordering = ['-orderDate'] urls.py: urlpatterns = [ path('', views.home, name='page-home'), path('orders_list/', OrderListView.as_view(), name='page-orders-list'), path('completed_orders_list/', OrderCompletedListView.as_view(), name='page-completed-orders-list'), path('orders/order_create/', OrderCreateView.as_view(), name='page-order-create'), path('orders/<int:pk>/delete/', OrderDeleteView.as_view(), name='page-order-delete'), ] template: <tbody> {% for order in object_list %} {% if order.isDone == False %} <tr> <td> <button type="button" class="btn btn-secondary" data-toggle="modal" data-target="#exampleModalCenter">Szczegóły</button> <form action="{% url 'page-orders-list' order.id %}" method="post"> {% csrf_token %} <button class="btn btn-info btn-sm">Finish order</button> <form> <a class="btn btn-danger adminButton" href="{% url 'page-order-delete' order.id %}">Usuń</a> </td> </tr> {% endif %} {% endfor %} </tbody> </table> </div> {% endblock %} What is the easiest way to do this ? -
How to pass argument in Django Context Processor From Template
I want to pass an argument in context_processors.py from the template. if anybody know please tell me. this is my context_processors.py def groupWiseCustomer(request,id): return {'groupWiseCustomer': CSSIList.objects.filter(CSSIGroup=id)} -
Original exception text was: 'QuerySet' object has no attribute 'name'
Got AttributeError when attempting to get a value for field name on serializer StudentSerializer. The serializer field might be named incorrectly and not match any attribute or key on the QuerySet instance. Original exception text was: 'QuerySet' object has no attribute 'name'. my models.py: class Student(models.Model): name = models.CharField(max_length=45, verbose_name="ФИО") .. class Group(models.Model): name = models.SmallIntegerField(verbose_name="Номер группы") .. class StudentInGroup(models.Model): input_Students = models.DateField(verbose_name="Студент вступил в группу") output_Students = models.DateField( verbose_name="Студент покинул группу", blank=True, null=True) students = models.ManyToManyField( Student, verbose_name="Студент", related_name="Group") groups = models.ManyToManyField( Group, verbose_name="Группа", related_name="StudentInGroup") .. class Subject(models.Model): name = models.CharField(max_length=50, verbose_name="Название предмета") groups = models.ForeignKey(Group, on_delete=models.PROTECT) .. class Lesson(models.Model): date = models.CharField(max_length=15, verbose_name="Дата занятия") subjects = models.ForeignKey( Subject, verbose_name="Проведенные занятия", blank=True, on_delete=models.PROTECT) groups = models.ForeignKey( Group, verbose_name="Группа на занятии", blank=True, on_delete=models.PROTECT) .. class Progress(models.Model): students = models.ForeignKey( Student, on_delete=models.PROTECT, verbose_name="Студент", blank=True) lessons = models.ForeignKey( Lesson, on_delete=models.PROTECT, verbose_name="Занятия", blank=True) attendance = models.CharField( max_length=3, default='Да', verbose_name='Присутствие') grade = models.PositiveSmallIntegerField( verbose_name='Оценка за занятие', default=0) my views.py: @api_view(['GET', 'POST']) def subject_detail(request, pk): if request.method == 'GET': subjects = Subject.objects.get(pk=pk) #view_subjects = Subject.objects.filter(pk=pk) lessons = subjects.lesson_set.order_by('date') view_progreses = [] for lesson in lessons: progress = lesson.progress_set.all() view_progreses.append(progress) relationships = subjects.groups.StudentInGroup.all() view_students = [] for relationship in relationships: student = relationship.students.all() view_students.append(student) subjects_serializer = … -
How to implement direct checkout button in Django website (No need cart features)
I have created an E-commerce website on Django and i just want to set the buy now button on my website. I don't need a cart feature on my entire website. So please guide me on how to do that. Make sure I don't want to use the cart function or cart_id in my project. -
images are not saved in media directory in Django project
I'm trying to upload a picture (with Postman at the moment) and save it in the "media" directory but although the server returns 200 status code, nothing's saved in the project. urls.py: urlpatterns = [ path('users/sign-up', views.RegisterAPI.as_view()), path('users/login', views.LoginAPI.as_view()), path('users/<int:id>', views.UserProfile.as_view()), path('users/<int:id>/bill', views.UploadPicture.as_view()), ] + static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT) settings.py: STATIC_URL = '/static/' MEDIA_URL = '/media/' MEDIA_ROOT = os.path.join(BASE_DIR, 'media') models.py: class UserBill(models.Model): bill_picture = models.ImageField(default='bill_pic', null=True, blank=True) sender = models.ForeignKey(User, on_delete=models.CASCADE, null=True, related_name='user') created_at = models.DateTimeField(auto_now=True, auto_now_add=False) status = models.IntegerField(null=True) views.py: class UploadPicture(generics.GenericAPIView): permission_classes = [IsAuthenticated, IsAccountOwner] def post(self, request, *args, **kwargs): new_data = request.data new_data['user'] = request.user.id new_data['status'] = PaymentStat.PENDING.value serializer = UserBillSerializer(data=request.data) serializer.is_valid(raise_exception=True) bill = serializer.save() return Response({ "bill": UserBillSerializer(bill, context=self.get_serializer_context()).data, }, status=status.HTTP_200_OK) serializers.py class UserBillSerializer(serializers.ModelSerializer): class Meta: model = UserBill fields = '__all__' def create(self, validated_data): user = User.objects.all().get(id=self.initial_data.get('user')) bill = UserBill.objects.create(**validated_data, sender=user) return bill def update(self, instance, validated_data): obj = super().update(instance, validated_data) obj.is_regular = True obj.save() return obj -
How to tell passenger_wsgi.py to look for Django project inside another folder?
I'm trying to host a django app on cpanel but i cant find a way to tell passenger_wsgi.py to look for the django project(main file) inside another folder My site structure is: /home/project/ tmp/ public/ passenger_wsgi.py abdi-group/ passenger_wsgi.py: from abdiGroup.wsgi import application this works fine if i move everything inside abdi-group/ to /home/project/ I tried this: passenger_wsgi.py: from abdi-group.abdiGroup.wsgi import application but it can't find abdiGroup(django project name) inside abdi-group/ am i missing something? -
What model/approach to use to relate space and objects in django
I'm trying to play a little with django so I've started to create a "solution" to an old problem I have. My background at OO programming and models relation is not that much so I ask for ideas/paths/solutions on how to achieve my goals. My problem: I need to define spatial objects and relate them ex: Building 1, inside we have floor 1 and 2, inside floor 2 we have room A and B At each type of "location" I will place "things" ex: place 1 camera at building 1; place 1 camera at floor 2; place 1 camera at room B So I can archive the results bellow: Building 1: 3 cameras floor 2: 2 cameras room B: 1 camera I was planning to archieve this using the old method of a table for each kind of object (building, floor, room) but I'm a little stuck on how to deal with diferent stuff the same way (actions) specialy because after dealing with this I have to put "people" at the equation, ie, I can put person J at room 2 and put a camera on him. I thank you all in advance on all the thoughts (even if it … -
Set CharField to RTL in Django Admin site
When dealing with RTL content, it's very easy to use CKEditor, replace TextField with RichTextField in the model definition, and then set the editor to RTL but what about a CharField (the title of a blog post for instance)? Technically it is possible to set that to RichTextEditor too, but it's not convenient. So is there any way to change the direction of a text-box to RTL in Django admin site? -
Changes in views.py doesnt appear in my browser unless I stop the server
When I make any changes in views.py it doesnt appear in my browser unless I restart the server. Even CTRL + F5 and SHIFT+CTRL+R doesnt work . Does this happen for a reason? -
Curl POST file upload for django FileField
I have this model which has models.FileField and I have confirmed file upload works on Django rest framework web UI (viewsets.ModelViewSet) class MyFile(models.Model): name = models.CharField(verbose_name='NAME', max_length=30) file = models.FileField(upload_to='file/%Y/%m/%d') created_at = models.DateTimeField( auto_now_add=True) class MyFileSerializer(serializers.Serializer): name = serializers.CharField() file = serializers.FileField(required=False) def create(self, validated_data): return MyFile.objects.create(**validated_data) class MyFileViewSet(viewsets.ModelViewSet): queryset = MyFile.objects.all() serializer_class = MyFileSerializer def create(self, request, *args, **kwargs): serializer = self.get_serializer(data=request.data) serializer.is_valid(raise_exception=True) self.perform_create(serializer) headers = self.get_success_headers(serializer.data) return Response(serializer.data, status=status.HTTP_201_CREATED, headers=headers) then I try to upload the file from curl. curl -X POST -F upfile=temp/@image.jpg -F 'name=test' it returns like this but file is not uploaded. {"name":"test","file":null} Where am I wrong? -
Query on response value
How to write a conditional query on multiple fields? Explain: I have an index let say "case" and the fields are "title", "secondTitle(contain nested obj)", "source(contain nested obj)". Now I want to search on title and want number of document inside of secondTitle, which also contains in source field of another document. PUT /case_indx_tmp_tmp { "mappings": { "properties": { "title":{ "type": "text", "fields": { "title":{ "type":"keyword" } } }, "secondTitle":{ "type": "nested", "properties": { "second_title":{ "type":"text", "fields": { "secondtitle":{ "type":"keyword" } } } } }, "source":{ "type": "nested", "properties": { "source_title":{ "type":"text", "fields": { "sourcetitle":{ "type":"keyword" } } } } } } } } PUT /case_indx_tmp_tmp/_doc/1 { "title" : "Case 1", "secondTitle" : [ { "case_title" : "Case 2" } ], "source":[ { "source_title":"Case 3" }, { "source_title":"Case 4" } ] } PUT /case_indx_tmp_tmp/_doc/2 { "title" : "Case 2", "secondTitle" : [ { "case_title" : "Case 3" }, { "case_title" : "Case 4" }, { "case_title" : "Case 1" } ], "source":[ { "source_title":"Case 1" } ] } PUT /case_indx_tmp_tmp/_doc/3 { "title" : "Case 3", "secondTitle" : [ { "case_title" : "Case 5" }, { "case_title" : "Case 4" }, { "case_title" : "Case 1" } ], "source":[ { "source_title":"Case … -
How to hide the django AuthenticationForm built-in error_message?
I'm new to django and trying to hide the error message that has bullet on it (see screenshot below), the built-in error_message attribute when using the AuthenticationForm class on login, because I have used the form.errors in the templates and wanted to keep the error message on the top. I tried to use css to hide, but when I load the login page, it wont work. Is there a way to hide or perhaps disable it? I can only see the options to customize error_message in the docs though. Here is my code. login.html {% extends 'blog/base.html' %} {% load crispy_forms_tags %} {% block content %} <!-- Custom Error Message --> {% if form.errors %} {% for _, error in form.errors.items %} <div class="alert alert-danger text-center"> {{ error|striptags }} </div> {% endfor %} {% endif %} <div class="content-section"> <form method="POST"> {% csrf_token %} <fieldset class="form-group"> <legend class="border-bottom mb-4">Log in</legend> {{ form | crispy }} </fieldset> <div class="form-group"> <button class="btn btn-outline-info" type="submit">Login</button> <small class="text-muted ml-2"> <a href="{% url 'password_reset' %}">Forgot Password?</a> </small> </div> </form> <div class="border-top pt-3"> <small class="text-muted"> Need An Account? <a href="{% url 'register' %}" class="ml-2">Sign Up</a> </small> </div> </div> {% endblock content %} forms.py class LogInAuthForm(AuthenticationForm): username = … -
How to post a foreign key using as an actual field name and not pk value
Im still new to django and im trying to post the rfid number and bus reg number and i get the following error: Error: {"status":"error","data":{"rfid":["Incorrect type. Expected pk value, received str."],"bus":["Incorrect type. Expected pk value, received str."]}} I would like to post the actual rfid number and bus reg number instead of the pk value. Is there a way of achieving this. Transaction model: class Transaction(models.Model): bus = models.ForeignKey(Bus, on_delete = models.CASCADE) rfid = models.ForeignKey(Rfid, on_delete = models.CASCADE) date = models.DateTimeField(default=timezone.now) updated = models.DateTimeField(auto_now = True) created = models.DateTimeField(auto_now_add = True) Serializer: class TransactionSerializer(serializers.ModelSerializer): class Meta: model = Transaction fields = ('rfid', 'bus') views.py: class TransactionViews(APIView): def post(self, request): serializer = TransactionSerializer(data=request.data) if serializer.is_valid(): serializer.save() return Response({"status": "success", "data": serializer.data}, status=status.HTTP_200_OK) else: return Response({"status": "error", "data": serializer.errors}, status=status.HTTP_400_BAD_REQUEST) rfid model: class Rfid(models.Model): rfid_num = models.CharField(max_length = 50, unique = True) lock = models.BooleanField(choices = BOOL_CHOICES, default = False, verbose_name = 'Lock card', blank=True) is_active = models.BooleanField(default = True) user = models.OneToOneField(User, on_delete = models.CASCADE) balance = models.PositiveIntegerField(default=0) created_at = models.DateTimeField(auto_now_add=True) updated_at = models.DateTimeField(auto_now=True) bus model: class Bus(models.Model): reg_num = models.CharField(max_length = 20, unique = True) destination = models.ForeignKey(Destination, on_delete = models.CASCADE) created_at = models.DateTimeField(auto_now_add=True) updated_at = models.DateTimeField(auto_now=True) company = models.ForeignKey(Company, … -
how to search a string with space in django search method?
when I search the first_name and last_name field together it won't display the result eg: serch_text = "harry potter " it does not include the space? views.py def get(self, request, *args, **kwargs): if request.is_ajax(): search_text = request.GET.get('search') if search_text is not None and search_text != u"": search_text = request.GET.get('search') print(search_text) wallets = Wallet.objects.filter(Q(user__customer__first_name__icontains=search_text) | Q(user__customer__last_name__icontains=search_text) | Q(user__customer__email__icontains=search_text) | Q(user__customer__phone__icontains=search_text)) else: wallets = Wallet.objects.all() html = render_to_string('customer/wallet-filter.html', {'wallets': wallets}, request) return JsonResponse({'html': html}) wallets = Wallet.objects.all().order_by('-id') return render(request, 'customer/wallets.html', {'wallets': wallets}) -
Python - order python list by datetime object
I have a list of datetime objects that's being appended into an array from my database with an additional library called Django Recurrence. I append it as follows inside a for loop: events = Events.objects.filter(...some conditions) timeslots = [] for event in events: for occurence in event.recurrences.between(context['today'], context['end']): occurence_date = datetime.combine(occurence.date(), time(0, 0)) timeslots.append({ 'start_date': occurence_date + timedelta(hours=event.start_time.hour, minutes=event.start_time.minute), 'end_date': occurence_date + timedelta(hours=event.end_time.hour, minutes=event.end_time.minute), }) It would then output it as [{'start_date': datetime.datetime(2022, 3, 7, 14, 0), 'end_date': datetime.datetime(2022, 3, 7, 15, 0)}, {'start_date': datetime.datetime(2022, 3, 8, 14, 0), ... }] which is great. A side effect from the events loop, is that it would add a the other events, after all the occurrences, eg 1 march, 5 march, 10 march, 2 march, 4 march, etc etc etc. I'd like to order them by the starting date, so I can render them out in the correct order in my template. Thanks -
How to edit a Djano app in production mode in a remote linux server
I have to make changes to a Django application already in production on a linux. Can anyone guide me as to how I can make changes to this application through ssh? I was able to ssh and access the code of the application but I don't know how to commit a change to the application as I don't have access to the runserver terminal like the one I have access to when developing on windows. Also would be helpful if someone could explain how to access the particular python env it's running on. Help on this would be appreciated. -
Using for django loop inside of a JavaScript variable
I want to loop through a django query in JavaScript, example: musics = Music.query.all(). I did something like this: const songs = [ {% for music in musics %} { id: "{{music.id }}", songName: "{{ music.title }}", poster: "{{ music.cover_image.url }}", } {% endfor %} ] Array.from(document.getElementsByClassName("songItem")).forEach((element, I) =>{ element.getElementsByTagName('img').src = songs[I].poster; }) I get Uncaught TypeError: Cannot read properties of undefined (reading 'poster'), but if I use console log console.log(element.getElementsByTagName('img').src = songs[I].poster); ``` it works in the console.