Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Django Rest Framework: Serializing a model and grouping by a foreign key for other data
I have the following three models: class Package(models.Model): name = models.CharField() class Part(models.Model): name = models.CharField() sku = models.IntegerField() class Member(models.Model): name = models.CharField() class MemberPurchase(models.Model): member = models.ForeignKey(Member) package = model.ForeignKey(Package) part = models.ForeignKey(Part) purchase_date = models.DateField() I want to serialize MemberPurchase model for an API so that I can have all the information I need as below: { "name": "John Doe", "id": 123, "purchases": [ { "name": "Package Silver", "parts": [ { "name": "Part Silver 1", "sku": "12345", }, { "name": "Part Silver 2", "sku": "145678", } ] }, { "name": "Package Gold", "parts": [ { "name": "Part Gold 1", "sku": "1010101", } ] } ] } I am not exactly sure how to build the serializer to give me the result above. I can write a serializer that will serialize a queryset from MemberPurchase but that will have a lot of repeated data. I am guessing this needs multiple serializers: class MemberSerializer(serializers.ModelSerilaizer): purchases = MemberPurchaseSerializer(source='memberpurchase_set', many=True) class Meta: model = Member fields = ['name', 'id'] class MemberPurchaseSerializer(serializers.Serializer): name = serializers.SerializerMethodField('get_package_name') parts = PackagePartSerializer(many=True) def get_pacakage_name(self, instance): return instance.package.name class PackagePartSerializer(serializers.Serializer): name = serializers.SerializerMethodField('get_part_name') sku = serializers.SerializerMethodField('get_part_sku') def get_part_name(self, instance): return instance.part.name def get_part_sku(self, instance): return instance.part.sku I … -
Django,python pip install mysqlclient not work
I am working with Django and trying to install mysqlclient but haven't had any success in doing so. I keep getting an error when I run python manage.py makemigrations. Here's the error I'm seeing: Command "/usr/bin/python -u -c "import setuptools, tokenize;__file__='/private/var/folders/w8/tfy1yzhd74502cs1_2thbkl00000gn/T/pip-build-yYQxRD/mysqlclient/setup.py';f=getattr(tokenize, 'open', open)(file);code=f.read().replace('\r\n', '\n');f.close();exec(compile(code, file, 'exec'))" install --record /var/folders/w8/tfy1yzhd74502cs1_2thbkl00000gn/T/pip-DGru8k-record/install-record.txt --single-version-externally-managed --compile" failed with error code 1 in /private/var/folders/w8/tfy1yzhd74502cs1_2thbkl00000gn/T/pip-build-yYQxRD/mysqlclient/ -
Send data from Django to java script(in Chrome extension)
I have developed a chrome extension and I am inserting json data in mysql through django service. I want to send data from django to java script which is in chrome extension. popup.js: document.addEventListener('DOMContentLoaded', documentEvents, false); function myAction(fname,femail,fpassword) { var str = "name="+ fname.value + "&email=" + femail.value + "&password=" + fpassword.value; var xmlhttp = new XMLHttpRequest(); alert(str); var theUrl = "http://127.0.0.1:8000/polls/?"; xmlhttp.open("POST", theUrl, true); xmlhttp.onreadystatechange = function() { //alert(xmlhttp.readyState + " " + xmlhttp.status); if (xmlhttp.readyState == 4){ alert("entered"); } else{ alert("not entered"); } }; xmlhttp.setRequestHeader("Content-Type","application/x-www-form-urlencoded;charset=UTF-8"); xmlhttp.send(str); } function loadDoc() { var xhttp = new XMLHttpRequest(); var theUrl = "http://127.0.0.1:8000/polls/?"; xhttp.onreadystatechange = function() { if (this.readyState == 4 && this.status == 200) { document.getElementById("output").innerHTML = this.responseText; } }; xhttp.open("GET",theUrl,true); xhttp.send(); } function documentEvents() { var submitButton = document.getElementById('submit') submitButton.addEventListener('click', function(event) { var formId = document.getElementById('test'); var name = document.getElementById('name'); var email = document.getElementById('email'); var password = document.getElementById('password'); myAction(name,email,password); }); } views.py : from django.http import HttpResponse from django.http import HttpResponseRedirect, HttpResponse from .models import UserProfile from django.views.decorators.csrf import csrf_exempt @csrf_exempt def index(request): req = request.method t = request.GET print(req) name = request.POST.get('name') email = request.POST.get('email') password = request.POST.get('password') savedata = UserProfile(name=name,email=email,password=password) savedata.save() print('Hello %s %s %s' % (name, email, … -
Django timezone same day diff is not 0
test function from django.utils import timezone def date_diff_now(date): print(date) print(timezone.now()) print(date - timezone.now()) print((date - timezone.now()).days) Result 2018-02-07 17:46:36.442314+00:00 2018-02-07 17:47:32.084900+00:00 -1 day, 23:59:04.357374 -1 Why the difference between 2 datetime on the same day does not return 0 ? -
Load Unknown Number of Charts with Django Chartit
I have a script that generates multiple charts that are passed to the datachart variable in my chart.html. I'd like to have each chart in it's own <div>. It is easy enough to iterate through datachart and create the amount of <div> required, but the problem I'm facing is that the number of charts in datachart varies. In the example below there are 12 charts generated and I have to manually pass datachart|loadchart:"p1,p2,...". Is there a way to iterate though the charts or a way to construct the datachart|loadchart:"p1,p2,..." dynamically based on the length of the datachart array? Snippet from chart.html Template <head> <!-- code to include the highcharts and jQuery libraries goes here --> <!-- load_charts filter takes a comma-separated list of id's where --> <!-- the charts need to be rendered to --> <script src="http://ajax.googleapis.com/ajax/libs/jquery/1.7.1/jquery.min.js" type="text/javascript"></script> <script src="http://code.highcharts.com/highcharts.js" type="text/javascript"></script> <script src="/highcharts.js" type="text/javascript"></script> {% load chartit %} {{ datachart|load_charts:"p1,p2,p3,p4,p5,p6,p7,p8,p9,p10,p11,p12" }} </head> <center> {% for c in datachart %} <div id='p{{forloop.counter}}' style="height: 40%; width: 80%"> </div> {% endfor %} </center> -
Django - list items based on a foreign key
I am a new to python, Django (and programming in general). I have spend over 10 hours on this problem, but I seem to be missing something. I have two models in Django - articles and categories, and I am using ListView and DetailsView in my views.py file. On the articles_details page, I am trying to list all the articles that are in the same category as the current article. I have tried a million things, but to no avail. I am thinking that I could define a function using __exact to filter the categories database, based on the current value of articles.category (the category of the current article). I am not sure how to do so, though, and how to call such a function in my template. Could someone please assist? Thank you, in advance. P.S.: Not sure if part of the problem is using ListView and DetailsView. Here is my code: Views.py from django.shortcuts import render from web import models from web.models import Main, Series_rh, Articles_rh from django.views.generic import View,TemplateView,ListView,DetailView class IndexView(TemplateView): template_name = 'web/index.html' class CategoriesView(ListView): model = models.Series_rh template_name = 'web/series.html' context_object_name = 'Categories_rh_list' class CategoriesView(DetailView): model = models.Series_rh template_name = 'web/series.html' context_object_name = 'Categories_rh_details' class … -
How to dynamically specify the name of a static file?
I have a report.html template in which I need to dynamically change the name of images. I've done a lot of research and trial and error. But I just can't get the URLs for the images to be correct. The images are in /templates/users/reports/rptemplate/images. After researching static images, I also copied the images to: /static/images. Here's my latest html: <?xml version="1.0" encoding="UTF-8"?> {% load staticfiles %} <html> ... <img alt="" src="static/images/{{img_vision}}"> ... This is my report view: class UserReportView(LoginRequiredMixin, TemplateView): model = User template_name = 'users/reports/rptemplate/report.html' def get_context_data(self, **kwargs): #context = super(DisplayTaskView, self).get_context_data(kwargs) #TODO: retrieve the actual data context = {'sid': 519893, 'church_name': 'Lakeview Bible', 'report_date': '5 Feb 2018', 'responses': 57, 'img_vision': 'image1.png', 'img_leadership': 'image1.png', 'img_mobilization': 'image1.png', 'img_stewardship': 'image1.png', 'img_context': 'image1.png', 'img_evangelism': 'image1.png', 'img_discipleship': 'image1.png', 'img_service': 'image1.png', 'img_fellowship': 'image1.png', 'img_worship': 'image1.png', 'img_category': 'image1.png', 'img_radar': 'image1.png' } return context And this is my user/url.py: from django.conf.urls import url from django.views.generic import TemplateView from django.contrib.staticfiles.urls import staticfiles_urlpatterns from . import views urlpatterns = [ url( regex=r'^$', view=views.UserListView.as_view(), name='list' ), url( regex=r'^~redirect/$', view=views.UserRedirectView.as_view(), name='redirect' ), url( regex=r'^(?P<username>[\w.@+-]+)/$', view=views.UserDetailView.as_view(), name='detail' ), url( regex=r'^~update/$', view=views.UserUpdateView.as_view(), name='update' ), url( regex=r'^reports/rptemplate/$', view=views.UserReportView.as_view(), name='report' ), ] urlpatterns += staticfiles_urlpatterns() So where is my mistake? How do I dynamically … -
Django: NoReverseMatch in html
I am always getting this error in detail.html Reverse for 'vote' with arguments '('',)' not found. 1 pattern(s) tried: ['polls\\/(?P<question_id>[0-9]+)\\/$'] the detail.html is <h1>{{ question.question_text }}</h1> {% if error_message %}<p><strong>{{ error_message }}</strong></p>{% endif %} <form action="{% url 'detail' question.id%} " method="post"> {% csrf_token %} {% for choice in question.choice_set.all %} <input type="radio" name="choice" id="choice{{ forloop.counter }}" value="{{ choice.id }}" /> <label for="choice{{ forloop.counter }}">{{ choice.choice_text }}</label><br /> {% endfor %} <input type="submit" value="Vote" /> </form> and my polls.url.py is urlpatterns = [ path('', views.index, name='index'), path('<int:question_id>/', views.detail, name='detail'), path('<int:question_id>/results/', views.results, name='results'), path('<int:question_id>/vote/', views.vote, name='vote'), ] The issue is that I have a similar code <a href = "{% url 'vote' question.id %}"> in index.html, it will work. The project directory is here enter image description here -
Celery task blocked in Django view with a AWS SQS broker
I am trying to run a celery task in a Django view using my_task.delay(). However, the task is never executed and the code is blocked on that line and the view never renders. I am using AWS SQS as a broker with an IAM user with full access to SQS. What am I doing wrong? Running celery and Django I am running celery like this: celery -A app worker -l info And I am starting my Django server locally in another terminal using: python manage.py runserver The celery command outputs: -------------- celery@LAPTOP-02019EM6 v4.1.0 (latentcall) ---- **** ----- --- * *** * -- Windows-10-10.0.16299 2018-02-07 13:48:18 -- * - **** --- - ** ---------- [config] - ** ---------- .> app: app:0x6372c18 - ** ---------- .> transport: sqs://**redacted**:**@localhost// - ** ---------- .> results: disabled:// - *** --- * --- .> concurrency: 4 (prefork) -- ******* ---- .> task events: OFF --- ***** ----- -------------- [queues] .> my-queue exchange=my-queue(direct) key=my-queue [tasks] . app.celery.debug_task . counter.tasks.my_task [2018-02-07 13:48:19,262: INFO/MainProcess] Starting new HTTPS connection (1): sa-east-1.queue.amazonaws.com [2018-02-07 13:48:19,868: INFO/SpawnPoolWorker-1] child process 20196 calling self.run() [2018-02-07 13:48:19,918: INFO/SpawnPoolWorker-4] child process 19984 calling self.run() [2018-02-07 13:48:19,947: INFO/SpawnPoolWorker-3] child process 16024 calling self.run() [2018-02-07 13:48:20,004: INFO/SpawnPoolWorker-2] child process … -
Why won't save_model override allow HttpResponseRedirect()?
I'm trying to add an intermediate confirmation page while saving a model that is conditional based on variables of the object being saved. ex, if object status is draft and the change will be to live, trigger confirmation. Else any other status, just save with no intermediate confirmation. I added admin.ModelAdmin to my models admin class: class SurveyAdmin(SimpleHistoryAdmin, admin.ModelAdmin): And I'm trying to override save_model to test conditions and add confirmation if need: @csrf_protect_m @transaction.atomic def save_model(self, request, object_id=None, form_url='', extra_context=None): survey = Survey.objects.get(pk=object_id.id) def response_add(self, request, obj, post_url_continue=None): if request.method == 'POST' and 'confirm' in request.POST: # do the thing return HttpResponseRedirect(reverse('admin:survey_change', args=(survey.pk,))) else: context = { 'title': _('Make live'), 'is_popup': False, 'opts': self.model._meta, 'app_label': self.model._meta.app_label, 'object': survey, } return TemplateResponse( request, 'admin/survey/make_live_confirmation.html', context) The problem: It seems save_model ignores my HttpResponseRedirect AND my TemplateResponse returns. I have this exact process working on other methods inside admin.py, but they are not overrides, they are custom definitions. Any ideas why save_model won't let me take control of the returns? -
Difference between reverse() and reverse_lazy() in Django
I understand that we can use reverse() in FBV and reverse_lazy() in CBV. I understand that we have to use reverse_lazy() in CBV as the urls are not loaded when the file is imported. Ref: Reverse_lazy and URL Loading? What I don't understand is - How are urls are loaded when we call reverse from the FBV? As when we import the views at the top of the urls.py in django app, urlpatterns list is yet to be evaluated. How does reverse() for FBV work but not for CBV? Does my question makes sense?? :P Thanks in advance. Regards. -
Uploading files POST urls raise 404 when deploy
I'm deploying a django app on a host with apache and cPanel. I think I did all the steps that django needs to deploy. Everything works fine except some posts urls. When I'm sending a form via post, and one of its fields is a File that will be uploaded to a directory, the server responses me 404, even from the admin add urls. Some info: Python 3.5, Django 1.11.9 Error: 404 Not Found When: sending any post form containing a Choose File field, even if the file isn't mandatory. The forms without files in their fields work fine. In production everything works perfect. I have a symlink in the public_html folder to my media and static folders and yes, I wrote multipart in the form and I guess admin app did it to. This is my code: urls.py urlpatterns = i18n_patterns( url(r'^admin/', admin.site.urls), url(r'^i18n/', include('django.conf.urls.i18n')), url(r'^', include('myapp.urls')), prefix_default_language=False) settings.py MEDIA_ROOT = os.path.join(BASE_DIR, 'media') MEDIA_URL = '/media/' This is my first time hosting a website, so, sorry if I'm asking a dummy question, but I couldn't find any solution, even here. Also, sorry for my English. Thanks for the future answers -
Django: best practice to minify HTML to improve page speed loading
Its about results in https://developers.google.com/speed/pagespeed/insights/ Probably it is pretty much to just globally wrap whole HTML with {% spaceless %} tag? Or it is not safe and there are some better ways? -
How to import another table's row count?
I'm using Django Rest framework. (DB = MySQL) I want to import another table's row count. [article table] - articleNo(Primary key) - userkey - content - likeCount [like table] - articleNo(FK to article) - userkey For example, articleNo == 1, counting number of row in a like table and storing article table's likeCount column. All I want to know is about "like table", particularly suitable for a certian condition that counts values in table and list it to "article table" Can it be implemented with Rest framework? Thanks. p.s. As I'm a non-native English speaker, it would be very appreciated if you use plain language to help my understanding. -
How to update a Django model with a large CSV file (54 fields, ~5000 rows)?
I have a model describing data center items (e.g. Racks, PDUs, patch panels, switches, servers, blades, ...). The data is exported regularly as CSV (once a month) and the export currently has close to 5000 lines and 54 fields per row. For our Django App, roughly 80% of the rows are relevant: their equipment type must be in a pre-defined type list and the item must have a barcode (internal asset number) associated with it. The rest of the lines is skipped. The model (see below) captures all of the available fields, even if they're not used. The reason for that is that the app, once it becomes productive, will have several models related to each other but fed from different data sources. Until now all of them are completely unrelated, the goal is to detect lint in the various databases and, over time, clean the data. Maybe in the future some data sources may even be declared authoritative so their data can be used to automatically generate updates for secondary databases whenever a primary representation changes. In the app we currently upload the CSV file via form, here is a sample of the CSV (data anonymized): "Name";"Serial Number";"Barcode";"Installation Date";"Model … -
how to query google about position of webpage on keyword in django
I'm half way through creating my application. Now I don't know how to do it to the end. I want to query Google on what position the page is, on the keyword. From what to start here and what to do not to get an IP ban and not to display the recaptcha? -
django-scheduler how to relate model to an event?
I have the following models: class UserProfile(models.Model): user = models.OneToOneField(User, related_name='user', on_delete=models.CASCADE, primary_key=True) title = models.CharField(max_length=100, blank=True) address = models.CharField('Dirección', max_length=220, blank=True) colonia = models.CharField(max_length=220, blank=True) estado = models.CharField(max_length=220, blank=True) municipio = models.CharField(max_length=220, blank=True) cp = models.IntegerField('C.P.', max_length=6, blank=True, default=0) telefono = models.IntegerField('Tel.', max_length=13, blank=True) def user_directory_path(instance, filename): # file will be uploaded to MEDIA_ROOT/user_<id>/<filename> return 'user_{0}/{1}'.format(instance.user.username, filename) upload = models.FileField('Archivo .ZIP con las xml dentro', upload_to=user_directory_path, null=True, blank=True, ) def set_avatar(self): _avatar = self.avatar if not _avatar: self.avatar = "static/logos/default.png" @receiver(post_save, sender=user) def create_user_profile(sender, instance, created, **kwargs): if created: UserProfile.objects.create(user=instance) @receiver(post_save, sender=user) def save_user_profile(sender, instance, **kwargs): instance.UserProfile.save() def __str__(self): return self.user.username class Client(models.Model): pattern = models.ForeignKey('auth.User', on_delete=models.PROTECT) namec = models.CharField(max_length=200) description = models.TextField() address = models.CharField('Dirección', max_length=220, blank=True) colonia = models.CharField(max_length=220, blank=True) estado = models.CharField(max_length=220, blank=True) municipio = models.CharField(max_length=220, blank=True) cp = models.IntegerField('C.P.', max_length=6, blank=True, default=0) telefono = models.IntegerField('Tel.', max_length=13, blank=True) created_date = models.DateTimeField( default=timezone.now) published_date = models.DateTimeField( blank=True, null=True) def publish(self): self.published_date = timezone.now() self.save() def __str__(self): return self.namec Each user-UserProfile can create appointments in its own calendar, in each event in addition to the description to be able to attach files and a field to select a client of the client model. How can I achieve this? … -
try except doesn't work fine
I'm working on django and this is the code: def checkRights( self ): resources_rights = Resources_rights.objects.filter( self.checkRead(), self.checkWrite(), self.checkExecute(), group_id__in = self.groups ).distinct().order_by( "resource_id" ) return resources_rights def checkRead( self ): if self.query_dict[ 'read' ] is None: read_statement = Q( ) else: try: read_statement = Q( read = self.query_dict[ 'read' ] ) except Exception as e: read_statement = Q( ) self.errors = e self.warnings = "Resources have not been filtered" return read_statement I passe it self.query_dict[ 'read' ] as true so it rightly returns the ValidationError, because read is boolean and it must be True or False. Right for that, I've put a try except, the problem is that it never goes in the except, despite the try returns an error. What am I doing wrong? -
running inspectdb on a legacy msql database
I have successfully connected to a database from sql-server and my server starts perfectly, i tried to run inspectdb to get the models generated for me but these errors. Unable to inspect table 'AccountManagers' The error was: __new__() missing 1 required positional argument: 'default' I want to be able to generate models from this database -
Can't display different forms for different user types
I have 2 user types, teacher and student. I have built the view to be able to edit a student profile. But I also needed a different one for teacher. I didn't want 2 views, because that would be pointless. Now, for teacher it works as intended, but for some reason for teacher, the same form as for the student is displayed... a teacher has different attributes so it has a different form I need to show. class TeacherEditForm(forms.ModelForm): email = forms.EmailField(required=False) name = forms.CharField(max_length=30, required=False) surname = forms.CharField(max_length=50, required=False) academic_title = forms.CharField(max_length=30, required=False) bio = forms.Textarea() website = forms.URLField(required=False) photo = forms.ImageField(required=False) phone = forms.CharField(required=False) class StudentEditForm(forms.ModelForm): email = forms.EmailField(required=False) name = forms.CharField(max_length=30) surname = forms.CharField(max_length=50) photo = forms.ImageField(required=False) phone = forms.CharField(max_length=15, required=False) @login_required def profile_edit(request): user = request.user try: student = Student.objects.get(user=user) s = True except ValueError: teacher = Teacher.objects.get(user=user) if not s: if request.method != 'POST': form = TeacherEditForm(instance=teacher) else: form = TeacherEditForm(request.POST, instance=teacher) if form.is_valid(): user.email = form.cleaned_data['email'] user.save() form.save() return redirect('index') elif s: if request.method != 'POST': form = StudentEditForm(instance=student) else: form = StudentEditForm(request.POST, instance=student) if form.is_valid(): user.email = form.cleaned_data['email'] user.save() form.save() return redirect('index') context = { "form": form, } return render(request, "registration/profile_edit.html", context) -
Error deploying Django app on heroku
I'm kinda new to Django as well as heroku and have encountered a problem while publishing my app to heroku. The error I get is this: remote: Compressing source files... done. remote: Building source: remote: remote: -----> App not compatible with buildpack: https://codon-buildpacks.s3.amazonaws.com/buildpacks/heroku/python.tgz remote: More info: https://devcenter.heroku.com/articles/buildpacks#detection-failure remote: remote: ! Push failed remote: Verifying deploy... remote: remote: ! Push rejected to shielded-lake-72150. remote: To https://git.heroku.com/shielded-lake-72150.git ! [remote rejected] master -> master (pre-receive hook declined) error: failed to push some refs to 'https://git.heroku.com/shielded-lake-72150.git' I tried a lot of solutions given online, but nothing worked. I even set the buildpack to python. But it still shows me the same error. Any help appreciated, thanks. -
How to send message from user in telegram in web application
I am trying to create web application using python3.x and django2.x I am create view that authorize user in telegram, but when i get secure code and send it to function sign_in i recieve an error "You also need to provide a phone_code_hash." I don't know what is the phone_code_hash, and where I can get it. views.py:: def authorize_user(request): if request.method == 'POST': secure_code = request.POST.get('secure_code') phone = request.POST.get('phone') api_id = request.POST.get('api_id') api_hash = request.POST.get('api_hash') client = TelegramClient('spamer', api_id, api_hash) if secure_code: try: client.sign_in(phone, secure_code) except Exception as e: print(e) return JsonResponse({'status': 0, 'error': 'error'}) return JsonResponse({'status': 2}) client.connect() client.send_code_request(phone) return JsonResponse({'status': 1}) return render(request, 'spamer/add_user.html') I use telethon library for API interaction. Maybe someone from you know how to authorize user and send message from him many times in different days. Maybe you suggest more suitable library or to use API requests with urllib. I only want to authorize user and use him to send many messages to another people, is it real? -
posible to store an excel file into a html element? [duplicate]
This question already has an answer here: How to serve static files in Flask 12 answers Python - Write to Excel Spreadsheet 8 answers Create and download a CSV file from a Flask view 1 answer we are making a website using flask where we display a table with information, and the user want to be able to export that to excel, we can do that with javascript but some of the charts that we created cant be transfer, so we thought doing the excel file in the back end and pass it to a button, that way the user can have the table in the browser and click a button and that will already have in it the excel file. how can I store/pass the excel file into a html element button? -
how to post callback to Background [duplicate]
This question already has an answer here: How can I upload files asynchronously? 25 answers This is an easy Html. <!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>Title</title> </head> <body> <form method="POST" action="https://sm.ms/api/upload" enctype="multipart/form-data"> <input name="smfile" type="file"> <input type="submit" name="upload"> </form> </body> </html> When i post an image to the server(third party) , the server(third party) returned the json and changed my web.. { code: "success", data: { width: 440, height: 440, filename: "timg.jpg", storename: "5a7b1807506b2.jpg", size: 11941, path: "/2018/02/07/5a7b1807506b2.jpg", hash: "m8FqIYBGWL1HDrT", timestamp: 1518016519, ip: "111.29.138.47", url: "https://i.loli.net/2018/02/07/5a7b1807506b2.jpg", delete: "https://sm.ms/delete/m8FqIYBGWL1HDrT" } } my question is how to POST this json to my background and how to don't change my web .. -
Django: why does NOT this give a syntax error? [duplicate]
This question already has an answer here: Why does python allow spaces between an object and the method name after the “.” 3 answers UPDATE This question has been marked as duplicate. The linked question answers my question partially. I have two questions and it answers one. ORIGINAL I am new to Django. I just by mistake put a space between this query and realized that it still works when I would expect it to give an error. ClinicDoctorDayShift.objects.filter(clinic_doctor__doctor_id = doctor_id).all() .order_by('day_shift__time') There is a space between all() and .order_by. Why doesn't it raise an error? the order_by still works. WHY? And one more thing. what is difference between ClinicDoctorDayShift.objects.filter(clinic_doctor__doctor_id = doctor_id) and ClinicDoctorDayShift.objects.filter(clinic_doctor__doctor_id = doctor_id).all() One is without all(). They work same way, apparently, when I use them in my template. Thank you