Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Nginx rewrite to https from http on same server_name block when ssl is handled downstream
We have had this issue for ages now, and its starting to bite us in the ass. We run a site for a client written in python on the django framework. We then use nginx as a webserver/proxy for django. This is usually the most standard setup and works well. The issue is that our client has another apache server higher up. That server handles the ssl termination and just passes requests to us via normal http. The apache server accepts both http and https on 2 domain names. We can easily rewrite http to https on nginx level, but the issue comes in that a user can remove https and just use http. Is there a way on nginx level to force users back to https://secure.example.com if they are on http://secure.example.com. Thanks -
How do I filter out a sensitive GET parameter in Django's request logging?
I am building an API using Django, and have a GET endpoint (GET /api/token) that accepts a username & a password and responds with a token. I'd like to hide/obfuscate the password in the default django.server log - how do I do that? I've tried writing a custom filter, but it doesn't have access to the GET request's URL yet. -
Subdomain Django Settings Conflict
I have a site with a set of sub-domains. When I visit one of those sub-domains including the actual domain, it sometimes shows an Internal Server Error on the browser and when I check the apache error.log it tells that it throws an ImportError : [Tue Oct 11 06:47:10.999837 2016] [:error] [pid 13114] [client 0.0.0.0:58735] mod_wsgi (pid=13114): Target WSGI script '/var/www/html/api.ai-labs.co/ai_labs_apps/wsgi.py' cannot be loaded as Python module. [Tue Oct 11 06:47:11.000377 2016] [:error] [pid 13114] [client 0.0.0.0:58735] mod_wsgi (pid=13114): Exception occurred processing WSGI script '/var/www/html/api.ai-labs.co/ai_labs_apps/wsgi.py'. [Tue Oct 11 06:47:11.000478 2016] [:error] [pid 13114] [client 0.0.0.0:58735] Traceback (most recent call last): [Tue Oct 11 06:47:11.000552 2016] [:error] [pid 13114] [client 0.0.0.0:58735] File "/var/www/html/api.ai-labs.co/ai_labs_apps/wsgi.py", line 27, in <module> [Tue Oct 11 06:47:11.000675 2016] [:error] [pid 13114] [client 0.0.0.0:58735] application = get_wsgi_application() [Tue Oct 11 06:47:11.000737 2016] [:error] [pid 13114] [client 0.0.0.0:58735] File "/usr/local/lib/python2.7/dist-packages/django/core/wsgi.py", line 13, in get_wsgi_application [Tue Oct 11 06:47:11.000853 2016] [:error] [pid 13114] [client 0.0.0.0:58735] django.setup() [Tue Oct 11 06:47:11.000913 2016] [:error] [pid 13114] [client 0.0.0.0:58735] File "/usr/local/lib/python2.7/dist-packages/django/__init__.py", line 17, in setup [Tue Oct 11 06:47:11.001017 2016] [:error] [pid 13114] [client 0.0.0.0:58735] configure_logging(settings.LOGGING_CONFIG, settings.LOGGING) [Tue Oct 11 06:47:11.001076 2016] [:error] [pid 13114] [client 0.0.0.0:58735] File "/usr/local/lib/python2.7/dist-packages/django/conf/__init__.py", line 55, in __getattr__ … -
django - accessing the development server over HTTPS, but it only supports HTTP
I am using python 3.5 & django 1.10 on windows 7 os. I re-started my laptop today and when I attempt to access my python-django app on my local development server, I now receive the following error: Starting development server at http://127.0.0.1:8000/ Quit the server with CTRL-BREAK. [11/Oct/2016 17:16:17] code 400, message Bad request version ('À\x13À') [11/Oct/2016 17:16:17] You're accessing the development server over HTTPS, but i t only supports HTTP. [11/Oct/2016 17:16:17] code 400, message Bad request syntax ('\x16\x03\x01\x00§\ x01\x00\x00£\x03\x03]=Ä)\xa0L\x13\x11\x01;æ\x16:ÅUù\tÓÚß\x0c½\x01z¯êÉú¦ñÚ\x93\x0 0\x00"̨̩Ì\x14Ì\x13À+À/À,À0À\tÀ\x13À') [11/Oct/2016 17:16:17] You're accessing the development server over HTTPS, but i t only supports HTTP. I haven't made any recent changes to the settings.py file, so I am assuming that the settings are not the culprit here, but here are some relevant settings it case it helps solve the issue: SECURE_SSL_REDIRECT = False SECURE_PROXY_SSL_HEADER = ('HTTP_X_FORWARDED_PROTO', 'https') ALLOWED_HOSTS = ['127.0.0.1', 'localhost'] I have searched SO and found this post on the subject. The answer suggests that I Switch back to http and that error will disappear. Does this mean that I should change or enter the url in the browser from https://127.0.0.1:8000/ to http://127.0.0.1:8000/? I am asking this because when I try to do that, the url in … -
DjangoRest serializers: Save Foreignkey relation and serialize
I am new to Django rest and serializers concept I have this kind of DB structure User 1->N Address, User 1->N Phone User is a django.contrib.auth.models.User. Address and Phone both models contains this field user_id = models.ForeignKey(User, on_delete=models.CASCADE) In my UserSerializer looks like this class UserSerializer(serializers.ModelSerializer): address = AddressSerializer(many=False) phone = PhoneSerializer(many=False) class Meta: model = User fields = ( 'id', 'username', 'first_name', 'last_name', 'email', 'password', 'address', 'phone') def create(self, validated_data): # Save user. user = User.objects.create( first_name=validated_data['first_name'], last_name=validated_data['last_name'], username=validated_data['username'], email=validated_data['email'], ) user.set_password(validated_data['password']) user.save() # User's address address_data = validated_data['address'] address_data['user_id'] = user.id address = Address.objects.create(**address_data) # User's phone phone_data = validated_data['phone'] phone_data['user_id'] = user.id phone = Phone.objects.create(**phone_data) return user And AddressSerializer: class AddressSerializer(serializers.ModelSerializer): class Meta: model = Address fields = ( 'user_id', 'address', 'pin_code', 'state', 'city', 'country') I am able to create User but while doing serializer.data I am getting this error: AttributeError: Got AttributeError when attempting to get a value for field `address` on serializer `UserSerializer`. The serializer field might be named incorrectly and not match any attribute or key on the `User` instance. Original exception text was: 'User' object has no attribute 'address'. -
Django How to validate form w/ foreign field without creating the object until all constraints are met?
I have a form with the model below and would like to make Artist and Title a required field. If Artist exists, it would use the existing foreign key, if not it would create a new Artist object. If user only specifies the Artist field, and leaves the Title field blank, it would state Title field is required and not create an Artist object until all constraints are met. How should I code this? models.py: class Artist (models.Model): name = models.CharField(max_length=100) Class Track (models.Model): artist = models.ForeignKey(Artist, blank=True, null=True, on_delete=models.SET_NULL, verbose_name="Artist") user = models.ForeignKey(settings.AUTH_USER_MODEL, blank=True, null=True, on_delete=models.SET_NULL, verbose_name="Submitted by", default=1) title = models.CharField(max_length=100, verbose_name="Title") mix = models.CharField(max_length=100, blank=True, verbose_name="Mix") views.py: class TrackCreateView(SuccessMessageMixin, AjaxCreateView): form_class = ProfileForm success_message = "Thank you for submitting track: %(artist)s - %(title)s - %(mix)s" def get_initial(self): self.initial.update({ 'user': self.request.user }) return self.initial def get_success_message(self, cleaned_data): return self.success_message % dict(cleaned_data, artist=self.object.artist, title=self.object.title, mix=self.object., ) forms.py: class ProfileForm(forms.ModelForm): class Meta: model = Track fields = [ "artist", "title", "mix", ] artist = forms.CharField(widget=forms.TextInput(attrs={'maxlength': '100',})) def __init__(self, *args, **kwargs): self.user = kwargs['initial']['user'] super(ProfileForm, self).__init__(*args, **kwargs) # Set layout for fields. my_field_text= [ ('artist', 'Artist', ''), ('title', 'Title', ''), ('mix', 'Mix', ''), ] for x in my_field_text: self.fields[x[0]].label=x[1] self.fields[x[0]].help_text=x[2] self.helper … -
Python Django not running
Firstly I installed Django using pip in my "CentOS" operating system. After that I performed these steps using terminal. "django-admin startproject mysite" a folder mysite is created with : manage.py and another subfolder mysite Then simply I just used these commands : python manage.py runserver and the server was running as clicked on the url : http://localhost:portnumber/ But after that when I made another app to run it is not running, my step are as follows : python manage.py startapp webapp Then one new folder created webapp in same mysite directory is created. After changing settings.py and urls.py of mysite and also changing urls.py and views.py of webapp. when i run : python manage.py runserver error is coming Performing system checks... Unhandled exception in thread started by <function wrapper at 0x24a7398> Traceback (most recent call last): File "/usr/lib/python2.7/site-packages/django/utils/autoreload.py", line 226, in wrapper fn(*args, **kwargs) File "/usr/lib/python2.7/site- packages/django/core/management/commands/runserver.py", line 121, in inner_run self.check(display_num_errors=True) File "/usr/lib/python2.7/site-packages/django/core/management/base.py", line 374, in check include_deployment_checks=include_deployment_checks, File "/usr/lib/python2.7/site-packages/django/core/management/base.py", line 361, in _run_checks return checks.run_checks(**kwargs) File "/usr/lib/python2.7/site-packages/django/core/checks/registry.py", line 81, in run_checks new_errors = check(app_configs=app_configs) File "/usr/lib/python2.7/site-packages/django/core/checks/urls.py", line 14, in check_url_config return check_resolver(resolver) File "/usr/lib/python2.7/site-packages/django/core/checks/urls.py", line 28, in check_resolver warnings.extend(check_resolver(pattern)) File "/usr/lib/python2.7/site-packages/django/core/checks/urls.py", line 24, in check_resolver for pattern in … -
rlm_rest serving TTLS PAP
I'm trying writing a django based service to serve FreeRadius rlm_rest. Currently, it's succes on : 1. Serving FreeRadius DHCP 2. Serving Authorization for PPPoE NAS, using only PAP, including set user IP-Address, Default Route Gateway and DNS server. but it Fail serving user using Android Wifi with TTLS-PAP. What user's gadget got is : 1. Looks like authenticated, but ... 2. keep in 'Optaining IP Address' state for some minutes ..... and Fail. Radius Debug (freeradius -X -x) Tue Oct 11 04:59:00 2016 : Debug: (34) rest: JSON Data: {"User-Name":{"type":"string","value":["dokter01"]},"User-Password":{"type":"string","value":["dr123456"]},"NAS-IP-Address":{"type":"ipaddr","value":["10.255.255.12"]},"Service-Type":{"type":"integer","value":[2]},"Framed-MTU":{"type":"integer","value":[1400]},"Called-Station-Id":{"type":"string","value":["00-0C-42-CF-16-55:ojoliwatkene"]},"Calling-Station-Id":{"type":"string","value":["08-8C-2C-0D-84-67"]},"NAS-Identifier":{"type":"string","value":["apsi-metal"]},"NAS-Port-Type":{"type":"integer","value":[19]},"NAS-Port-Id":{"type":"string","value":["wlan1"]},"FreeRADIUS-Proxied-To":{"type":"ipaddr","value":["127.0.0.1"]}} Tue Oct 11 04:59:00 2016 : Debug: (34) rest: Returning 631 bytes of JSON data Tue Oct 11 04:59:01 2016 : Debug: (34) rest: Processing response header Tue Oct 11 04:59:01 2016 : Debug: (34) rest: Status : 200 (OK) Tue Oct 11 04:59:01 2016 : Debug: (34) rest: Type : json (application/json) Tue Oct 11 04:59:01 2016 : Debug: (34) rest: Parsing attribute "reply:Reply-Message" Tue Oct 11 04:59:01 2016 : Debug: (34) rest: Type : string Tue Oct 11 04:59:01 2016 : Debug: (34) rest: Length : 20 Tue Oct 11 04:59:01 2016 : Debug: (34) rest: Value : "Welcomeback dokter01" Tue Oct 11 04:59:01 2016 : Debug: … -
How to get appname from model in django
I have this code class Option(models.Model): option_text = models.CharField(max_length=400) option_num = models.IntegerField() # add field to hold image or a image url in future class Meta: app_label = 'myapp' if i have Options model in my view i want to get the appname from it -
Rabbitmq message queues pile up untill system crash (all queues are "ready")
I have a simple Raspberry pi + Django + Celery + Rabbitmq setup that I use to send and receive data from Xbee radios while users interact with the web app. For the life of me I cant get Rabbitmq (or celery?) under control where after only a single day (sometimes a little longer) the whole system crashes due to some kind of memory leak. What I am suspecting is that the queues are piling up and never being removed. Heres a picture of what I see after only a few minutes of run time: Seems that all of the queues are in the "ready" state. What's strange is that it would appear that the workers do in fact receive the message and run the task. The task is very small and shouldn't take longer than 1 second. I have verified the tasks do execute to the last line and should be returning ok. I'm no expert and have no clue what I'm actually looking at so I'm unsure if that is normal behavior and my issue lies elsewhere? I have everything set to run as daemonized, however even when running in development modes I get same results. I have … -
DoesNotExist at /admin/login/ Site matching query does not exist
I am getting this problem. I do not know why. I have used django cookie cutter. DoesNotExist at /admin/login/ Site matching query does not exist. Request Method: GET Request URL: http://localhost:8020/admin/login/?next=/admin/ Django Version: 1.9.10 Exception Type: DoesNotExist Exception Value: Site matching query does not exist. Exception Location: /home/mufti/Documents/latestCookieCutter/projects/local/lib/python2.7/site-packages/django/db/models/query.py in get, line 387 Python Executable: /home/mufti/Documents/latestCookieCutter/projects/bin/python Python Version: 2.7.6 Python Path: ['/home/mufti/Documents/latestCookieCutter/testpro', '/home/mufti/Documents/latestCookieCutter/projects/lib/python2.7', '/home/mufti/Documents/latestCookieCutter/projects/lib/python2.7/plat-x86_64-linux-gnu', '/home/mufti/Documents/latestCookieCutter/projects/lib/python2.7/lib-tk', '/home/mufti/Documents/latestCookieCutter/projects/lib/python2.7/lib-old', '/home/mufti/Documents/latestCookieCutter/projects/lib/python2.7/lib-dynload', '/usr/lib/python2.7', '/usr/lib/python2.7/plat-x86_64-linux-gnu', '/usr/lib/python2.7/lib-tk', '/home/mufti/Documents/latestCookieCutter/projects/local/lib/python2.7/site-packages', '/home/mufti/Documents/latestCookieCutter/testpro/src', '/home/mufti/Documents/latestCookieCutter/projects/lib/python2.7/site-packages'] Server time: Tue, 11 Oct 2016 09:43:55 +0600 -
How can Javascript or jQuery access my Django Models?
I have a little bit of jQuery on my page which needs to access one of my Django Models. Basically it's a form autocomplete, and it needs to look up values in my database. I understand how to get values into a Django Template, but getting them into some Javascript code is confusing. Is this possible? How can it be done? Thank you. -
django channels routing error
I'm doing chat application with django-channels but I have strange routing error. AttributeError: 'Message' object has no attribute 'META' so here is my routing.py from channels.routing import route, include from chat.consumers import ws_connect, ws_message, ws_disconnect from chat.views import chatmain http_routing = [ route("http.request", chatmain, path=r"^/chatwindow/$", method=r"^GET$"), ] chat_routing = [ route("websocket.connect", ws_connect), route("websocket.receive", ws_message), route("websocket.disconnect", ws_disconnect), ] channel_routing = [ include(chat_routing), include(http_routing), ] I want then I follow /chatwindow link to use normal view and unload chat application but it won't work. -
why is accessing a dictionary value using a value from a list not possible in django templates?
Hello I have a list of strings that has numbers created using the following code... time_value= [str(j) for j in [i%24 for i in xrange(4,28)]] Then I have a dict something like this time_dict={'19': [<Task: 3rd task>, <Task: 3rd task>], '18': [<Task: 1st task>, <Task: 2nd task>]} Now in template, I am iterating over time_value and I have an if statement that compares the current value with the time_dict.keys(). Which if true should do something now if I run the following code it wont work {% if value in time_dict.keys %} <td> {{ time_dict.value }}</td> {% endif%} time_dict.value wont print the list, but if I do the following {% if value in time_dict.keys %} <td> {{ time_dict.18}}</td> {% endif%} then it works fine it prints the list in front of 18...why is it not printing the values. Is there a workaround.... -
Django: How can I make views accept only ajax request?
What I want to do is not to allow general POST request, only accept ajax request. class CustomerInfoCheckView(View): def post(self, request, *args, **kwargs): # CustomerInfoForm by ajax request if request.is_ajax(): form = CustomerInfoForm( request.POST, ) if form.is_valid(): return JsonResponse( data={ "valid": True, } ) else: return JsonResponse( data={ "valid": False, "errors": form.errors } ) else: return Http404 But problem is that is shows an error: AttributeError: type object 'Http404' has no attribute 'get'. How can I deal with it? -
Django Sanity Test Reveals 404 is not 404
I was creating sanity checks in my django tests and came across an error I had accounted for. Unfortunately my test fails when it should be successful. I am testing when a page is not there (a 404 status code). The error message and code are below. When I added quotes I received 404 is not '404'. Django-1.10.2 & Python 3.4.5 ./manage.py test app Traceback (most recent call last): File "/tests/dir/tests.py", line 26, in test_404 self.assertIs(response.status_code,404) AssertionError: 404 is not 404 from django.test import TestCase from django.test import Client class SanityCheckTests(TestCase): def test_404(self): """ Http Code 404 """ client = Client() response = client.get('/test404') print(response) self.assertIs(response.status_code,404) -
Use admin template in an app
I am fairly new to Django (and web development in general) and I'm having a tough time understanding how to use the resources that are already available to us. I am trying to make an app that produces a sortable table quite similar the one I have in the admin app from the official tutorial (I linked a picture to make it more explicit). I found out that I need to use the {% extends admin/base_site.html %} tag to at least get the general style and the header, however I'm having a tough time overriding the table to get it to stretch on the width and setting the rows inside it without hardcoding most of it. This is the template I have for now: {% extends "admin/base_site.html" %} {% block title %}AnimeList{% endblock %} {% block breadcrumbs %}{% endblock %} {% block branding %} <h1 id="site-name">AnimeList</h1> {% endblock %} {% block content %} <div id="content-main"> <form action="{% url 'animelist:anime_form' %}" method="post"> {% csrf_token %} <input type="submit" value="Add anime" /> </form> <div class="results"> <table id="result_list" width="100%"> <thead> <tr> <th class="sortable" scope="col"> <div class="text">Anime name</div> <div class="clear"></div> </th> <th class="sortable" scope="col"> <div class="text">Number of episodes seen</div> <div class="clear"></div> </th> <th class="sortable" scope="col"> … -
python django id to hex
I'm looking to take the default ID key from the django model turn it into hexadecimal and display it on a page when the user sumbits the post, I've tried several of methods with no success can anyone point me in the right direction? views.py def post_new(request): if request.method == "POST": form = PostForm(request.POST) if form.is_valid(): post = form.save(commit=False) post.author = request.user post.published_date = timezone.now() post.save() return redirect('post_detail', pk=post.pk) else: form = PostForm() return render(request, 'books_log/post_edit.html', {'form': form}) Can supply more information if needed. -
Create a new user when using facebook authentication - Django
I am following a book to learn Django, "Django by Example". At this moment I am learning how to use facebook authentication system using the python-social-auth package. Before using the facebook login each user should register on the website, where I use the following function, where you can see it creates a new_user and a profile linked to this new_user: def register(request): if request.method == 'POST': user_form = UserRegistrationForm(request.POST) if user_form.is_valid(): new_user = user_form.save(commit=False) new_user.set_password(user_form.cleaned_data['password']) new_user.save() profile = Profile.objects.create(user=new_user) return render(request, 'account/register_done.html', {'new_user': new_user}) else: print (user_form.errors) else: user_form = UserRegistrationForm() return render(request, 'account/register.html', {'user_form': user_form}) I am wondering what I should do to create a new user when someone login with facebook, and at the same time creating a profile linked to this user. -
Django - Many To Many after filtering one end of the relationship, counting backwards always produces the value 1
I have two models that are in a Many To Many relationship, and I want the following effect to occur: Consider models A and B in a many to many relationship with eachother. A's related_name for B is bs and B's related name for A is as Whenever I create an A or B it will always be immediately connect to one or more of the other, so initially all instances of A and B will have at least one related object. If I want to delete an A (let's call it a0) I want it to delete all Bs that would be left with no related A's after a0 is deleted, so essentially I want to delete all B that have only a0 in their related_set as (the reverse example of this would also be expected). The way I was trying to implement this is, when I want to delete an A such as a0, I would say: a0.bs.annotate(Count('bs')).filter(bs__count=1).delete() However this would unconditionally delete ALL related B instances in a0.bs, and when I went to the shell to test it out, when I would get this result: >>> a0.bs.annotate(Count('bs')).values_list('bs__count',flat=True) <QuerySet [1, 1, 1, 1]> >>> B.objects.filter(as=a0).annotate(Count('bs')).values_list('bs__count',flat=True) <QuerySet [1, 1, … -
django: side menu template visible everywhere
I need to create a side menu in my django admin that should appear in all pages. Ideally my template should be a generic navigation.html file containing this code and parsing app_list param (the same that is used into index.html template populating the dashboard): {% block side_menu %} {% if app_list %} {% for app in app_list %} <ul class="sidebar-menu app-{{ app.app_label }} module"> <li class="treeview"> <a href="#"> <i class="fa fa-dashboard"></i> <span>{{ app.name | truncatechars:"25" }}</span> <span class="pull-right-container"> <i class="fa fa-angle-left pull-right"></i> </span> </a> {% for model in app.models %} <ul class="treeview-menu"> {% if model.admin_url %} <li><a href="{{ model.admin_url }}"><strong>{{ model.name }}</strong></a></li> {% else %} <li>{{ model.name }}</li> {% endif %} {% if model.add_url %} <li><a href="{{ model.add_url }}"><i class="fa fa-plus"></i> {% trans 'Add' %}</a></li> {% else %} <td>&nbsp;</td> {% endif %} {% if model.admin_url %} <li><a href="{{ model.admin_url }}"><i class="fa fa-pencil-square-o"></i> {% trans 'Change' %}</a></li> {% else %} <td>&nbsp;</td> {% endif %} </ul> {% endfor %} </li> </ul> {% endfor %} {% else %} <p>{% trans "You don't have permission to edit anything." %}</p> {% endif %} {% endblock side_menu %} My questions are: 1) how can I include my new navigations.html template in all pages? 2) how can … -
Capture semantic version in django url
I have the following url http://localhost:8000/api/package/printf/release/v0.0.1 I need to capture the version at the end. What is the right way for the same. The url regex that i have now is /package/(?P<pk>[a-z]+)/release/(?P<version[a-z]+)/$ The semantic version should be passed as a single parameter and not as multiple int with major and minor version etc as different parameters. -
Using MySQL in a Docker Container
I am kinda new to Docker and I am trying to build an image for a Django App using MySQL. The problem that I am having is, after running my image I get the following error : django.db.utils.OperationalError: (2002, "Can't connect to local MySQL server through socket '/var/run/mysqld/mysqld.sock' (111)") . As a base for the image I am using FROM django:python2 , I have installed the server using the following commands: RUN echo "mysql-server mysql-server/root_password password X" | debconf-set-selections RUN echo "mysql-server mysql-server/root_password_again password X" | debconf-set-selections RUN apt-get update && apt-get install -y mysql-server To fix the problem I tried multiple solutions, which I found on the internet such as: RUN touch /var/run/mysqld/mysqld.sock RUN chmod -R 755 /var/run/mysqld/mysqld.sock EXPOSE 3306 Sadly, nothing worked. I also made sure the server is running, yet the problem is still there. -
AttributeError on Django migration / Django-polymorphic
I'm trying to update my app to use django-polymorphic. I'm getting an error that I don't really understand when trying to make the migration. I've just changed DashableModel to inherit from PolymorphicModel instead of models.Model and I have no idea how to approach this error. File "manage.py", line 10, in <module> execute_from_command_line(sys.argv) File "/root/.virtualenvs/mysite/local/lib/python2.7/site-packages/django/core/management/__init__.py", line 351, in execute_from_command_line utility.execute() File "/root/.virtualenvs/mysite/local/lib/python2.7/site-packages/django/core/management/__init__.py", line 325, in execute django.setup() File "/root/.virtualenvs/mysite/local/lib/python2.7/site-packages/django/__init__.py", line 18, in setup apps.populate(settings.INSTALLED_APPS) File "/root/.virtualenvs/mysite/local/lib/python2.7/site-packages/django/apps/registry.py", line 108, in populate app_config.import_models(all_models) File "/root/.virtualenvs/mysite/local/lib/python2.7/site-packages/django/apps/config.py", line 198, in import_models self.models_module = import_module(models_module_name) File "/usr/lib/python2.7/importlib/__init__.py", line 37, in import_module __import__(name) File "/srv/www/apps/jobboard/models.py", line 280, in <module> class JobPost(SiteModel, OrderableMixIn, DashableModel): File "/root/.virtualenvs/mysite/local/lib/python2.7/site-packages/django/db/models/base.py", line 189, in __new__ new_class.add_to_class(obj_name, obj) File "/root/.virtualenvs/mysite/local/lib/python2.7/site-packages/django/db/models/base.py", line 324, in add_to_class value.contribute_to_class(cls, name) File "/root/.virtualenvs/mysite/local/lib/python2.7/site-packages/django/db/models/fields/related.py", line 2549, in contribute_to_class self.rel.through = create_many_to_many_intermediary_model(self, cls) File "/root/.virtualenvs/mysite/local/lib/python2.7/site-packages/django/db/models/fields/related.py", line 2106, in create_many_to_many_intermediary_model db_constraint=field.rel.db_constraint, File "/root/.virtualenvs/mysite/local/lib/python2.7/site-packages/django/db/models/base.py", line 189, in __new__ new_class.add_to_class(obj_name, obj) File "/root/.virtualenvs/mysite/local/lib/python2.7/site-packages/django/db/models/base.py", line 324, in add_to_class value.contribute_to_class(cls, name) File "/root/.virtualenvs/mysite/local/lib/python2.7/site-packages/django/db/models/fields/related.py", line 1772, in contribute_to_class super(ForeignObject, self).contribute_to_class(cls, name, virtual_only=virtual_only) File "/root/.virtualenvs/mysite/local/lib/python2.7/site-packages/django/db/models/fields/related.py", line 313, in contribute_to_class add_lazy_relation(cls, self, other, resolve_related_class) File "/root/.virtualenvs/mysite/local/lib/python2.7/site-packages/django/db/models/fields/related.py", line 86, in add_lazy_relation operation(field, model, cls) File "/root/.virtualenvs/mysite/local/lib/python2.7/site-packages/django/db/models/fields/related.py", line 312, in resolve_related_class field.do_related_class(model, cls) File "/root/.virtualenvs/mysite/local/lib/python2.7/site-packages/django/db/models/fields/related.py", line 355, in do_related_class self.set_attributes_from_rel() File … -
Why does django date filter gives me entries from the next day as welll
I am trying to access a database which has say two entries for 2016,9,25 and two entries for 2016,9,26, each of those entries have different time... I view them by listing each of them using the task.start_time in my template following is the list that I get TASK Task.title duration start_time project project_color user 1st task This is the first task 0:02:40 Sept. 25, 2016, 11:42 p.m. Unassigned NO COLOR faizank 2nd task This is the second task 0:01:30 Sept. 25, 2016, 11:47 p.m. Unassigned NO COLOR faizank 3rd task asdasdasdasd 0:20:00 Sept. 26, 2016, 12:19 a.m. Unassigned NO COLOR faizank 3rd task this is the problem 0:20:00 Sept. 26, 2016, 12:22 a.m. Unassigned NO COLOR faizank start_time is a datetime_field, now i am filtering the datetime object using the following queries >>> c= Task.objects.filter(start_time__date=datetime.date(2016,9,25) This gives me <QuerySet [<Task: 1st task>, <Task: 2nd task>, <Task: 3rd task>, <Task: 3rd task>]> but when I change the date to 26 it gives me an empty set.... I even did this >>> c= Task.objects.filter(start_time__date=datetime.datetime(2016,9,25,0,0,0,0,pytz.UTC) got the same result. So why is the date returning the entries from 26 as well....and on querring 26 it returns an empty set....