Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
"ValueError: year is out of range" with Django
When I started my current position, I inherited a Django Rest API that sits on top of our Postgres database. It was still running on Django v.1.7.11. Now almost two years later, I decided it's finally time to upgrade. I first upgraded to Django v1.11.29 (planning on getting it more current, but wanted to upgrade somewhat incrementally). I fixed any errors caused by the upgrade and was all set. I was able to access it and everything worked properly, except for reading data from one table. This table contains four date fields, and when accessing it's API endpoint, I get the following error: Request Method: GET Request URL: http://obis.twalk.tech:81/api/obis/occurrence/ Django Version: 1.11.29 Exception Type: ValueError Exception Value: year is out of range Exception Location: /usr/local/lib/python2.7/site-packages/django/db/utils.py in inner, line 101 Python Executable: /usr/local/bin/python Python Version: 2.7.18 From what I could tell initially with the debug output, this error was caused by having a null values in one of the date fields. I'm working in a personal development environment so I was able to change, at the database level, each instance of a null value in any of the date fields to be a properly formatted date. I still got the same … -
Got AttributeError when attempting to get a value for field `user` on serializer
I am trying to upload a csv file and then using it to populate a table in the database (creating multiple objects). serializers.py: class FileUploadSerializer(serializers.ModelSerializer): filedata = serializers.FileField(write_only=True) class Meta: model = WorkData fields = ['user', 'filedata'] def create(self, validated_data): file = validated_data.pop('filedata') data_list = csv_file_parser(file) # utility method batch = instantiate_batch_objects(data_list, validated_data['user']) # utility method work_data_objects = WorkData.objects.bulk_create(batch) # print(work_data_objects[0]) return work_data_objects views.py: class FileUploadView(generics.CreateAPIView): queryset = WorkData.objects.all() permission_classes = [IsAuthenticated] serializer_class = FileUploadSerializer def get_serializer(self, *args, **kwargs): print(kwargs.get('data')) if isinstance(kwargs.get('data', {}), list): kwargs['many'] = True return super().get_serializer(*args, **kwargs) models.py class WorkData(models.Model): user = models.ForeignKey( settings.AUTH_USER_MODEL, on_delete=models.CASCADE, related_name='work_data', ) work = models.IntegerField(blank=False, null=False) recordTime = models.DateTimeField(blank=False, null=True) When I upload the file and post it I get this error: Got AttributeError when attempting to get a value for field user on serializer FileUploadSerializer. 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 'user'. But I can see table is populated successfully in the database. What could be the source for this error? -
Django collectstatic keeps waiting when run through Github Action
We are facing a very weird issue. We ship a django application in a docker container through Github Actions on each push. Everything is working fine except collectstatic. We have the following lines at the end of our CD github action: docker exec container_name python manage.py migrate --noinput docker exec container_name python manage.py collectstatic --noinput migrate works perfectly fine, but collectstatic just keeps on waiting if ran through the github action. If I run the command directly on the server then it works just fine and completes with in few minutes. Can someone please help me figuring out what could be the issue? Thanks in advance. -
TypeError: serve() got an unexpected keyword argument 'document_root'
my problem Here the image/file that the user uploaded aren't being displayed(They are being saved though!!) when I run the site using Terminal I get an error message on Terminal TypeError: serve() got an unexpected keyword argument 'document_root' but the site runs just fine. when I open my site on chrome it displays name of the image/file and only a symbol of an image/file but i want it to display the image/file it self not a symbol. Setting.py: STATIC_URL = '/static/' MEDIA_ROOT = os.path.join(BASE_DIR, 'media') MEDIA_URL = '/media/' ( This only some part of the urls.py) urls.py: from django.urls import path from django.conf import settings from django.conf.urls.static import static urlpatterns += static(settings.MEDIA_URL, documnet_root=settings.MEDIA_ROOT) ( This is also some part of the html file that displays the image) file.html {% if model.image %} <image src="{{model.image.url}}"> {% endif %} -
Django. Error saving empty string to DateTimeField(blank=True)
I have a model with a DateTimeField (blank=True, null=True). However, when I try to save an empty string in it, I get the following error: >>> from courses.models import Event >>> x = Event.objects.last() >>> x.date_start = "" >>> x.save() django.core.exceptions.ValidationError: ['“” value has an invalid format. It must be in YYYY-MM-DD HH:MM[:ss[.uuuuuu]][TZ] format.'] I have never seen this, any ideas? All my migrations are up to date. -
Django + Mongo + Docker getting pymongo.errors.ServerSelectionTimeoutError
I've been struggling to get a simple app running using Django, Djongo, Mongo, and Docker Compose. My setup looks like this: docker-compose.yml services: mongodb: image: mongo:latest restart: always environment: MONGO_INITDB_ROOT_USERNAME: root MONGO_INITDB_ROOT_PASSWORD: mongoadmin MONGO_INITDB_DATABASE: django_mongodb_docker ports: - 27017:27017 web: build: ./src restart: always command: python src/manage.py runserver 0.0.0.0:8000 volumes: - .:/code ports: - 8000:8000 links: - mongodb Dockerfile FROM python:3 ENV PYTHONUNBUFFERED=1 RUN mkdir /code COPY . /code/ WORKDIR /code COPY requirements.txt /code/ RUN pip install -r requirements.txt settings.py DATABASES = { 'default': { 'ENGINE': 'djongo', 'HOST': 'mongodb', 'PORT': 27017, 'USER': 'root', 'PASSWORD': 'mongoadmin', 'AUTH_SOURCE': 'admin', 'AUTH_MECHANISM': 'SCRAM-SHA-1', } } What is annoying is that I am able to use pymongo from my web container to connect to the container running mongo. That works as follows. from pymongo import MongoClient c = MongoClient( 'mongodb://mongodb:27017', username='root', password='mongoadmin', authSource='admin', authMechanism='SCRAM-SHA-1') print(c.server_info()) The issue is that when I go to run migrations from within my web container I get the following error. pymongo.errors.ServerSelectionTimeoutError: localhost:27017: [Errno 111] Connection refused, Timeout: 30s, Topology Description: <TopologyDescription id: 5f9c8d338cc55e515780edb9, topology_type: Single, servers: [<ServerDescription ('localhost', 27017) server_type: Unknown, rtt: None, error=AutoReconnect('localhost:27017: [Errno 111] Connection refused')>]> Any help on this would be greatly appreciated. -
How to edit the html page and save it at the same page using Django?
I have HTML page that contains a title and content that title, I had created an edit link that directs me to another page that should let me update the title and the content, and after editing click a button to save that update. How i can let the user do this kind of updating using Django? this is my HTML page <h1>CSS</h1> <p>CSS is a language that can be used to add style to an HTML page.</p> <ul> <li><a href="{% url 'wiki:edit' %}">Edit</a></li> </ul> -
How to write if else condition to retrieve data by querying django filter
I want to write if else condition for django filter to retrieve data by querying in django rest framework. I want to qerry data by filtering class CreateRoutineFilter(filters.FilterSet): class Meta: model = CreateRoutine fields = ('batchCode', 'roomCode') class CreateRoutineViewSet(viewsets.ModelViewSet): queryset = CreateRoutine.objects.all() serializer_class = CreateRoutineSerializer filterset_class = CreateRoutineFilter filter_backends = (django_filters.rest_framework.DjangoFilterBackend,) __basic_fields = ( 'dpt_code', 'roomCode') filter_backends = (filters.DjangoFilterBackend, OrderingFilter) filter_fields = __basic_fields def retrieve(self, request, *args, **kwargs): params=kwargs print(params['pk']) # programs = Program.objects.all() if(coursesOffered = CourseOffered.objects.filter(batchCode = params['pk'])) else: (coursesOffered = CourseOffered.objects.filter(dpt_code = params['pk'])) serializer = CourseOfferedMiniSerializer(coursesOffered, many=True) return Response(serializer.data) -
Django Rest API: View definition delete queryset
I'm still pretty new to creating views in Django Rest Framework, I can make basic views but I still have no clue about definitions so please help me out here. I've got this View which gets the answers of a question (by a given question id). The list definition works perfectly, however I want to make a delete_all function which deletes these results. You can see what I came up with below. URL router.register('manager/course/question/answers', QuestionAnswerView) http://.../manager/course/question/answers/5 works. http://.../manager/course/question/answers/delete_all/5 does not work. View class QuestionAnswerView(viewsets.ModelViewSet): queryset = QuestionAnswer.objects.all() serializer_class = QuestionAnswerSerializer # works def list(self, request): queryset = QuestionAnswer.objects.all() if request.query_params: question_id = request.query_params['question_id'] queryset = QuestionAnswer.objects.filter(question=question_id) serializer = QuestionAnswerSerializer(queryset, many=True) return Response(serializer.data) # does not work def delete_all(self, request): if request.query_params: question_id = request.query_params['question_id'] queryset = QuestionAnswer.objects.filter(question=question_id) queryset.delete() return Response('success') -
Stream multiple files with a single request using python requests
I'm using python's requests library to upload images into a server created by django / drf. It is a simple task and test script looks like this: files = { 'client_files[0]': ('415.png', open('E:\\Olaylar\\test_set\\cvat_test_small\\415.png', 'rb')), 'client_files[1]': ('422.png', open('E:\\Olaylar\\test_set\\cvat_test_small\\422.png', 'rb')), 'client_files[2]': ('485.png', open('E:\\Olaylar\\test_set\\cvat_test_small\\485.png', 'rb')) } payload = { 'image_quality': 50 } response = requests.post(post_url, auth=auth, data=payload,files=files) The problem is, I need to upload hundreds, if not thousands of images, and in a single request. So when I try to read all files into memory in order to post them, I run out of memory quite fast. I know there is a possible solution, by putting a generator in data argument of post method, and streaming the data by chunks. That would solve my problem quite well, but requests library does not support that functionality in files argument of the post method too. I will be grateful for any help or advice how to solve this problem. Thanks in advance -
Webfaction Alternative
Will Heroku work for a website that has these features? We're looking for a web host with the following features—ideally a large, stable company (been around at least 5 years)—one that charges a reasonable monthly fee for the following: Latest versions of Django and Python Has inexpensive tier of hosting appropriate for a low-traffic Django site—on a typical day there may be a handful of users (perhaps between 5 and 50?), doing low-bandwidth activities (e.g. filling out text forms) Nginx or similar service to handle static files Postgres database (ideally with user-friendly database-management software for Postgres databases) Supports having multiple working versions (development, release candidate, and production) running at the same time, using different subdomains Supports wkhtmltopdf (to convert webpages to downloadable PDF files) Supports ability to send individual emails from Django -
Django field values are not getting autopopulated in TabularInline in admin.py
can you please help me with the below query in django TabularInline: In models.py, I have model A and B class A (models.Model): Name = models.CharField(max_length=100) Location = models.CharField(max_length=100) def__(str)__(self) : return "%s" %(self.Name) class B(models.Model): Name = models.ForeignKey(A, on_delete=models.cascade) Added_by = models.ForeigKey(User, null=True,on_delete=models.cascade,related_name="Added_by") Added_date = models.DateTimeField(default=datatime.now) Modified_by = models.ForeigKey(User, null=True,on_delete=models.cascade,related_name="Modified_by") Modified_date = models.DateTimeField(editable=False,blank=True) In admin.py , class B_admin(admin.TabularInline): model = B extra = 0 readonly_fields=["Added_by","Added_date","Modified_by","Modified_date"] classes = ('grp-collapse grp-closed',) inline_classes = ('grp-collapse grp-closed',) def save_model(self, request,obj form, change): if getattr(obj, '', None) is None: obj.Added_by = request.user obj.Modified_by = request.user obj.Added_date = datetime.now() obj.Modified_date = datetime.now() else: obj.Modified_by = request.user obj.Modified_date = datetime.now() obj.save() class A_admin (admin.ModelAdmin): Inline = [B_admin] list_display = ['Name','location'] list_filter = ['Name','location'] search_fields = ['Name','location'] classes = ('grp-collapse grp-closed',) inline_classes = ('grp-collapse grp-closed',) Here , the admin page A is working fine with Model B as TabularInline. Also, the readonly_fields looks good inside TabularInline. Now the problem is when the admin page gets saved , the readonly_fields(Added_by,Modified_by,Modified_date) are showing blank and are not getting autopopulated . Added_date is working correctly since i have mentioned default=datetime.now while declaring inside model B. Other 3 fields are not getting autopopulated. Kindly assist me in this . Thanks in … -
How can i add an item to a user in django (rest framework)
I have a Teammodel and a Usermodel. Every User can belong to one or more Teams. The creation of a user with a Team is working fine. But i want to add a existing user to a existing Team. I tried several options but for every option i get an error. The Models: class Teams(models.Model): name = models.CharField(max_length=20) file = models.FileField(upload_to='team_icons', null='True', blank='True') members = models.ManyToManyField(User, related_name='member') def __str__(self): return self.name **The Serializers:** class UserSerializer(serializers.ModelSerializer): member = serializers.PrimaryKeyRelatedField(many=True, queryset=Teams.objects.all()) class Meta: model = User fields =['id', 'username', 'owner', 'password', 'todos','member', 'email', 'first_name', 'last_name',] The View class AddUserToTeam(generics.RetrieveUpdateDestroyAPIView): queryset = models.User.objects.all() serializer_class = serializers.UserSerializer permission_classes = [permissions.AllowAny] So i want: user.member.add(x), x is the team where user had to be added to -
How to display data dynamically with ant design tables
first please my javascript skill level is not good, but here... I have a table i got from ant.design, im trying to build a frontend with react, so I want to display some data on the table from my database but im finding it had because of the want ant design table is set up. This is the code class OrderSummary extends React.Component { render() { const columns = [ { title: 'Number', dataIndex: 'number', key: 'number', render: text => <a>{text}</a>, }, { title: 'Event Name', dataIndex: 'name', key: 'name', }, { title: 'Event Price', dataIndex: 'price', key: 'price', }, { title: 'Quantity', dataIndex: 'quantity', key: 'quantity', }, { title: 'Total', dataIndex: 'total', key: 'total', }, ]; const datasource = {data.order_items.map((orderItem, i) => { return ( [ { key: {orderItem.id}, number: {orderItem.item.title} -{" "}, name: 32, price: 'NGN' {orderItem.item.price} , quantity: {orderItem.quantity}, total: {data.total}, }, // { // key: 1, // name: 'John Brown', // age: 32, // address: 'New York No. 1 Lake Park', // tags: ['nice', 'developer'], // }, ]; return ( <Layout> <div> <PageHeader className="site-page-header" onBack={() => null} title="Order Summary" /> <Table columns={columns} dataSource={datasource} /> </div> </Layout> ) } }; export default OrderSummary; Note where i commented … -
I have a problem when testing my api on localhost everything went okay however when deployed to dev server and need to test it I get KeyError 'Date'
class Prayers(APIView): parser_classes = (JSONParser,) permission_classes = (rest_permissions.AllowAny,) def get(self, request): """ API for the visitorstrong text to get all prayers paginated """ data = helpers.dict_filter(request.query_params.dict(), 'date','nbdays') if "nbdays" in data : days=timedelta(days=int(data['nbdays'])) if "date" in data: date = datetime.strptime(data['date'], constants.GENERAL.DATE_FORMAT) date=date+days else: today=datetime.now() date=today+days elif "date" in data: date = datetime.strptime(data['date'], constants.GENERAL.DATE_FORMAT) days=timedelta(days=30) date=date+days else: today=datetime.now() days=timedelta(days=30) date=today+days serializer = PrayerSerializer( models.Prayer.objects.get(pk=date) ) response = { "prayer times": serializer.data, } return Response(response, status=status.HTTP_200_OK) 'API to get prayers time through filtering' -
How to avoid repetition in Django model fields?
I have models that share many common fields. For example: class Customer(models.Model): name = models.CharField() email = models.CharField() address = models.CharField() phone = models.CharField() city = models.CharField() state = models.CharField() country = models.CharField() wallet = models.FloatField() class Seller(models.Model): # same fields from Customer class, except the field wallet To avoid repeating these fields, I have tried to create classes with these common fields and link using OneToOneField: class ContactInformation(models.Model): phone = models.CharField() email = models.CharField() class AddressInformation(models.Model): address = models.CharField() city = models.CharField() state = models.CharField() country = models.CharField() class Customer(models.Model): wallet = models.FloatField() contact_information = models.OneToOneField(ContactInformation) address_information = models.OneToOneField(AddresssInformation) class Seller(models.Model): contact_information = models.OneToOneField(ContactInformation) address_information = models.OneToOneField(AddresssInformation) But now it gets very messy if I try to create a ModelForm based on the Customer, as there is only the wallet field in it. To display my other OneToOneFields I have to create multiple forms: a form for the contact information and another for address information, as ModelForms don't simply display these OneToOneFields as a single form. The views get bloated, as I have to validate 3 forms in total and have to manually create the object instances. Am I missing something here? Should I use inheritance instead? Should I … -
Get and assign elements in variables from a Nested List in Python
i'm working with a nested list in python like this list[[a,b,c,d,e],[a,b,c,d,e]] every element is composed ever of 5 parts, the content of the list can change in amounts of elements it can be from 1 to 10 elements max. Here came the difficult for me, cause I need to assign any part of every element into one individual variable, and when the element end, move to the next element,but before move send variables to one function that insert data in the oracle database. It is a part of a function in python django web app. The idea is to separate the data received in form a list after that send it to a stored procedure. This is part of the code. enter code here acomp = '' acomp = request.POST.getlist("acomp") split_strings = [] #Here divide the list in 5 parameters that are the rows of the table in #oracle n = 5 for index in range(0, len(acomp), n): #Creamos una lista anidada para dividir los datos de los acompañantes por cada uno split_strings.append(acomp[index : index + n]) #ow I can seperate the data assign every element into a variable and send it to the function that will insert it in … -
how to show images from serializers list in django using jquery ajax
I want to show image from serializers list view using jquery . I wanted to show all the tweets using ajax but i have no idea how to show image using jquery ajax models.py class Tweet(models.Model): content = models.CharField(max_length=140) author = models.ForeignKey(User,on_delete=models.CASCADE) Image = models.FileField(upload_to="images/",blank=True) updated = models.DateTimeField(auto_now=True) timestamp = models.DateTimeField(auto_now_add=True) serializers.py class TweetModelSerializers(serializers.ModelSerializer): author = UserDisplaySerializer() class Meta: model = Tweet fields = ['content','author','Image'] views.py class TweetListAPIView(generics.ListAPIView): serializer_class = TweetModelSerializers def get_queryset(self,*args,**kwargs): qs = Tweet.objects.all().order_by("-timestamp") print(self.request.GET) query = self.request.GET.get("q", None) if query is not None: qs = qs.filter( Q(content__icontains=query) | Q(user__username__icontains=query) ) return qs jquery $.ajax({ url:"/api/tweet", method:"GET", success: function(data){ //console.log(data) $.each(data,function(key,value){ //console.log(key) console.log(value.Image) var tweetContent = value.content; var tweetUser = value.author; var tweetImage = value.Image; $("#tweet-container").append( "<div class=\"media\"><div class=\"media-body\">" + tweetContent + "<br/> via " + tweetUser.username + " | " + "<a href='#'>View</a>"+"<br>" + tweetImage + "</div></div><hr/>" ) }) }, error:function(data){ console.log("error") } }) this method doesnot show the image. It only show the name of the images like http://127.0.0.1:8000/img/images/FB_IMG_1538467390993.jpg . How can i show the images in jquery ? -
Django actual value in choice field form
I have models like this: class Projects(models.Model): project = models.CharField(max_length=150, blank=True, null=True) def __str__(self): return self.project class Profile(models.Model): user = models.OneToOneField(get_user_model(), on_delete=models.CASCADE) project = models.ForeignKey(Projects, on_delete=models.CASCADE, null=True, blank=True) def __str__(self): return self.user.username I also made a form in which I want to change current Project assigned Profile: class ProjectForm(ModelForm): class Meta: model = Profile fields = [ 'project' ] My view looks like this: def change_project(request, user): user = User.objects.filter(username=user)[:1].get() profile = Profile.objects.get(user=user) form = ProjectForm(request.POST, instance=profile) if request.method == 'POST': if form.is_valid(): form.save() context = {'form': form} return render(request, 'datafiller/change_project.html', context) I can change the project using this form, but every time I want to do it again the form looks like this How can I show in the form the current project instead of "------"? -
How to create a custom templatetag in my django project
I have been trying create a custom templatetag in my project , but it does not work This is my structured project : I created a folder in my index directory called templatetags > __init__.py , extras.py , inside extras file this: from django import template register = template.Library() def cut(value): return value.replace("no", 'yes') Template : {% load poll_extras %} but I got this -
CSS inheritance in Django templates
I want to split my CSS to multiple files to match with each template and app. But the following problem keeps me baffled. In the base.css of my base.html template, I have an element class button declared as following: .button { ... } So, all buttons should follow this css. In an app called table, in a template table_view.html that extends base.html {% extends "base.html" %} {% load static %} {% block content %} <link href="{% static 'css/table.css' %}" rel="stylesheet" /> ... <button class="btn-avail table">Table</button> ... {% endblock %} I have a different format for class btn-avail in table.css. But I could not get it to load and override the base format. If I change the class name to button (of base.css), then it reflects the base format. Or if I place btn-avail in the base.css, then its format is correctly reflected. In my settings.py, here is my static directory: STATIC_URL = '/static/' STATICFILES_DIRS = ( os.path.join(BASE_DIR, 'static'), ) STATIC_ROOT = os.path.join(BASE_DIR, 'staticfiles') What am I doing wrong? Thanks. -
Hi All! I'm getting a "Bad Request (404)" error after deploying a Django app to Heroku
This is my first question on Stackoverflow so please bare with me. I've been trying to deploy a Django app to Heroku using AWS S3 as the place for my media storage. I've gone through what's neccesseryto get everything up and running (see settings.py code below) but can't figure out why I keep hitting the "Bad Request (404)" error page. Here's part of my heroku logs --tail traceback. I originally thought the issue was with Gunicorn but all seems to be fine there. If you need to see the rest please let me know as SO wont allow me to post the full traceback. 2020-10-30T18:20:28.057488+00:00 heroku[router]: at=info method=GET path="/" host=fryed-project.herokuapp.com request_id=8daaabd0-3f8d-4f87-847e-25291d4372fc fwd="176.26.119.21" dyno=web.1 connect=1ms service=193ms status=400 bytes=476 protocol=https 2020-10-30T18:20:28.058801+00:00 app[web.1]: 10.12.135.75 - - [30/Oct/2020:18:20:28 +0000] "GET / HTTP/1.1" 400 143 "-" "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/86.0.4240.111 Safari/537.36" 2020-10-30T18:20:28.352784+00:00 heroku[router]: at=info method=GET path="/favicon.ico" host=fryed-project.herokuapp.com request_id=bc9d6397-6f63-4be7-a19f-826165de2cf6 fwd="176.26.119.21" dyno=web.1 connect=0ms service=127ms status=400 bytes=476 protocol=https 2020-10-30T18:20:28.353864+00:00 app[web.1]: 10.12.135.75 - - [30/Oct/2020:18:20:28 +0000] "GET /favicon.ico HTTP/1.1" 400 143 "https://fryed-project.herokuapp.com/" "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/86.0.4240.111 Safari/537.36" 2020-10-30T18:20:42.832461+00:00 heroku[router]: at=info method=GET path="/" host=fryed-project.herokuapp.com request_id=34319de1-399e-4c72-91b4-c9c3a173c0f7 fwd="176.26.119.21" dyno=web.1 connect=0ms service=18ms status=400 bytes=476 protocol=https 2020-10-30T18:20:42.833907+00:00 app[web.1]: 10.12.135.75 - … -
Populate another input field based on another field using ajax, Django
I am trying to populate one input field based on another field. I am using raw SQL query instead of ORM. My views : def myview(request): form=searchform(request.POST) conn = cx_Oracle.connect("xyz","abcde","TESTDB",encoding="UTF-8") rows=[] if request.method=='POST': empno = form['empno'].value() try: cursor = conn.cursor() sql_query=""" select empno,emp_name from tb_ps_emp_info where empno= :emp_no_insert and status=:status """ emp_no_insert=empno status_="W" data = { "emp_no_insert": emp_no_insert, "status": status_, } cursor.execute(sql_query,data) columns = [col[0] for col in cursor.description] cursor.rowfactory = lambda *args: dict(zip(columns, args)) rows = cursor.fetchall() finally: conn.close() for row in rows: employee_name=row['EMP_NAME'] context={ "rows":rows, "form":form, "employee_name":employee_name, } return render(request,"test.html", context) @csrf_exempt def ajaxviews(request): empno = request.POST.get("empno") conn = cx_Oracle.connect("xyz","abcde","TESTDB",encoding="UTF-8") cursor = conn.cursor() sql_query=""" select empno,emp_name from tb_ps_emp_info where empno= :emp_no_insert and status=:status """ emp_no_insert=empno status_="W" data = { "emp_no_insert": emp_no_insert, "status": status_, } cursor.execute(sql_query,data) columns = [col[0] for col in cursor.description] cursor.rowfactory = lambda *args: dict(zip(columns, args)) rows = cursor.fetchall() print(rows) context={ "rows":rows, } return HttpResponse(context) Urls: urlpatterns = [ path('admin/', admin.site.urls), path('test/',views.myview,name="test"), path('test_ajax/',views.ajaxviews,name="test_ajax"), ] forms: class searchform(forms.Form): empno=forms.CharField(label="empno", max_length=50, widget=forms.TextInput(attrs={"class":"form-control"})) empname=forms.CharField(label="empname", max_length=50, widget=forms.TextInput(attrs={"class":"form-control"})) HTML: <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js"></script> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <title>Document</title> </head> <body> <form action="" method="POST"> {% csrf_token %} <p><label for="id_empno">empno:</label> <input type="text" name="empno" class="form-control" maxlength="50" required="" id="id_empno"></p> <input type="Submit" name="submit" value="Submit"> </form> <p><label … -
Django 3: How to pass 'rows' into the html template?
I'm building a Crud table template as the user has many many tables to update and I'm having trouble passing on the records to the template. Here is my view: def crud_table(request): user = request.user org = Organization.objects.filter(user=user) active_project = Project.objects.filter(organization=org[0], is_active=True)[0] assets = Asset.objects.filter(project=active_project) context_lbls = {'name': 'Name', 'asset_id': 'Asset ID', 'det_curve': "Deterioration Curve", 'class': 'Class', 'surface_type': 'Surface Type', 'Age': 'Age', 'AADT': 'AADT', 'AADTT': 'AADT', 'route': 'Bus Route', 'truck_route': 'Truck Route', 'Length': 'Asset Length', 'HCI': 'HCI' } context_data = {'name': Asset.objects.filter(project=active_project), 'asset_id': assets.asset_id, 'det_curve': assets.det_curve.name, 'class': assets.func_class.name, 'surface_type': assets.surface_type.name, 'Age': assets.age, 'AADT': assets.aadt, 'AADTT': assets.aadtt, 'route': assets.is_bus_route, 'truck_route': assets.is_truck_route, 'Length': assets.length, 'HCI': assets.hci } context = {'labels': context_lbls, 'records': context_data} And here is my template: <thead> <tr> <th> <span class="custom-checkbox"> <input type="checkbox" id="selectAll"> <label for="selectAll"></label> </span> </th> {% for l in labels %} <th>{{l}}</th> {% endfor %} </tr> </thead> <tbody> <tr> <td> <span class="custom-checkbox"> <input type="checkbox" id="checkbox1" name="options[]" value="1"> <label for="checkbox1"></label> </span> </td> {{ records }} {% for r in records %} <td>{{r}}</td> {% endfor %} </tr> </tbody> My context_data is obviously incorrect, I'm just not sure how to pass the information to the template. I'm doing all of this to avoid having to create multiple HTML files and … -
Django: Sum of annotated field
I have the following two models: class ProductionSet(models.Model): product = models.ForeignKey(Product, on_delete=models.CASCADE) line = models.ForeignKey(Line, on_delete=models.CASCADE) class ProductionSetEntry(models.Model): productionset = models.ForeignKey( ProductionSet, on_delete=models.CASCADE, related_name="set" ) audited_at = models.DateTimeField( verbose_name=_("Audited at"), null=True, blank=True ) What I want to achieve is a result set grouped for each line with two counts: an entries total count and a count for fully audited sets. Sample result: <QuerySet [{'line': 1, 'sum_fully_audited': 0, 'total': 43}, {'line': 2, 'sum_fully_audited': 0, 'total': 51}, {'line': 3, 'sum_fully_audited': 2, 'total': 4}]> I'm able to add the fully_audited to each row before grouping by: ProductionSet.objects.annotate( audited=Count("set", filter=Q(set__audited_at__isnull=False)), ).annotate( fully_audited=Case( When(audited=Count("set"), then=1), default=0, output_field=IntegerField(), ) ) Following query: ProductionSet.objects.annotate( audited=Count("set", filter=Q(set__audited_at__isnull=False)), ).annotate( fully_audited=Case( When(audited=Count("set"), then=1), default=0, output_field=IntegerField(), ) ).values( "line", "fully_audited" ).annotate( total=Count("id", distinct=True), sum_fully_audited=Sum("fully_audited"), ).order_by( "line" ) raises django.core.exceptions.FieldError: Cannot compute Sum('fully_audited'): 'fully_audited' is an aggregate while ProductionSet.objects.annotate( audited=Count("set", filter=Q(set__audited_at__isnull=False)), ).annotate( fully_audited=Case( When(audited=Count("set"), then=1), default=0, output_field=IntegerField(), ) ).values( "line", "fully_audited" ).annotate( total=Count("id", distinct=True), ).order_by( "line" ) results in <QuerySet [{'line': 1, 'fully_audited': 0, 'total': 43}, {'line': 3, 'fully_audi... which looks good so far but obviously has no sum_fully_audited yet.