Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Cannot assign "['9', '10', '11']": "Element.value_code" must be a "Value" instance
I am a student who is learning Janggo. I am currently implementing a page where the selected option information, price, and quantity appear when I select the option. However, the error keeps appearing. I don't know if modelchoicefield is a problem or where I missed it, or if the format that I get from the getlist in the view conflicts with the form, so I can't get the value. I'm sure that in script, var checkValue = $("#optionSelect").Val(); /Get this value " <input name=\"value_code2\" id=\"value_code2\">" + I left it in the input box to save the selected option value, but I'm frustrated why they keep saying it's not value instance. How on earth can I solve the problem I've been through? ERROR : ValueError at /join/join_create/2/ Request Method: POST Request URL: http://127.0.0.1:8000/join/join_create/2/ Exception Type: ValueError Exception Value: Cannot assign "['9', '10', '11']": "Element.value_code" must be a "Value" instance. Models.py class Option(models.Model): option_code = models.AutoField(primary_key=True) name = models.CharField(max_length=32) product_code = models.ForeignKey(Product, on_delete=models.CASCADE, db_column='product_code') def __str__(self): return self.name class Meta: ordering = ['option_code'] class Value(models.Model): value_code = models.AutoField(primary_key=True) option_code = models.ForeignKey(Option, on_delete=models.CASCADE, db_column='option_code') product_code = models.ForeignKey(Product, on_delete=models.CASCADE, db_column='product_code') name = models.CharField(max_length=32) extra_cost = models.IntegerField() def __str__(self): return self.name class Meta: ordering = … -
Error: Invalid LatLng object: (undefined, -0.09) (When trying to get data from django rest api)
import React, { useRef, useEffect, useState } from 'react' import { gsap, Power3 } from 'gsap' import { MapContainer, TileLayer, Marker, Popup } from 'react-leaflet' import 'mapbox-gl/dist/mapbox-gl.css' const ResturentMapOpenDates = (props) => { //Close Map model const tl = gsap.globalTimeline var store_longitude = props.store_longitude var store_latitude = props.store_latitude var lon_lan = [store_longitude, store_latitude] const closemapmodel = () => { var full_map_box = document.querySelector('.map_box_open_full'); var map_box = document.querySelector('.map_open_date'); tl.to(full_map_box, .3, {visibility: 'hidden', opacity: 0}) .to(map_box, .2, {visibility: 'hidden', opacity: 0}) } return ( <> <div className="map_box_open_full" onClick={closemapmodel}></div> <div className="map_open_date"> <div id="res_location_map"> <div className="map-container"> <MapContainer center={[store_longitude, -0.09]} zoom={18} scrollWheelZoom={true} > <TileLayer attribution='&copy; <a href="http://osm.org/copyright"></a>' url="https://{s}.tile.openstreetmap.org/{z}/{x}/{y}.png" /> <Marker position={[51.505, -0.09]}> <Popup>{props.returent_name}</Popup> </Marker> </MapContainer> </div> </div> </div> </> ) } export default ResturentMapOpenDates I cant use the store_longitude variable. It always gives undefined. Because it is undefined leaflet js cant render the map. I am studying react and I am a beginner in this, I am trying to make a map with the Leaflet tool of react. The fact is that when I select a particular country I want it to go to the selected country but it generates an error that is "Error: Invalid LatLng object: (54, undefined)", it would be helpful if … -
Why can't I fully get the value which is a list in python dictionary (Django request)?
I have a form inside of which is a select tag with options, it looks like this: <form method="POST"> {% csrf_token %} <div class="row"> <div class="col-sm-3"> <h4 class="mb-0 mt-2">Title:</h4> </div> <div class="col-sm-9"> <input type="text" name="title" class="form-control" placeholder="Blogpost Title"> </div> </div> <hr> <div class="row"> <div class="col-sm-3"> <h4 class="mb-0 mt-2">Tags:</h4> </div> <div class="col-sm-9"> <select class="form-select" name="tags" multiple aria-label="multiple select example" required> {% for tag in tags %} <option value="{{tag.name}}">{{tag.name}}</option> {% endfor %} </select> </div> </div> <hr> <div class="row"> <div class="col-sm-3"> <h4 class="mb-0 mt-2">Description:</h4> </div> <div class="col-sm-9"> <textarea name="desc" class="form-control" id="exampleFormControlTextarea1" rows="4" placeholder="Blogpost Description (HTML supported)"></textarea> </div> </div> <hr> <div class="text-center"> <button type="submit" class="btn btn-primary">Create</button> </div> </form> And this is my view, where I'm handling it: def create_blogpost(request, id): user = User.objects.get(id=id) tags = Tag.objects.all() if request.method == 'POST': title = request.POST['title'] blogpost_tags = request.POST['tags'] desc = request.POST['desc'] # BlogPost.objects.create( # title=title, # profile=user, # tags=tags, # desc=desc # ) else: pass context = { 'user': user, 'tags': tags } return render(request, 'main/create_blogpost.html', context) When I'm printing out request.POST it looks like this: request.POST <QueryDict: {'csrfmiddlewaretoken': ['TOKEN'], 'title': ['blogpost title'], 'tags': ['Python', 'C++'], 'desc': ['']}> Here I chose 2 tags: Python and C++, but when I'm printing out the variable blogpost_tags, it shows … -
How to query products under Brands individually
I am trying get Product name such as "stethoscope" which has a brand named "Beximco". I want to query all the data from 'm_Product' Table as above. My model: class m_Product(models.Model): name = models.CharField(max_length=200) Brand = models.CharField(max_length=200) quantity = models.IntegerField(default=0, null=True, blank=True) price = models.DecimalField(max_digits=7, decimal_places=2) digital = models.BooleanField(default=False, null=True, blank=True) image = models.ImageField(null=True, blank=True) description = models.CharField(max_length=2000) tags = models.CharField(max_length=20) def __str__(self): return f'{self.name} - {self.quantity} - {self.Brand} - {self.price}' My query: brandData = m_Product.objects.all().values("name").filter('Brand') Help! if you anyone understand this. Thank you! -
django rest framework api saving multiple data in db and using nested serializers
I have 3 serializers: UserCreationSerializer, StudentProfileSerializer, StudentInfoSerializer Now, I want to use my StudentProfileSerialzer as the "parent" which means I want to put UserCreationSerializer and StudentInfoSerialzer inside the StudentProfileSerialzer. I came up with this idea because I dont want to ruin the data integrity so might as well ask all information in one form and then just pop data and insert them into respective serializers Is this even Possible? If it is, someone please tell me how to do it right. And also I want to ask if the way how I create my StudentInfoSerializer is right or wrong, especially the serializers.RelatedField() part. I already worked on UserCreationSerializer and StudentProfileSerializer, and put UserCreationSerializer inside my StudentProfileSerializer, but I dont know how to put StudentInfoSerializer beacause all fields of StudentInfoSerializer are related on different models and some fields are going to be created on the fly when end-user input the data on my forms(example of this is the user). this is the StudentInfoSerializer I want to put in StudentProfileSerializer: class CreateStudentInfoSerializer(serializers.ModelSerializer): student = serializers.Related_Field(source='user',) period = serializers.Related_Field(souce="schoolperiod", read_only= True) adviser = serializers.Related_Field(source= "user", read_only= True) profile = serializers.Related_Field(source="studentprofile") section = serializers.Related_Field(source="Section", read_only= True) class Meta: Model = Student fields= [ 'id','student', … -
Django Widget : load CSS with Media class
I am creating a custom widget for forms, but CSS files are not loaded. Here is the widget: widgets.py from django.forms.widgets import Widget class MyCustomWidget(Widget): template_name = 'widgets/my_custom_widget.html' class Media: css = { 'all': ('css/my_custom_widget.css',) } Here is the call to the widget: models.py from django import forms from .widgets import CalendarWidget class MyForm(forms.Form): field = forms.CharField(widget=MyCustomWidget) The widget seems to be well constructed. The <link> I get from the shell using: >>> import MyCustomWidget() >>> w = MyCustomWidget() >>> print(w.media) <link href="/css/my_custom_widget.css" type="text/css" media="all" rel="stylesheet"> is correct because if I include it in my widget template the css is loaded. But I think the Media class should do this work automatically to make it included in the header (and I dont want to include the css in the main html form). Can you help me loading the CSS ? Thanks ! Django 3.2 documentation: Styling widgets , Media class -
Can I use Django truncatewords filter without image fields?
I upload a photo with ckeditor on my blog and show this photo in the content area. To show the summary of a blog on the home page, I limit the content area to truncatewords, but if there is an image within the word limits I specified, this image is shown in the blog summary. How do I prevent this situation? How can I prevent images from appearing when using the truncatewords filter? {{ blog.content|safe|truncatewords:50 }} -
Django images in static folder can not show on Heroku project
I deployed my app on Heroku. But the images in my static folder won't show up. In my local environment, here is the screenshot But on the project, the images fails to load Here are code in multiple related files. settings.py from pathlib import Path import os # Build paths inside the project like this: BASE_DIR / 'subdir'. BASE_DIR = Path(__file__).resolve().parent.parent # SECURITY WARNING: don't run with debug turned on in production! DEBUG = True ALLOWED_HOSTS = [] # Application definition INSTALLED_APPS = [ 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', # additional django 'django.contrib.sites', 'django.contrib.sitemaps', 'article', 'taggit', 'crispy_forms', ] 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', ] ROOT_URLCONF = 'blog.urls' TEMPLATES = [ { 'BACKEND': 'django.template.backends.django.DjangoTemplates', 'DIRS': [os.path.join(BASE_DIR, 'templates')], 'APP_DIRS': True, 'OPTIONS': { 'context_processors': [ 'django.template.context_processors.debug', 'django.template.context_processors.request', 'django.contrib.auth.context_processors.auth', 'django.contrib.messages.context_processors.messages', 'article.context_processors.common_context' ], }, }, ] WSGI_APPLICATION = 'blog.wsgi.application' # Password validation # https://docs.djangoproject.com/en/3.2/ref/settings/#auth-password-validators AUTH_PASSWORD_VALIDATORS = [ { 'NAME': 'django.contrib.auth.password_validation.UserAttributeSimilarityValidator', }, { 'NAME': 'django.contrib.auth.password_validation.MinimumLengthValidator', }, { 'NAME': 'django.contrib.auth.password_validation.CommonPasswordValidator', }, { 'NAME': 'django.contrib.auth.password_validation.NumericPasswordValidator', }, ] # Internationalization # https://docs.djangoproject.com/en/3.2/topics/i18n/ LANGUAGE_CODE = 'en-us' TIME_ZONE = 'Asia/Taipei' USE_I18N = True USE_L10N = True USE_TZ = True # Static files (CSS, JavaScript, Images) # https://docs.djangoproject.com/en/3.2/howto/static-files/ STATIC_URL = '/static/' STATIC_ROOT = os.path.join(BASE_DIR, 'staticfiles') … -
django REST api not receiving data from query param when getting request from java
I am calling a Django endpoint with the postman and passing some values in query param and its working fine but when i cal the same API from java code it doesn't getting data in params -
How to delete a row in a table using Django?
I want to delete a row from a table in the shell provided by Django. I am running the command Birthdays.objects.delete() but it's not working and gives a syntax error. -
drf-spectacular reverse related objects
I have an issue with reverse related objects in schema. Serializers: class MessageSerializer(serializers.ModelSerializer): files = FileUploadSerializer(many=True, required=False) class Meta: model = Message fields = ['id', 'sender', 'recipient', 'text', 'is_feedback', 'files'] read_only_fields = ['sender'] def create(self, validated_data): files = validated_data.pop('files') message = Message.objects.create(**validated_data) for file in files: File.objects.create(message=message, file=file) return message class FileUploadSerializer(serializers.ModelSerializer): # noqa file_uploaded = fields.FileField() class Meta: model = File fields = ['file_uploaded', 'message'] read_only_fields = ['message'] view is not ready cuz i can't upload files: class MessageList(ViewSet): queryset = Message.objects.all() serializer_class = MessageSerializer permission_classes = (IsAuthenticated,) parser_classes = [MultiPartParser] def list(self, request):... def create(self, request): """Create a new message where sender is current User and recipient is target User.""" files = request.data.get('files', None) print(files) serializer = self.serializer_class(data=request.data) if serializer.is_valid(): serializer.save(sender=request.user) return Response(serializer.data, status=status.HTTP_201_CREATED) else: return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST) The main issue is that this reverse related objects(files) are rendered wrong. image Instead of some kind of file inputs array i got array of json's. What should I do to fix it? I know that I can make it in another way, like just make files = serializer.ListField(child=FileField...) and save this files even without any serializer, but I want to do it in some kind of right way =/ -
Integer field is not increasing on like
I am building a Blog App and I build a feature of increasing points when someone likes the posts. AND I made an IntegerField to count points when post like. BUT Integer field is not increasing when someone likes the post. models.py class Profile(models.Model): user = models.OneToOneField(User, on_delete=models.CASCADE,unique=True) full_name = models.CharField(max_length=100,default='') points = models.IntegerField(default=1) class BlogPost(models.Model): post_owner = models.ForeignKey(User,default='',null=True,on_delete = models.CASCADE) post_title = models.CharField(max_length=500,default='') likes = models.ManyToManyField(User, related_name='post_like', blank=True) views.py def blogpost_like_dislike(request, post_id): post = get_object_or_404(BlogPost, pk=blogpost_id) # Like if request.GET.get('submit') == 'like': if request.user in post.dislikes.all(): request.user.profile.points += 10 # Increasing Here request.user.profile.save() post.dislikes.remove(request.user) post.likes.add(request.user) return JsonResponse({'action': 'undislike_and_like'}) elif request.user in post.likes.all(): post.likes.remove(request.user) return JsonResponse({'action': 'unlike'}) else: post.likes.add(request.user) return JsonResponse({'action': 'like_only'}) else: messages.error(request, 'Something went wrong') return redirect('blogposts') I have tried many times but it is still not increasing. Any help would be much Appreciated. Thank You in Advance. -
Bootstrap Modal Not Showing in Django Template
I have spent way too much time troubleshooting this. Does anyone have any idea why this modal won't pop up? It seems that if I remove the table (that takes up most of the code), the modal then works fine. If I remove the CSS, the modal still doesnt work. Don't judge if it's horrible, only started learning Django, HTML, etc. 2 weeks ago 😛 {% extends 'base.html' %} {% load crispy_forms_tags %} {% block head %} <style> .teacher-list { margin-left: 200px; height: 100%; width: 350px; position: fixed; overflow:hidden; overflow-y:scroll; border-right: 1px solid; border-color: #d3d3d3; } .teacher-list-title { line-height: 1.3; height: 4px; } .teacher-list-text { line-height: 1.3; padding-bottom: 0px; font-weight: normal; height: 4px; } .teacher-body { padding-left: 570px; padding-top: 10px; text-align: center; } .icon-only-button { background: transparent; border: none !important; padding: 0 0 0 0; } .search input { padding-left: 10px; height: 30px; width: 220px; border: none; } .line { margin-left: 550px; width: 100%; border-bottom: 1px solid black; position: absolute; } </style> {% endblock %} {% block content %} <div class="teacher-list"> <table class="table"> <tbody> <tr class="search"> <form method="GET" name="search"> <th scope="row"> <input name="search" type="search" placeholder="Search.." value="{{ search_text }}"> </th> </form> <td> <button type="button" class="icon-only-button" data-bs-toggle="modal" data-bs-target="#exampleModal"> <svg xmlns="http://www.w3.org/2000/svg" width="25" height="25" … -
Unit test cases in Django not executed
I've my Django project's unit test set up. Strangely, regardless of how many I run the command still the test cases didn't get executed. The resulting test always shows ZERO. I suspect is the files/directories permissions issue. Your help and advice are much appreciated. Please see the screenshots below. -
Django smart_str 'NoneType' object has no attribute
In django, I want to download the data to excel using the smart_str, but some record of user dont have data or blank some field like in the error below, how can i do with smart_str which should be unnecessary or error free if no data can be detected? def downloadcv(request): response = HttpResponse(content_type='text/csv') # decide the file name response['Content-Disposition'] = 'attachment; filename="StudentEnrollmentRecord.csv"' writer = csv.writer(response, csv.excel) response.write(u'\ufeff'.encode('utf8')) writer.writerow([ smart_str(u"Guardians_Fullname"), smart_str(u"Guardians_Address"), smart_str(u"Contact_Number"), ]) reports = StudentsEnrollmentRecord.objects.filter(School_Year=yearid).order_by('Education_Levels','-Date_Time') for report in reports: last_name = report.Student_Users.Parent_Users.Guardian_LastName or "" first_name = report.Student_Users.Parent_Users.Guardian_FirstName or "" initial = report.Student_Users.Parent_Users.Guardian_Middle_Initial or "" writer.writerow([ smart_str(last_name, first_name, initial), return response if response is not None else 'None' this is the error i get -
Django Queryset objects and accessing model field attributes
Technology Django 3.2 Model I have a model with fields with properties like max_length and decimal_places. View Furthermore I have a view returning a Queryset with model objects. I would like to access the field attribute like so: Template {{ model_name.field_name.max_length }} {{ model_name.field_name.decimal_places }} also the following does not work: {{ model_name.field_name.field.max_length }} {{ model_name.field_name.field.decimal_places }} Any ideas? It seems to work with a model form, in which the latter examples work. Thanks in advance. -
getting current user in django-import-export
I want to automatically add current user in a field before importing in django-import-export. class MyModel(models.Model): user = models.ForeignKey(User, on_delete = models.CASCADE, null=True, blank=True) name = models.CharField(max_length=100) img = models.ImageField(upload_to='model', null=True, blank=True) slug = models.SlugField(max_length=100) -
In Django Rest Framework, how to parse an object as a field in a serializer?
Suppose I have the following serializer for a Product instance. from rest_framework import serializers class Product: def __init__(self, code): self.code = code class ProductSerializer(serializers.Serializer): code = serializers.CharField() def create(self, validated_data: dict): return Product(validated_data['code']) Now, I can use it like thus to obtain a Product instance from the request data: serializer = ProductSerializer(data=request.data) serializer.is_valid() product = serializer.save() # product is a `Product` instance Now, I have another serializer that have a product as a field: class CompareProductRequestSerializer(serializers.Serializer): product1 = ProductSerializer() product2 = ProductSerializer() Now if I do this: serializer = CompareProductRequestSerializer(data=request.data) serializer.is_valid() p1 = serializer.validated_data['product1'] p2 = serializer.validated_data['product2'] Then p1 and p2 would be dictionaries, and not Product instances (e.g., p1 == {code: '12345'}). How can I get p1 and p2 to be Product instances instead? -
Alert box is unable to show a variable Order Id of the order placed
I am using a checkout page to allow users to place order in my shopping website using django. But once the checkout form is filled and submit button is clicked, an alert box pops up: $('#done').click(function(){ console.log({{ord_id}}) alert('Thanks for ordering with us. Your order Id is {{ord_id}} . Use it to track your order.'); localStorage.clear(); }) Look at the variable inside the alert box string. I am unable to get its value enter image description here The function in views.py which points to the HTML page containing this javascript part, looks like this: def checkout(request): if request.method=="POST": itemsJson=request.POST.get("itemsJson","") name=request.POST.get("name","") email=request.POST.get("email","") phone=request.POST.get("phone","") address=request.POST.get("address1","")+" "+request.POST.get("address2","") city=request.POST.get("city","") state=request.POST.get("state","") zip=request.POST.get("zip","") place_order=Order(itemsJson=itemsJson,name=name,email=email,phone=phone,address=address,city=city,state=state,zip=zip) place_order.save() orderid=place_order.check_id update=UpdateOrder(order_id=orderid,update_email=email,update_desc="Your Order has been Placed") update.save() params={'ord_id':orderid} return render(request,'shop/checkout.html',params) return render(request,'shop/checkout.html') What should I do?? -
Django model query selecting related items and excluding current object
I am using Django 3.2 I have an Article model: from taggit.managers import TaggitManager class Article(models.Model): # fields tags = TaggitManager() In my views, I try to select related articles (using tag similarity as the "distance metric"). This is the statement that returns related articles in my view handling logic: # Note: self.model resolves to `Article` related_posts = self.model.objects.filter(is_published=True, tags__name__in=article_tags_array).exclude(id=article_object.id).prefetch_related().distinct() This statement however, FAILS to EXCLUDE the current object, in the returned QuerySet - despite my *EXPLICITLY invoking exclude() on the returned QuerySet. Why is this happening? How do I fix this, so that the current object is not included in the returned set? -
How to set variable maxValue in django forms
I'm writing a code in django framework for a sales website and the number of available pieces of a certain merchandise is limited. to obtain the number of remaining products I have to call a certain function. Now I wanted to ask if there's any way to call this function in the models.py or forms.py modules or any other way to set this limit. This is my view module: from django.http.response import HttpResponse, HttpResponseRedirect from django.shortcuts import render from .forms import orderForm from regpage.models import User from django.views import View class orderView(View): def get(self, request): form = orderForm() return render(request, "dashboard/order.html", {'form': form,}) This is my forms module: from django import forms from .models import Order class orderForm(forms.ModelForm): class Meta: model = Order fields = ['productCount'] This is my models module: from django.db import models from django.db.models.enums import Choices from regpage.models import User from django.core import validators from django.core.validators import EmailValidator, MaxValueValidator, MinValueValidator class Order(models.Model): userID = models.ForeignKey(User, on_delete=models.CASCADE) productCount = models.PositiveSmallIntegerField() #THE LIMITED FIELD This is my html file: {% extends 'dashboard.html' %} {% block dashTitle %} Order {% endblock dashTitle %} {% block dashContent %} <p style="text-align:center;font-size:30px;"><b> Order Page </b> </p> <form style="text-align:center;font-size:25px" method="POST"> {% csrf_token %} {% … -
MultiValueDictKeyError at /upload_notes
I am unable to solve this error since 10 days. I refer all over google but did not get solution of it. Please someone help me to solve this error. upload_notes.htmlfile <form method="POST" enctype="multipart/form-data"> {% csrf_token %} <label>Notes File</label> <input type="file" class="form-control" name="notesfile" > <input type="submit" class="btn btn-danger mt-2" value="Submit"> </form> views.py def upload_notes(request): if not request.user.is_authenticated: return redirect('login') error="" if request.method=='POST': b=request.POST['branch'] s=request.POST['subject'] n=request.POST['notesfile'] f=request.POST['filetype'] d=request.POST['description'] u=User.objects.filter(username=request.user.username).first() try: Notes.objects.create(user=u,uploadingdate=date.today(),branch=b,subject=s, notesfile=n,filetype=f,description=d,status='pending') error="no" except: error="yes" d={'error':error} return render(request,'upload_notes.html',d) enter image description here This is the error image -
I cannot connect my form to my models for posting of grades
Models.py class YearLevel(models.Model): ... class Section(models.Model): ... class Subject(models.Model): ... class Student(models.Model): first_name = models.CharField(max_length = 100, default = '') last_name = models.CharField(max_length = 100, default = '') year_level = models.OneToOneField(YearLevel, on_delete=models.SET_NULL, null = True) section = models.OneToOneField(Section, on_delete=models.SET_NULL, null = True) enrolled_subject = models.ManyToManyField(Subject) parent = models.ForeignKey(Parent, on_delete=models.SET_NULL, null = True) #parent is from user models class StudentGrade(models.Model): PERIOD_CHOICES = [ ... ] student = models.ForeignKey(Student, on_delete=models.CASCADE,) period = models.CharField(choices=PERIOD_CHOICES, max_length = 30) subjects = models.ForeignKey(Subject, on_delete=models.CASCADE) grade = models.DecimalField(default = 75.00, max_digits=4, decimal_places=2) Views.py def postgrade(request): students = Student.objects.all().prefetch_related('enrolled_subject') context = { 'students': students, } if request.method == "POST": data = request.POST grade_list = data.getlist('grade') subject_list = data.getlist('subject') student = Student.objects.get(pk= data.get('studentid')) #this is where they point my error i=0 while i < len(grade_list): enrolled_subject = Subject.objects.get(pk= subject_list[i]) new_grade = StudentGrade(student = student, period= data.get('period'), subjects = enrolled_subject, grade=grade_list[i]) new_grade.save() i+= 1 Postgrade.html(template) My queries are displaying properly, the problem is I get an error when i try to save the form {% for students in students %} <p> <a class="btn btn-primary" data-bs-toggle="collapse" href="#collapse{{forloop.counter}}" role="button" aria-expanded="false" aria-controls="collapse{{forloop.counter}}"> {{students.first_name}} {{students.last_name}} </a> </p> <div class="collapse" id="collapse{{forloop.counter}}"> <div class="card card-body"> <form method="POST" > {% csrf_token %} <input type="hidden" name="studentid" value="{{students.student.id}}"> <label … -
Display all days in specific month for data
I want to create a table that displays all days of a given month, and then check if this day is in the database, if it displays the necessary data for a given record at the moment i have loop for display all days for month: def example_table(request,pk,month): something = database.filter(pk=pk).all() num_days = monthrange(2021, month)[1] num_days = range(1,num_days+1) context = locals() in template i was add something like that: {%for time in num_days%} {%for x in something%} {%if x.day == time%} table {%endif%} {%endfor%} {%endfor%} but this record is repeated x times. Someone can give me some advice how to do that ? should looks like 1 data data data 2 3 4 data data data ...etc -
UnboundLocalError while using Django Querysets
I am trying to implement the following Django Queryset in my webapp: from django.db.models import When, Case, Value, Sum, IntegerField, F from django.shortcuts import render,redirect from hr.models import * def mobile_recharge(request): S=['0'] T=['1'] B=['A','B','C'] db_obj1=BillsPayment.objects.using('MBDB').all() db_obj2=BillsService.objects.using('MBDB').all() while db_obj1.values('BILLER_ID')==db_obj2.values('BILLS_SERVICE_CODE') and db_obj2.values('BILLS_TYPE')=='3': data = db_obj1.annotate( Transaction_type=F('BILLER_ID'), Success=Sum(Case( When(ERROR_CODE__in=S, then=Value(1)), default=Value(0), output_field=IntegerField() )), Technical_declines=Sum(Case( When(ERROR_CODE__in=T, then=Value(1)), default=Value(0), output_field=IntegerField() )), Business_declines=Sum(Case( When(ERROR_CODE__like='B',then=Value(1)), When(ERROR_CODE__in=B, then=Value(1)), When(ERROR_CODE__isnull=True, then=Value(1)), default=Value(0), output_field=IntegerField() )) ).order_by(Transaction_type) return render(request,'hr/test.html',{'model':data}) Which is supposed to execute the following SQL Query: SELECT 'MOB' AS TYPE, SUM(case when BP.ERROR_CODE in ('0') then 1 else 0 end) SUCCESS, SUM(case when BP.ERROR_CODE in ('1') then 1 else 0 end) TECHNICAL_DECLINES, SUM(case when (BP.ERROR_CODE LIKE '%ERR%' OR BP.ERROR_CODE in ('A','B','C') or BP.ERROR_CODE is null ) then 1 else 0 end) BUSINESS_DECLINES FROM BP,BS WHERE BP.BILLER_ID=BS.BILLS_CODE AND BS.BILLS_TYPE='3'; When I run the server using the python manage.py runserver command however the browser is giving the UnboundLocalError: Please help me with this. Thank you.