Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
get post by name of user or by id
i have this model class Post(models.Model): auth = models.ForeignKey(settings.AUTH_USER_MODEL,default=1) title = models.CharField(max_length=120) DESCSPECSOFT = ( (u'Null','Null'), (u'Phone',u'Phone'), (u'Car',u'Car'), (u'Laptop',u'Laptop'), (u'jops',u'Jops'), (u'Electronic',u'Electronic'), (u'Clothes',u'Clothes'), (u'Makeup',u'Makeup'), (u'Furnishings',u'Furnishings'), (u'books',u'books'), (u'sports',u'sports'), (u'Property',u'Property'), (u'Other',u'Other'), ) City = ( (u'Null','Null'), (u'Kosti',u'Kosti'), (u'Khartoum',u'Khartoum'), (u'Rabbik',u'Rabbik'), (u'Duwaim',u'Duwaim'), (u'Sinnar',u'Sinnar'), (u'Bahri',u'Bahri'), (u'Omdurman',u'Omdurman'), (u'Sawakin',u'Sawakin'), (u'Port Sudan',u'Port Sudan'), (u'Kasala',u'Kasala'), (u'Madani',u'Madani'), (u'Alabid',u'Alabid'), ) Case = ( (u'Null','Null'), (u'New',u'New'), (u'Old',u'Old'), (u'Second Hand',u'Second Hand'), (u'Other',u'Other'), ) Type = models.CharField(choices=DESCSPECSOFT, default='Null',blank = False,null = False,max_length=120) company = models.CharField(max_length=120) dis = models.TextField(default="in here you w,ll write all the discribtion about your product") image = models.ImageField(null=True,blank=True,width_field="width_field", height_field="height_field") width_field = models.IntegerField(default=0) height_field = models.IntegerField(default=0) case = models.CharField(choices=Case, default=99,blank = False,null = False,max_length=120) price = models.BigIntegerField(default=0) city = models.CharField(choices=City, default='Null',blank = False,null = False,max_length=120) address = models.CharField(max_length=120) draft = models.BooleanField(default=False) #pup = models.DateField(auto_now=False,auto_now_add=False ,null=False) date = models.DateTimeField(auto_now=True ,auto_now_add=False) puplis = models.DateTimeField(auto_now=False ,auto_now_add=True) objects = PostManager() def __str__(self): return self.title def __unicode__(self): return self.title any user can add a post but i want the user name show in the data base means the user how add the post because every post show the admin name not the user how add the post can someone show me haw can i fix this ??? sorry my en is bad ... -
Session authentication with Django channels
Trying to get authentication working with Django channels with a very simple websockets app that echoes back whatever the user sends over with a prefix "You said: ". My processes: web: gunicorn myproject.wsgi --log-file=- --pythonpath ./myproject realtime: daphne myproject.asgi:channel_layer --port 9090 --bind 0.0.0.0 -v 2 reatime_worker: python manage.py runworker -v 2 I run all processes when testing locally with heroku local -e .env -p 8080, but you could also run them all separately. Note I have WSGI on localhost:8080 and ASGI on localhost:9090. Routing and consumers: ### routing.py ### from . import consumers channel_routing = { 'websocket.connect': consumers.ws_connect, 'websocket.receive': consumers.ws_receive, 'websocket.disconnect': consumers.ws_disconnect, } and ### consumers.py ### import traceback from django.http import HttpResponse from channels.handler import AsgiHandler from channels import Group from channels.sessions import channel_session from channels.auth import channel_session_user, channel_session_user_from_http from myproject import CustomLogger logger = CustomLogger(__name__) @channel_session_user_from_http def ws_connect(message): logger.info("ws_connect: %s" % message.user.email) message.reply_channel.send({"accept": True}) message.channel_session['prefix'] = "You said" # message.channel_session['django_user'] = message.user # tried doing this but it doesn't work... @channel_session_user_from_http def ws_receive(message, http_user=True): try: logger.info("1) User: %s" % message.user) logger.info("2) Channel session fields: %s" % message.channel_session.__dict__) logger.info("3) Anything at 'django_user' key? => %s" % ( 'django_user' in message.channel_session,)) user = User.objects.get(pk=message.channel_session['_auth_user_id']) logger.info(None, "4) ws_receive: %s" % user.email) … -
Django form not showing up on admin page
I have a contact form/model in Django that isn't showing up on the admin management page. I have no idea why it isn't showing up, I have tried to debug by running migrations, and also renaming some of the model variables. models.py from django.db import models class Contact(models.Model): their_name = models.CharField(max_length=100) email = models.EmailField(max_length=100) message = models.CharField(max_length=500) def __str__(self): return self.name forms.py from django import forms class ContactForm(forms.Form): their_name = forms.CharField(label='Name', max_length=100) email = forms.EmailField(label='Email', max_length=100) message = forms.CharField(label='Message', max_length=500, widget=forms.Textarea(attrs = {'id': 'Message_form'})) admin.py from django.contrib import admin from .models import Contact admin.register(Contact) views.py from django.shortcuts import render from django.http import HttpResponse, HttpResponseRedirect from django.shortcuts import render_to_response from django.template import RequestContext from .models import Contact from .forms import ContactForm ... def contact(request): valid_input = 'no input' if request.method == 'POST': valid_input = 'invalid input' TheForm = ContactForm(request.POST) if TheForm.is_valid(): valid_input = 'valid input' name = TheForm['name'] email = TheForm['email'] message = TheForm['message'] Contact.objects.create(name=name, email=email, message=message) else: TheForm = ContactForm() return render(request, 'BlogHome/pages/contact.html', {'TheForm': TheForm, 'valid_input': valid_input}) Could this be the way I am importing the model? I have no idea what is causing this problem. -
html load more from json data on click of button
i'm trying display list of institutions from our api, where i want to disply only 10 and when load more button is clicked it should display remaining and load more button contain nextpage url i.e., remaining list in json format html code is as follows <div class="container text-center"> <h1 class="text-center">Existing Institutions </h1> <div class="row row-centered"> <div class="col-md-10 col-md-offset-1"> <div class="col-md-12"> <div class="table-responsive"> <table class="table table-bordered table-hover table-striped tablesorter"> <thead> <tr> <th class="header"> Institute Name <i class="icon-sort"></i></th> <th class="header"> Address <i class="icon-sort"></i></th> <th class="header"> Location <i class="icon-sort"></i></th> </tr> </thead> <tbody> {% for key in data %} <tr> <td><a href="../institutedetails?businessId={{ key.businessId }}">{{ key.displayName }}</a></td> <td>{{ key.businessAddress }}</td> <td>{{ key.businessLocation }}</td> </tr> {% endfor %} </tbody> </table> <ul class="pager"> <li class="next"><button name="load_more" id="load_more" onsubmit="loadMore({{ nextPage }});">Load More</button></li> </ul> </div> </div> </div> </div> </div> -
Studying SQL injections: can't drop tables
The code below is about Python + Django + PostgreSQL. But maybe the question is limited to psycopg2 behaviour. I'm studying web security and namely SQL injections. Learning purpose only. This is World sample database (http://pgfoundry.org/frs/?group_id=1000150&release_id=366#world-world-1.0-title-content). I have invented these SQL injections: 1'; drop table city cascade;select 1 where 'me'='me 1'; drop owned by admin;select 1 where 'me'='me I'm in the debug mode, so I can see errors if any. Well, these injections don't produce any errors. But the tables are still present. And I can execute those commands in psql: world=# drop owned by admin; DROP OWNED world=# \dt No relations found. QUESTION: Could you help me understand why my SQL injections don't produce the same result? world=# \dt List of relations Schema | Name | Type | Owner --------+-----------------+-------+------- public | city | table | admin public | country | table | admin public | countrylanguage | table | admin world=# \d+ city Table "public.city" Column | Type | Modifiers | Storage | Stats target | Description -------------+--------------+-----------+----------+--------------+------------- id | integer | not null | plain | | name | text | not null | extended | | countrycode | character(3) | not null | extended | | … -
Passing Context From One Django View To Another
I have a Django view with a membership form that redirects to a thank you page. The form is integrated with Stripe for payments. The form works as expected; charging via Stripe and redirecting to a thank you page. I would like pass the context variables to be displayed on the thank you page. I read Django Sessions can do this, but I can't figure it out. Below are my application and thank you page views. Thank you for your help. def membership_application(request): # TODO - add method to check if id exists before posting # TODO - setup proper form validation # TODO - Setup billing if request.method == 'POST': form = MembershipForm(data=request.POST) if form.is_valid(): stripe.api_key = settings.STRIPE_SECRET_KEY name = request.POST.get('name', '') address = request.POST.get('address', '') city = request.POST.get('city', '') state = request.POST.get('state', '') zip = request.POST.get('zip', '') phone_number = request.POST.get('phone_number', '') membership = request.POST.get('membership', '') support = request.POST.get('support', '') agree = request.POST.get('agree', '') email_address = request.POST.get('email_address', '') number = request.POST.get('number', '') cvc = request.POST.get('cvc', '') exp = request.POST.get('exp', '') # token = form.cleaned_data['stripe_token'], # exp_m = int(request.POST.get('exp_month', '')) # exp_y = int(request.POST.get('exp_year', '')) exp_month = exp[0:2] exp_year = exp[5:9] subject = 'New Plaque Order' from_email = settings.DEFAULT_FROM_EMAIL recipient_list … -
Storing images in Django model and media folder
I have been following this post However I do not understand this part in which the answer states In url.py from django.conf.urls.static import static from django.conf import settings urlpatterns = [.... ] + static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT) Now In my project if I add + static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT) after my urlpatterns = [.... ] I get the error + static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT) TypeError: bad operand type for unary +: 'list' any suggestions on how i can fix this ? -
How to get the part of a URL without protocol nor domain
I have URLs of the form http://example.com/example/a/b/c.html https//www.example.com/ How do I get the path from the server root, without protocol or domain name? With the examples above, the function should return: /example/a/b/c.html / (I am using Django: answers relying on this framework are accepted!) -
Making Network Requests through React Native
I have just started learning React Native. Built my Component and am trying to use an authenticate function written in a separate file to authenticate. My Authenticate file looks like var constants = require("../constants") module.exports = function(usr,pwd){ var trailing_url = '/api/token/'; var url = constants.DOMAIN + trailing_url; console.log("url"); return fetch(url, { method: "POST", headers: { 'Accept': 'application/json', 'Content-Type': 'application/json' }, body: JSON.stringify({ username: usr, password: pwd, }) }).then(function(response){ return response.json(); }).then(function(json){ return json; }); } I am experiencing this error once i go to fetch. I am unable to make network requests to my backend in django which is running at http://127.0.0.1:8000/api/token/ I am getting the following error. Couldn't copy paste that here for some reason. Another question I had is how to debug the code? I tried the Chrome debugger. But its showing Status: Waiting, press Ctrl R in simulator to reload and connect. Tried refreshing the Simulator but didn't work. -
Django and domain driven design
I am confused about Domain Driven Design Approaches. From the sources on net I understood it is way of segregating your Domain Objects and Database Objects but I don't understand the difference between two. For an example lets take the code of Polls example in django tutorial, there are two models Polls and Choice. Are these domain level objects or database level objects? Is there a need for DDD with an ORM? For example, this is the model class Polls(models.Model): question = models.CharField(max_length=200) pub_date = models.DateTimeField('date published') DDD approach code I have seen people writing class PollService(object): def __init__(self, poll_repository): self.poll_respository = poll_respository def update(self, poll_id): poll = self.poll_respository.fetch_by_id(poll_id) poll.question += '?' self.poll_respository.update(poll) #assume that the following code works? class PollRepository(): def __init__(self, db): self.db = db def update(self, poll): try: self.db.session().add(poll) self.db.session.commit() except Exception: self.db.session.rollback() Is this a correct approach? I see a lot of redundant code here but people say that Polls is a domain level object and it should not directly talk to database? Another approach views.py def update_poll(poll_id): poll = models.Polls.objects.get(poll_id) poll.question += '?' poll.save() What is wrong with this approach? -
Third Party API Integration in Python / Django
import requests r = requests.get('some url') data = r.text() {"NumberOfPassedStudents":"21061","TotalAttendedCandidates":"74494","NumberOfEnrolledStudents":"84308"} The above dictionary I got as a output My question is I want to get output in the below mention way Number of Passed Students : 21061 Total Attended Candidates : 74494 Number of Enrolled Students : 84308 What is the code in python 2.7 to convert those dictionary into my desire above mention output. -
Broken pipe from ('127.0.0.1', 57124)
Well, I have written the following code to make a login functionality at backend using django 1.10 and mongoengine 0.9.0 (MongoDB),here is the code: @csrf_exempt def check_auth(request): csrf_dict = {} csrf_dict.update(csrf(request)) username = json.loads(request.body)['username'] password = json.loads(request.body)['pwd'] try: user = User.objects.get(username=username) if user.check_password(password): user.backend = 'mongoengine.django.auth.MongoEngineBackend' user = authenticate(username=username, password=password) login(request, user) request.session.set_expiry(60 * 60 * 1) user_id = str(user.pk) print HttpResponse.status_code if request.POST.has_key('next'): return redirect(request.POST['next']) else: return redirect('/dashboard/home') else: return redirect('/dashboard/login') except DoesNotExist: return redirect('/dashboard/login') response code is 200, but it is not redirecting page to home, instead it is giving me the error: [04/Feb/2017 06:00:05] "POST /dashboard/check_auth HTTP/1.1" 302 0 [2017-02-04 06:00:05,223] - Broken pipe from ('127.0.0.1', 57124) Please suggest to resolve this issue. -
How to kill plugin-container process in python selenium ( selenium quit not working )?
I was using python selenium for my functional testing using geckodriver, but on recent update seems driver.quit not working ! gecko-driver - v0.14.0 python-selenium - 3.0.2 code in setUp & tearDown class FunctionTestCase(TestCase): def setUp(self): super(FunctionTestCase, self).setUp() self.driver = Firefox() self.driver.set_window_size(1024, 768) self.driver.delete_all_cookies() def tearDown(self): self.driver.delete_all_cookies() self.driver.quit() super(FunctionTestCase, self).tearDown() My intention using driver.quit() was clearing all data ( related to all domains) from the browser, but it is not working as expected; note that am also using delete_all_cookies method but it's only clear my dev server cookies ( this code was working perfectly, but dont care about that). -
is there a way to export images as zip and export data as csv in django?
There are actually two questions but both of them are about exporting First, what I want to do is, I have a bunch of image urls as FileField in db and the images are in s3 server. I want to have like a link which zips the images in bundle and download as the zip. If possible, I want to have few links and let's say link 1, 2, 3 and 1 downloads all images in January and 2 downloads all images in Feburary. Second, I want to export some joined tables and select which column to export the data as one csv / excel format file. Are these possible if so, how? Thanks in advance. -
Create a software with an API 'X'
I want to create a little software, to having fun, that could predict the price of gasoline. I'm having experience with Python and MySQL, and I've got a Ph.D. in mathematics. To create this little software, I need to manage databases and create graphs. In fact, that software is a prototype of a real software that I want to do. However, I don't know what's the better API to create that. I need a little bit of your help about that. What type of API could I use? Does Django could be a good solution? In reality, I want to work with two or three persons on my main project. So It'd be interesting to work on a local server (127.0.0.1:8000). -
Most Secure Way to Log Into Django Account from Java
I have a Django web application made with a system for accounts. Therefore, there are auth_user rows in my database. I want to access this database from a Java desktop application and use it to login users from the Java app. How may I securely and effectively accomplish this? -
Django and DRF How to use the fields of a POST request to the API before saving?
I have an installation of Django 1.10 and Django REST framework. I am getting POST requests well, but I would like it before the content is created, doing some tasks with the fields, I have the following in my views.py file from rest_framework.decorators import detail_route from rest_framework import serializers from suds.client import Client import base64 from . import views # Create your views here. from cfdipanel.models import Report, Invoice, UserProfile from cfdi.serializers import ReportSerializer, InvoiceSerializer, UserProfileSerializer class ReportViewSet(viewsets.ModelViewSet): queryset = Report.objects.all() serializer_class = ReportSerializer @detail_route(methods=['post']) def set_invoice(self, request, pk=None): #get report object my_report = self.get_object() serializer = InvoiceSerializer(data=request.data) if serializer.is_valid(): serializer.save(report=my_report) return Response(serializer.data, status=status.HTTP_201_CREATED) return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST) And this a fragment of my file serializer.py from rest_framework import serializers from cfdipanel.models import Report, Invoice, UserProfile class UserProfileSerializer(serializers.ModelSerializer): class Meta: model = UserProfile fields = ('user', 'karma') class InvoiceSerializer(serializers.ModelSerializer): class Meta: model = Invoice fields = ('uuid', 're', 'rr', 'tt', 'emision_date', 'type_invoice', 'status', 'owner') class ReportSerializer(serializers.ModelSerializer): owner = UserProfileSerializer(read_only=True) ownerId = serializers.PrimaryKeyRelatedField(write_only=True, queryset=UserProfile.objects.all(), source='owner') invoices = InvoiceSerializer(many=True, read_only=True, source='invoice_set') class Meta: model = Report fields = ('id', 'title', 'body', 'owner', 'ownerId', 'invoices') And this other is a snippet of models.py class Invoice(models.Model): owner = models.ForeignKey(UserProfile) report = models.ForeignKey(Report) uuid = models.CharField(max_length=36) … -
Django Modelform Redirect to form-submitted content
Disclaimer: Still very new at this. I've managed to get a site up and running that catalogs rock climbs. I've got a functioning form that allows users to submit a new item to the catalog, but have been unable to figure out how to redirect them to the newly created page. Here's my code: ("..." in place of what I think is irrelevant and bulky code. Let me know if you need it in!) forms.py: class PostForm(forms.ModelForm): class Meta: model = MyDB fields = (...) def save(self): instance = super(PostForm, self).save(commit=False) instance.slug = slugify (instance.name) instance.save() return instance views.py: def post_new(request): things = MyDB.objects.order_by('name') if request.method == "POST": form = PostForm(request.POST) if form.is_valid(): created_at = timezone.now() updated_at = timezone.now() form.save() return render(request, 'DB.html', { 'things': things, }) else: form = PostForm() return render(request, 'things/submit_thing.html', {'form': form}) models.py: from django.db import models class MyDB(models.Model): ... slug = models.SlugField(unique=True) and urls.py: url(r'^things/(?P<slug>[-\w]+)/$', views.thing_detail, name='thing_detail'), url(r'^post/new/$', views.post_new, name='post_new'), Right now i Just have it redirecting to a static html page because I can't figure out how to get it to load the newly created page. I've tried using the redirect function, but am unsure how to designate the newly created page as the … -
django logging to a file does not work
The django settings.py has: LOG_LEVEL = 'DEBUG' LOGGING = { 'version': 1, 'disable_existing_loggers': False, 'handlers': { 'logfile': { 'level': LOG_LEVEL, 'class': 'logging.handlers.RotatingFileHandler', 'filename': '/tmp/django.log', 'maxBytes': 1000000, 'backupCount': 10, }, }, 'loggers': { 'django.request': { 'handlers': ['logfile'], 'level': LOG_LEVEL, 'propagate': True, }, } } and views.py has: import logging def some_view(erquest): logging.info('something') I've also tried the following straight out of the official django 1.8 documentation: LOGGING = { 'version': 1, 'disable_existing_loggers': False, 'handlers': { 'file': { 'level': 'DEBUG', 'class': 'logging.FileHandler', 'filename': '/path/to/django/debug.log', }, }, 'loggers': { 'django.request': { 'handlers': ['file'], 'level': 'DEBUG', 'propagate': True, }, }, } I'm not getting this message in the log. However, if something throws and exception, that does show up in the django log file. Also, if I set DEBUG=False in the settings and use a print statement instead of the logger, then the message shows up in the console. Any ideas how to make the logger messages appear in the log file? -
How to address filtering in related models in django haystack
I have the following models: class Note(models.Model): user = ForeignKey(User) topic = CharField(max_length=20) class Referral(models.Model): recipient = ForeignKey(User, related_name=referral_rcvd) giver = ForeignKey(User, related_name=referral_given) about = CharField(max_length=20) and the following in search_indexes.py: class NoteIndex(indexes.SearchIndex, indexes.Indexable): text = indexes.EdgeNgramField(document=True, use_template=True) topic = indexes.CharField(model_attr='topic') What I want to see in my template is: Search for: <topic> Results: <ul> <topic> <topic.user.username> <topic.user.referral_rcvd.filter(about=topic) </ul> Working in shell so it's easier, this gives me what I want: from haystack.query import SearchQuerySet as SQS from models import * s = SQS().models(Note).auto_query('topic_name') [i.object.user.referral_rcvd.filter(about=i.object.topic).count() for i in s.all()] But this doesn't work in the html template: {% for result in object_list %} {{ result.object.user.referral_rcvd.filter(about=i.object.topic).count() }} {% endfor %} If it works in the shell, how do I make it work in the template? Thanks! -
Get saved object of a model form in Django?
I just want to access model details just after posting it with model form in Django. This guy also had asked the same thing but when i try the accepted answer, it returns none type value. Here is my code in 'views.py': if request.method == 'POST': if request.user.is_authenticated(): form = PostStoryForm(request.POST) if form.is_valid(): obj = form.save(commit=False) obj.author = request.user new_post = obj.save() print(new_post) The Code above saves the form to the database successfully but 'new_post' variable is 'None'. For example when i tried to access 'new_post.title' which is a field in my model, it returns 'AttributeError' which says 'NoneType' object has no attribute 'title' what am i doing wrong? -
django noreverse match help me
NoReverseMatch at / Reverse for 'show_category' with arguments '(u'',)' and keyword arguments '{}' not found. 1 pattern(s) tried: [u'rango/category/(?P>>[\w\-]d+)/$'] i got this error .... view.py url.py -
Django displaying content not defined in a template?
I verified that my Django url is calling the correct template or html file. The problem is the template is displaying the contents of a different template. Again I am 100% sure that my url is calling the correct template because I verified return render(request, 'my.html') calls my.html and there is no other my.html. So what could be wrong? Below is my setting, 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', ], }, }, ] -
csrf_exempt decorator not exempting
I have a wordpress site (coded with PHP) that I am using to post data to a django view. I post with this code $ch = curl_init( $url ); curl_setopt($ch, CURLOPT_POST, 1); curl_setopt($ch, CURLOPT_POSTFIELDS, $myvars); curl_setopt($ch, CURLOPT_FOLLOWLOCATION, 1); curl_setopt($ch, CURLOPT_HEADER, 0); curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1); curl_setopt($ch, CURLOPT_REFERER, 'https://mydjangosite.com/blah/blah2/'); The function the url above goes to is using the @csrf_exempt decorator because I want to allow a cross-site post in this instance from django.views.decorators.csrf import csrf_exempt @csrf_exempt @api_wrapper def add_referral_api(request, status_slug): However, I still receive this error in my logs [03/Feb/2017 18:17:48] WARNING [django.request:177] Forbidden (CSRF cookie not set.): How can I allow such cross-site posting between trusted sites? -
Django date__range query- add 1 day if date range ends on current date
On my site I have a page where you can enter a start and end date via a javascript calendar widget. It will query the database and return the results. Here is my view class flagfilter(ListView, View): form_class = FlagReportForm template_name = 'free/flagreport.html' paginate_by = 20 def get(self, request): form = self.form_class(None) return render(request, self.template_name, {'form': form}) def post(self, request): form = self.form_class(request.POST) if form.is_valid(): start_date = request.POST.get('start_date', '') end_date = request.POST.get('end_date', '') user = request.user s = datetime.datetime.strptime(str(start_date), '%m/%d/%Y') e = datetime.datetime.strptime(str(end_date), '%m/%d/%Y') if e == s: e = e + datetime.timedelta(days=2) s_filtered = s.strftime('%Y-%m-%d') e_filtered = e.strftime('%Y-%m-%d') punch = Punch.objects.filter(date__range=[str(s_filtered),str(e_filtered)]).order_by('-date') punches = punch.filter(user=user) context = {'punches': punches} return render(request, 'free/flagreport2.html', context) return render(request, self.template_name, {'form': form}) My issue is if you have a date range that ends on today's date it wont return objects from the current day. I added this line: if e == s: e = e + datetime.timedelta(days=2) I did this because if you have the start and end date as the current date it wouldn't return today's punch objects. This fixed the issue but I still have a problem. If you enter a date range with a start date of the, lets say, last …