Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Can anyone please help/tell me what I am doing wrong? And/Or what I shouldve done in my queries?
I have 3 models that I am using my query on: Models.py class Student(models.Model): ... class SchoolPeriod(models.Model): period = models.CharField(max_length = 100) class StudentGrade(models.Model): student = models.ForeignKey(Student, on_delete=models.CASCADE,) period = models.ForeignKey(SchoolPeriod, ...) subjects = models.ForeignKey(Subject, on_delete=models.CASCADE) grade = models.DecimalField(default = 75.00, max_digits=4, decimal_places=2) Views.py def viewgrade(request): current_parent = request.user.parent #gets current logged in parent tempstudent = Student.objects.get(parent = current_parent ) #gets student related to parent(theres no student user level) studentgrade = StudentGrade.objects.filter(student = tempstudent) #filters the grades of the student related to the parent logged in ... context = { ... 'studentgrade': studentgrade, } return render(request, 'Information/viewgrade.html', context) viewgrade.html(template) <table style="width:50%"> <tr> <th>Subject</th> <th>Grade</th> </tr> {% for studentgrade in studentgrade %} <tr> <td>{{ studentgrade.subjects }}</td> <td>{{ studentgrade.grade }}</td> </tr> {% endfor %} </table> What I can do was to print on my template the grades of the STUDENT that is related to the PARENT that is currently logged in. But, I also want to arrange it per grading period(quarter) example: **first grading** Science = 99 Math = 99 **second grading** Science = 70 Match = 70 Thanks for the help! -
JSQuery: How to add and retrieve column attributes?
I'm reading a table from my database using JQuery and I want to create a data type attribute by column in order to perform certain operations by column. So far, I have the following: var table = $('#maintable').DataTable({ "ajax": { "type": "GET", "url": "/cvs/PDFeditor/request/", "data": function(d) { d.placeholder = "asdf"; } }, "columns": [{ "className": 'edit-control', "orderable": false, "data": null, "width": "12px", "defaultContent": '<button type="button" class="btn btn-sm btn-primary"><span class="glyphicon glyphicon-edit"></span></button>' }, { "className": 'delete-control', "orderable": false, "data": null, "width": "12px", "defaultContent": '<button type="button" class="btn btn-sm btn-danger"><span class="glyphicon glyphicon-minus-sign"></span></button>' }, { "data": "investor", "class": 'inv-editable', "data-type": 'investor' }, { "data": "amount", "type": "num-fmt", "class": 'inv-editable', "data-type": 'amount' }, { "data": "code", "class": 'inv-editable', "data-type": 'code' } ], "pageLength": 15, "order": [ [5, "desc"] ] }); My purpose is to store the "data-type" attribute into a variable to update the column in the database prior: $('#maintable tbody').on('dblclick', '.inv-editable', function() { var value = $(this).text(); var data_type = $(this).data("type") if (data_type == 'investor') { var input = "<input type = 'text' class = 'input-data' value ='" + value + "' class='form-control' type="investor">"; } else if (data_type == 'amount') { var input = "<input type = 'text' class = 'input-data' value ='" + value … -
How to get latest position in Django's related model with prefetch_related
I've been trying to get the latest promotion of an employee based on the effective date in the EmployeePosition model which has a many-to-one relation with and Employee model. Based on my research, I've found a way to prefetch the data, but I get multiple results as i can't figure out how to filter our the values from the effective date. Here are the models: class Employee(models.Model): SENIOR = 'Sr' JUNIOR = 'Jr' FIRST = 'I' SECOND = 'II' THIRD = 'III' GENERATIONAL_SUFFIX = [ (SENIOR, 'Senior'), (JUNIOR, 'Junior'), (FIRST, 'First'), (SECOND, 'Second'), (THIRD, 'Third'), ] MALE = 'male' FEMALE = 'female' OTHER = 'other' SEX = [ (MALE, 'Male'), (FEMALE, 'Female'), (OTHER, 'Other'), ] user = models.OneToOneField(User, on_delete=models.CASCADE) phone_regex = RegexValidator(regex=r'^\d{11}$', message="Phone number must be entered in the format: '09151234567'.") phone_number = models.CharField(validators=[phone_regex], max_length=11, blank=True) middle_name = models.CharField(max_length=20, blank=True) sex = models.CharField(max_length=6, choices=SEX, blank=True) suffix = models.CharField(max_length=3, choices=GENERATIONAL_SUFFIX, blank=True) birthday = models.DateField(null=True, blank=True) hire_date = models.DateField(null=True, blank=True) image = models.ImageField(blank=True, default='blank_profile_picture.jpg') slug = models.SlugField(max_length=60, blank=True, null=True) updated = models.DateTimeField(auto_now=True) @property def get_full_name(self): first_name = self.user.first_name middle_name = self.middle_name last_name = self.user.last_name if middle_name is None: full_name = f'{first_name}{" "}{last_name}' return full_name else: full_name = f'{first_name}{" "}{middle_name}{" "}{last_name}' return full_name … -
How does Django know to call the index?
I just started learning Django and I am a bit confused. I'm following the official documentation and this is the code: mysite/urls.py from django.contrib import admin from django.urls import include, path urlpatterns = [ path('polls/', include('polls.urls')), path('admin/', admin.site.urls), ] polls/views.py from django.http import HttpResponse from django.conf import settings from django.shortcuts import render from django.views import View def index(request): return HttpResponse("Hello, world. You're at the polls index.") polls/urls.py from django.urls import path from . import views urlpatterns = [ path('', views.index, name='index'), ] I am mainly confused that if I add more functions in polls/views.py, how will using inclde('polls.urls') know that I wish to call the index function or some other function? Link for the documentation page that I am following: https://docs.djangoproject.com/en/3.2/intro/tutorial01/ -
How to use spreadsheet to show excel file with multiple sheet in django?
I'm working on a project and I need to present data in web page from excel with multiple sheets (multiple documents). Is it possible with this https://datatables.net/ and how? I have tried with this but something is wrong, only get me confused. I wasn't able to run the example that they have been prepared. Any ideas how to present excel document with multiple sheets online with django? Any other ideas are welcome -
Filtering django admin inline - limit the choices list
Given my inline admin: class TestInlineAdmin(admin.TabularInline): model = Test.questions.through extra = 0 and then class QuestionAdmin(admin.ModelAdmin): inlines = [TestInlineAdmin, ] Test model has question field which is ManyToMany. And i am normally able to edit the question list directly from Test model. But i want to be able to choose the Tests from inline admin within QuestionAdmin (so, in reverse). This works. But i need to filter the Test objects in this inline, so the list of choices would show me only Test.objects.filter(applicable=False). I've tried to use get_queryset, but this seems to have no effect on the choice list, it's only filtering the the actual referenced items in inline, but the list of choices for the new item always shows me the complete unfiltered queryset for Test model. Overriding formfield_for_manytomany does not work in inline - it's not executed at all. Would it be possible somehow with formfield_overrides? Or, as i believe the only way would be to customize the inline form? -
why it tell me 'str' object has no attribute 'append'?
`from django.shortcuts import render from django.http import HttpResponse from django import forms Create your views here. class NewTaskForm(forms.Form): task = forms.CharField(label = "New Task") task = ["foo", "bar", "taz"] def index(request): return render(request, "task/index.html", { "task" : task }) def add(request): if request.method == "POST": form = NewTaskForm(request.POST) if form.is_valid(): task = form.cleaned_data["task"] task.append('task') else: return render (request, "task/add.html",{ "form" : form }) return render(request, "task/add.html", { "form" : NewTaskForm() }) ` -
jQuery $.load Not Executing
I am currently using jQuery on my Django site to reload a div once a user clicks a button. $(document).ready(function(){ var post_list = Array.from(document.getElementsByClassName("post_container")) for(var post in post_list){ post_list[post].id = 'post' + post; } var $arrows = $(".arrow"); $arrows.each(function(index){ var data = $(this).data(); var element = $(this); element.on('click', function(event){ if(user_auth){ var currentParentElement = element.parent().parent().parent().get(0); var id = $(currentParentElement).attr('id'); $(id).load(document.URL + ' ' + id); } }) }) }); From the console I can see that currentParentElement and id are pointing to the correct div to reload, but $(id).load() does not seem to be doing anything. In the image linked below, the clicking the arrow buttons should make the green or red number change. The number does not change when the arrow is clicked, but it does change when I reload the entire page. https://i.stack.imgur.com/T26wn.png -
Django test case with invalid URL but giving 200
when run develop server (py manage.py runserver), and user browser with url "localhost:8000//index.html", it is giving 404. but when run test, client.get('//index.html') is 200, and content is same as request to ('/'). when run develop server, using py manage.py shell, then from django.test import Client, directly run is same result. so is it an issue of Client.get() function? or I am using it wrongly? def test_invalid_url2(self): response=self.client.get('//index.html') self.assertEqual(response.status_code, 404) -
Get data non form data from post request in django
I try to submit data on change and change the response from the view based on the data from the POST request. $.ajax({ url: $basicAnalysisChart.data("url"), type: "POST", headers:{ "X-CSRFToken": csrftoken }, dataType: "json", contentType: 'application/json; charset=utf-8', data:{ selector1:$("#Select1").val(), selector2:$("#Select2").val() }, i tried getting to that data in my view with request.POST.get("Select1", "") and request.POST.get("selector1", "") but cant get it working. -
OSError: no library called "cairo" was found // raise OSError(error_message)
raise OSError(error_message) # pragma: no cover OSError: no library called "cairo" was found no library called "libcairo-2" was found cannot load library 'libcairo.so.2': error 0x7e cannot load library 'libcairo.2.dylib': error 0x7e cannot load library 'libcairo-2.dll': error 0x7e for filename in filenames: try: return ffi.dlopen(filename) except OSError as exception: exceptions.append(exception) error_message = '\n'.join( str(exception) for exception in exceptions) raise OSError(error_message) cairo = dlopen( ffi, ('cairo', 'libcairo-2'), ('libcairo.so.2', 'libcairo.2.dylib', 'libcairo-2.dll')) -
Cannot test equality of rest_framework.utils.serializer_helpers.ReturnList while testing
Being new to django rest framework, I tried to make a simple unittest to test a simple search api endpoint. However, when I try to test the equality of the response data and the expected result, assertEqual always returns False when in fact it's the same result. Here is the test class # imports... client = APIClient() User = get_user_model() class SearchTest(APITestCase): def setUp(self): landlord = User.objects.create_user("a@a.com", "testuser", "firstname", "lastname", "password") self.test1_listing = Listing.objects.create(name="test1", place="Pinekarta", adult_guests=2, landlord=landlord) self.test2_listing = Listing.objects.create(name="test2", place="Pinekarta", landlord=landlord) self.test3_listing = Listing.objects.create(name="test3", place="New Bannkarta", landlord=landlord) def test_valid_place(self): response = client.get(reverse('api-search', kwargs={'place': "New Bannkarta"}), format='json') result = DetailedListingSerializer(instance=[self.test3_listing], many=True).data print(type(result)) print(type(response.data)) self.assertEqual(response.data, result) Although result and response.data have the same type and their string representation is the same, for some reason assertEqual always fails. self.assertEqual(response.data, result) AssertionError: [Orde[690 chars]ber_of_comments', 0), ('comments', []), ('avg_rating', None)])] != [Orde[690 chars]ber_of_comments', 0), ('comments', []), ('avg_rating', None)])] -
Django rest framework doesn't commit data to sqlite3 via POST untill server restarted
I just started to study django rest framework and encountered with problem. Here is my code (views.py, urls.py, models.py, serializers.py): #view.py: class AllData(viewsets.ModelViewSet): queryset = Run.objects.all() serializer_class = RunSerializer def get_queryset(self): queryset = self.queryset start_date = self.request.query_params.get('start_date') end_date = self.request.query_params.get('end_date') if start_date is not None and end_date is not None: queryset = queryset.filter(Q(date__gte=start_date) & Q(date__lte=end_date)) return queryset #serializers.py: class RunSerializer(serializers.ModelSerializer): class Meta: model = Run fields = '__all__' #models.py: class Run(models.Model): date = models.DateField() distance = models.DecimalField(max_digits=5, decimal_places=3) time = models.SmallIntegerField() def __str__(self): return str(self.distance) #urls.py: router = DefaultRouter() router.register('all_runs', AllData, basename='all_runs') urlpatterns = [ path('average_data/', AverageData.as_view(), name='average_data'), ] urlpatterns += router.urls So, i started with http://127.0.0.1:8000/all_runs/ and it works. http://127.0.0.1:8000/all_runs/1 or something else - too. (i have added some data already). I see POST, DELETE options, etc. in drf web interface. But...if i add data via POST: i see "POST /all_runs/ HTTP/1.1" 201 9187 - seems like OK. try to http://127.0.0.1:8000/all_runs/ again... and don't see added data! restart server (django by default, sqlite3, etc.) and... see added data! Seems like POST works, but i see data after re-starting server only in web-interface of drf. Same problems with Postman. Please, help. What is wrong in my code or common settings … -
Django: Implementing Group_Concat with optional separator with SQLITE
While Django implementation of Group_Concat on my_sql or mariaDB seem to be well documented, I am not able to make Group_Concat work in Django with optional separator on SQLITE. class GroupConcat(Aggregate): function = 'GROUP_CONCAT' separator = '-' def __init__(self, expression, separator='-', distinct=False, ordering=None, **extra): super(GroupConcat, self).__init__(expression, distinct='DISTINCT ' if distinct else '', ordering=' ORDER BY %s' % ordering if ordering is not None else '', output_field=CharField(), **extra) self.separator = separator It works well with the default separator ',' when using the distinct option def as_sqlite(self, compiler, connection, **extra_context): if self.separator: return super().as_sql( compiler, connection, separator=self.separator, template="%(function)s(%(distinct)s%(expressions)s)", **extra_context ) I figured out that with SQLITE, we can not use both distinct and declare separator, but I don't understand why it does not work without the distinct as in: def as_sqlite(self, compiler, connection, **extra_context): return super().as_sql( compiler, connection, separator=self.separator, template="%(function)s(%(expressions)s,%(separator)s)", **extra_context ) Whatever I try, I always end-up with an error: File "C:\Users\Gil\Gilles\Perso\Maison\Projets perso\Formacube\Formacube test App\Github_FormApp\FormApp\venv\lib\site-packages\django\db\backends\sqlite3\base.py", line 423, in execute return Database.Cursor.execute(self, query, params) django.db.utils.OperationalError: near ")": syntax error -
unable to view my model objects in django using cbv
i am unble to view my model item in django i did everthing right but my model item i not showing my model class Quote(models.Model): todays_Quote = models.CharField(max_length=500, blank=False) by = models.CharField(max_length=100, blank=False) created = models.DateTimeField(auto_now=True) def __str__(self): return self.todays_Quote my views class home(View): def get(self, request): quote = Quote.objects.all() return render(request, 'home.html', {'qoutes':quote}) my html for rendering it <section> <div class="col-11"> <div class="text-center"> {% for Quote in quotes %} <h1>{{ Quote.todays_Quote }} hello</h1> <p style="float: right;">{{ Quote.by }}</p> <p>Todays Date :- <span id="date"></span></p> {% endfor %} </div> </div> </section> any idea what wrong in that & yes i did the migration -
Django save-Making Two Orders on single click
i have created my ecommerce platform. Whenever I click the order-now-buttons, it makes two orders in my backend, I don't see where the error comes from. But it outputs a complete and incomplete, order.Here is my view.py makeorder function def processOrder(request): transaction_id = datetime.datetime.now().timestamp() data = json.loads(request.body) print(data) if request.user.is_authenticated: customer = request.user order, created = Order.objects.get_or_create( customer=customer, complete=False) total = order.get_cart_totals order.transaction_id = transaction_id if total == order.get_cart_totals: order.complete = True print("Total equals") order.save() if order.shipping == True: print("Wrong") ShippingAddress.objects.create( customer=customer, order=order, firstname=data['shipping']['firstname'], lastname=data['shipping']['lastname'], address=data['shipping']['address'], city=data['shipping']['city'], zipcode=data['shipping']['zipcode'] ) else: print("User doesn't exist") print('Data:', request.body) return JsonResponse('Payment Submitted', safe=False) I know the error is inside my function, but i cant figure it out Thanks for your help in advance -
How to add pagination : super()
I am trying to add pagination using super().list() method in modelviewset def list(self, request, **kwargs): print('list') try: if 'learner_id' in kwargs: learner_id = self.kwargs.get('learner_id') else: learner_id = request.learner.id details = RecentlyViewedVideos.objects.filter(learner_id=learner_id) response_data = super().list(details, kwargs) in output, it displays all the documents in the table, but I only need those details in the "details", give me a way to get the exact output. -
Programming Error with the Alias of my SQL Query
I am getting the below error for the below SQL query, I am pretty sure it has something to do with the Alias given to PostGl. I just don't know how to correct it. Query: all = 'SELECT Master_Sub_Account , cAccountTypeDescription , Debit , Credit FROM [Kyle].[dbo].[PostGL] AS genLedger'\ 'Inner JOIN [Kyle].[dbo].[Accounts] '\ 'on Accounts.AccountLink = PostGL.AccountLink '\ 'Inner JOIN [Kyle].[dbo].[_etblGLAccountTypes] as AccountTypes '\ 'on Accounts.iAccountType = AccountTypes.idGLAccountType'\ 'WHERE genLedger.AccountLink <> 161 OR 162 OR 163 OR 164 OR 165 OR 166 OR 167 OR 168 OR 122 ' Error : ProgrammingError at /Kyletrb ('42000', "[42000] [Microsoft][ODBC SQL Server Driver][SQL Server]Incorrect syntax near 'genLedger'. (102) (SQLExecDirectW)") -
how to show api end in swagger ui that has auth required after authentication django
is there any way to show an auth-required api endpoint in the swagger UI after successfully authentication of the user? -
Django Python With Gspread: 'choices' must be an iterable containing (actual value, human readable name) tuples
I am trying to do something that I have never seen done before with django, I am trying to make a model field(path_choices) that shows all of the unique path_names from my google sheet in a choice box so that the user can select one of them. However when I tried to make my choices CharField I am getting the error: ERRORS: dashboard.Robot.path_choices: (fields.E005) 'choices' must be an iterable containing (actual value, human readable name) tuples. Right now the google sheet that I am trying to pull from with gspread only has two path-names, so if anybody has any idea on what is causing this problem or what I can do better with this, the help would be appreciated! My Code: from django.db import models import gspread from oauth2client.service_account import ServiceAccountCredentials class Robot(models.Model): name = models.CharField(max_length=100) status_choices = [('driving', 'driving'), ('waiting', 'waiting'), ('stuck', 'stuck')] status = models.CharField(choices=status_choices, max_length=7, default='waiting') scope = ["REDACTED",'REDACTED',"REDACTED","REDACTED"] creds = ServiceAccountCredentials.from_json_keyfile_name("dashboard/Files/creds.json", scope) client = gspread.authorize(creds) sheet = client.open("tutorial").sheet1 path_name_fetch = sheet.col_values(1) path_names = [] temp_list = [] path_options = [] for i in path_name_fetch: if i not in path_names: path_names.append(i) for path_name_options in path_names: temp_list.append(f'{path_name_options}') temp_list.append(f'{path_name_options}') path_options.append(tuple(temp_list)) path_choices = models.CharField(choices=path_options, max_length=20, default='Default') -
Errno 2 No such file or directory in django
When I try to run server in django writing python manage.py runserver , python gives an error which is C:\Users\Alim Írnek\AppData\Local\Programs\Python\Python39\python.exe: can't open file 'C:\Users\Alim ├ûrnek\PycharmProjects\mysite\manage.py': [Errno 2] No such file or directory Is it because of spaces in my username or something else? -
ModelChoiceField in django admin gives 'Select a valid choice. That choice is not one of the available choices.' error
Hej! I want a field in my django admin area where the user can select from given choices in the database. For example get a list of countries and choose one. But I will always get the ' Select a valid choice. That choice is not one of the available choices.' error when you try to save the new instance. #models.py class PlaceSection(models.Model): code = models.CharField(max_length=1) def code_str(self): return self.code # admin.py class InstiForm(forms.ModelForm): place_sections = forms.ModelChoiceField( PlaceSection.objects.values(), widget=Select2Widget, ) class Meta: model = Something fields = [ "place_section"] class InstiAdmin(admin.ModelAdmin): form = InstiForm save_on_top = True def save_model(self, request, obj, form, change): fieldsets = [ ( ("General"), {"fields": [ "place_sections" ] } ) ] I do get the right choices in the admin dropdown but when I select one and save the error occurs. Does anyone has an idea how to fix this (in the admin) found only similar problems without the admin part and no solution worked for me. Help is really appreciated! :) -
Can't Submit ModelForm using CBVs
I am trying to use ModelForms and CBVs to handle them, but I am facing trouble especially while submitting my form. Here's my code. forms.py from django import forms from .models import Volunteer class NewVolunteerForm(forms.ModelForm): class Meta: model = Volunteer fields = '__all__' views.py from django.http.response import HttpResponse from django.views.generic.edit import CreateView from .forms import NewVolunteerForm class NewVolunteerView(CreateView): template_name = 'website/join.html' form_class = NewVolunteerForm def form_valid(self, form): print('Submitting') form.save() return HttpResponse('DONE') join.html {% extends 'website/_base.html' %} {% block title %}Join Us{% endblock title %} {% block content %} <form method="POST"> {% csrf_token %} {{ form.as_p }} <input type="submit"> </form> {% endblock content %} The form is getting displayed correctly with no issues at all, but when I fill it in and press the submit button it simply re-rendered the form and doesn't submit it at all. -
APM Django - how to correlate container logs from Filebeat with data from ElasticAPM in Kibana?
Kibana version: 7.14.0 Elasticsearch version: 7.14.0 APM Server version: 7.14.0 Filebeat version: 7.14.0 APM Agent language and version: Python Django - elastic-apm 6.3.3 Description: The APM server and Python agents are working as expected just like the Filebeat. They're collecting logs and metrics, but I don't know how to correlate them in Kibana: Live streaming from Logs section is working and I can filter apm instances with container.id. 1. APM, Elasticsearch, Kibana configs docker-compose.yml: version: '3.3' services: elasticsearch: image: docker.elastic.co/elasticsearch/elasticsearch:7.14.0 hostname: elasticsearch environment: - ES_JAVA_OPTS=-Xms512m -Xmx512m - ELASTIC_PASSWORD=password ports: - 192.168.100.100:9200:9200 volumes: - ./data:/usr/share/elasticsearch/data - ./elasticsearch.yml:/usr/share/elasticsearch/config/elasticsearch.yml networks: - elk kibana: image: docker.elastic.co/kibana/kibana:7.14.0 hostname: kibana restart: always ports: - 192.168.100.100:5601:5601 volumes: - ./kibana.yml:/usr/share/kibana/config/kibana.yml:ro networks: - elk apm: image: docker.elastic.co/apm/apm-server:7.14.0 hostname: apm command: --strict.perms=false depends_on: - elasticsearch cap_add: ["CHOWN", "DAC_OVERRIDE", "SETGID", "SETUID"] cap_drop: ["ALL"] volumes: - ./apm-server.yml:/usr/share/apm-server/apm-server.yml ports: - 192.168.100.100:8200:8200 networks: - elk networks: elk: driver: bridge apm-server.yml: apm-server: host: "apm:8200" secret_token: token rum: enabled: true kibana: enabled: true host: "kibana:5601" protocol: "http" username: "elastic" password: "password" setup.template.enabled: true setup.template.name: "apm-%{[observer.version]}" setup.template.pattern: "apm-%{[observer.version]}-*" setup.template.fields: "${path.config}/fields.yml" setup.template.overwrite: false setup.template.settings: index: number_of_shards: 1 number_of_replicas: 0 codec: best_compression number_of_routing_shards: 30 mapping.total_fields.limit: 2000 output.elasticsearch: hosts: ["elasticsearch:9200"] username: elastic password: password index: "apm-%{[observer.version]}-%{+yyyy.MM.dd}" indices: - index: "apm-%{[observer.version]}-sourcemap" … -
Django / postgres - maintain a table of counters
I want to maintain a running counter per user, that will be given to the user items. User table will have a last_item_num column class Item: name = models.CharField(max_length=100) user = models.ForeignKey(User, on_delete=models.CASCADE) item_num = models.IntegerField() # should be populated from the user table The question, when the user is creating an item, what is the best way to increment the counter and to copy the new counter to the newly created item, atomically? Technically I atomically need to: Increment and get the counter of the user Create a new Item with the value for item_num What is the django / postgres way to do that?