Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Windows 10 bash: pipenv: command not found
I need your help to resolve the bash: pipenv: command not found I get whenever I run $ pipenv install and $ pipenv shell on my Windows 10 machine. I know that pipenv IS installed because when I attempt to uninstall with $ pip uninstall pipenv I get Found existing installation: pipenv 2018.11.26 Uninstalling pipenv-2018.11.26: Would remove: c:\users\username\appdata\roaming\python\python38\scripts\pipenv-resolver.exe c:\users\username\appdata\roaming\python\python38\scripts\pipenv.exe c:\users\username\appdata\roaming\python\python38\site-packages\pipenv-2018.11.26.dist-info\* c:\users\username\appdata\roaming\python\python38\site-packages\pipenv\* Proceed (y/n)? Of course, I do not want to uninstall. I just want pipenv to run correctly. Appreciate your letting me know what I'm doing wrong. Thanks. -
Is there any suggestion to add group by in my query?
Hi there here is my query please suggest me how can I add a group by the field name in Model1 model, I tried to add distinct('name') but it says DISTINCT is not supported in the backend. result = Model1.objects.filter( custNumber__in=Model2.objects.filter(cpnumber=cp.cpnumber).values_list( 'custNumber', flat=True)).order_by('name') Thanks in advance -
Pizza ordering site django
I am creating a Pizza ordering system using Django, and I have 4 fields for my Pizza model. I have already added the different variations into the model (e.g: Regular Small 1 Topping (13.70), Regular Small Cheese (12.70)). Now I need to add toppings based on which addon the user selects. I have a list for all the toppings, but I am not exactly sure what to do now? Could someone guide on what i should do? SIZES = ( ("Small", "Small"), ("Large", "Large") ) class Pizza(models.Model): #type-size-topping (db) STYLES = ( ('Regular', 'Regular'), ('Sicilian', 'Sicilian') ) ADDONS = ( ('Cheese', 'Cheese'), ('1 Topping', '1 Topping'), ('2 Topping', '2 Toppings'), ('3 Topping', '3 Toppings'), ('Special', 'Special') ) type = models.CharField(max_length=10, choices=STYLES) size = models.CharField(max_length=10, choices=SIZES) addons = models.CharField(max_length=20, choices=ADDONS) price= models.DecimalField(max_digits=10, decimal_places=2) class Meta: verbose_name_plural = "Pizza" def __str__(self): return f"{self.type} {self.size} {self.addons} ({self.price})" Thanks in advance! -
Trying to add the ability to create or select a category through front end form instead of having to create them all manually through the backend
So I have a front end form for posting an article but as far as the categories go I can only select ones that I've already added through the back end. I want to be able to either select a pre existing category or add a new one instead of having to add them manually through admin. My categories link through a foreign key to a separate Category model. I added a second form for category but then it doesn't connect it to the article being posted. models.py: class Category(models.Model): title = models.CharField(max_length=20) class Meta: verbose_name = "Category" verbose_name_plural = "Categories" ordering = ['title'] def __str__(self): return self.title class Post(models.Model): title = models.CharField(max_length=100) overview = models.TextField() timestamp = models.DateTimeField(auto_now_add=True) content = HTMLField() author = models.ForeignKey(User, on_delete=models.CASCADE) thumbnail = models.ImageField() categories = models.ManyToManyField(Category) featured = models.BooleanField() previous_post = models.ForeignKey( 'self', related_name='previous', on_delete=models.SET_NULL, blank=True, null=True) next_post = models.ForeignKey( 'self', related_name='next', on_delete=models.SET_NULL, blank=True, null=True) bookmarked = models.ManyToManyField(User, related_name='bookmarked', blank=True) allow_comments = models.BooleanField(default=True) def __str__(self): return self.title def get_absolute_url(self): return reverse('index:post-detail', kwargs={ 'post_id': self.id }) def get_update_url(self): return reverse('post-update', kwargs={ 'pk': self.pk }) def get_delete_url(self): return reverse('post-delete', kwargs={ 'pk': self.pk }) @property def view_count(self): return PostView.objects.filter(post=self).count() def save(self): super().save() img = Image.open(self.thumbnail.path) if img.height … -
IntegrityError: UNIQUE cosntraint failed, how to catch and respond
I'm making a marketplace app with Django REST framework which I'm new to. I wrote a test to test the unique together field. It works as I wanted it to, raising a UNIQUE constraint failed error when the fields author and target are not unique together, but my question is how should I handle this error so that my test would pass. models.py class Review(models.Model): FEEDBACK_CHOICES = [ ('POSITIVE', 'positive'), ('NEUTRAL', 'neutral'), ('NEGATIVE', 'negative') ] feedback = models.CharField( max_length=8, choices=FEEDBACK_CHOICES, default='NEGATIVE' ) review = models.TextField(max_length=200) target = models.ForeignKey( settings.AUTH_USER_MODEL, related_name='reviews', on_delete=models.CASCADE ) author = models.ForeignKey( settings.AUTH_USER_MODEL, related_name='given_reviews', on_delete=models.CASCADE ) created = models.DateTimeField(auto_now_add=True) class Meta: ordering = ['created'] unique_together = ['author', 'target'] serializers.py class ReviewSerializer(serializers.ModelSerializer): target = serializers.PrimaryKeyRelatedField( queryset=User.objects.all() ) author = serializers.ReadOnlyField(source='author.id') class Meta: model = Review fields = [ 'id', 'feedback', 'review', 'target', 'author', 'created' ] views.py class ReviewViewSet(viewsets.ModelViewSet): queryset = Review.objects.all() serializer_class = ReviewSerializer permission_classes = [ ReviewPermissions ] def perform_create(self, serializer): serializer.save(author=self.request.user) -
Django Swagger landing page
I have some API's in my Django project and I have successfully installed Django Swagger for the API documentation but when I hit the swagger url, I am not able to view any kind of existing API's of my project in the swagger UI. Please suggest a workaround to get all the needed apis visible in the swagger UI Note :- http://localhost:8000/api is the swagger URL. -
Why i keep getting exception in views.py?
I am trying to create article by receiving data from serializers.py but i always get exception error in my code. Views.py class ArticleView(CreateAPIView): serializer_class = ArticleCreateSerializer permission_classes = (IsAuthenticated,) def post(self, request, format=None): try: serializer = self.serializer_class(data=serializer_data, context=serializer_context,) serializer_context = { 'request': request } serializer_data = request.data.post('article',{}) if serializer.is_valid(): serializer.save(author=self.request.user.profile) return Response(serializer_data, status=status.HTTP_201_CREATED) else: return JsonResponse({'fail':'True'}) except Exception as e: return JsonResponse({'exception':'True'}) def get(self, request, format=None): queryset = Article.objects.all() serializer = ArticleCreateSerializer() return Response(serializer.data) It always returns this output {'exception':'True'} Does anybody knows why? -
Display images with carousel in Django
I have problems while displaying my images, the same image is always printed on the carousel. Image URLs have not problem bot I see only one and the same image in my carousel. I know there are 3 different images because of for loop but when I delete it, the carousel is not work The method I tried is below. {% for i in ads%} <div id="carouselExampleSlidesOnly" class="carousel slide" data-ride="carousel"> <div class="carousel-inner"> <div class="carousel-item active"> <img src="/image/{{i.image_ads}}" class="d-block w-100" alt="DersNo1"> </div> <div class="carousel-item"> <img src="/image/{{i.image_ads}}"class="d-block w-100" alt="DersNo2"> </div> <div class="carousel-item"> <img src="/image/{{i.image_ads}}"class="d-block w-100" alt="DersNo3"> </div> </div> </div> {%endfor %} -
How to use Pycharm debugger tool for django with "heroku local web" command?
the question is: How to use Pycharm debugger tool for django with "heroku local web" command? Thankyou for your answers! -
Django Rest Framework reduce number of queries
I have 2 models ModelA and ModelB. Their common field is the foreignkey to the model ModTypes. class ModelA (models.Model): types = models.ForeignKey( ModTypes, verbose_name='type', on_delete=models.PROTECT) model_name = models.CharField( verbose_name='Model name', max_length=20) class ModelB (models.Model): types = models.ForeignKey( ModTypes, verbose_name='type', on_delete=models.PROTECT) serial_number = models.CharField( verbose_name='Serial number', max_length=50) There are 3 ModType records: TypeA, TypeB and TypeC which are linked to a ManyToManyField 'users'. class ModTypes(models.Model): field_one = models.CharField(max_length=60) field_two = models.CharField(max_length=60) users = models.ManyToManyField( settings.AUTH_USER_MODEL, verbose_name='user access', blank=True) Lets say user JohnDoe is in the TypeA record. Using django rest framework serialization, I have a custom mixin to automatically adds the ModType that belongs to JohnDoe. def get_modtype(user): return ModTypes.objects.filter(users=users))[0] class ModTypeMixin(object): def filter_queryset(self, queryset): user = self.request.user qry = super().filter_queryset(queryset) return qry.filter(types=get_modtype(user)) def perform_create(self, serializer): user = self.request.user serializer.save(types=get_modtype(user)) Everything works fine except if I view it from the performance perspective. Everytime a request is made, this kind of mixin makes the same kind of request. So I decided to load the users ModType information after logging in. I tried to modify the user instance when the user_logged_in signal is triggered. But I cant get the information to the serializer. What am I doing wrong. And what would be … -
TypeError: Update_Profile() missing 1 required positional argument: 'self'
whenever i am creating the superuser then it's throwing me error Update_Profile() missing 1 required positional argument: 'self'. @receiver(post_save, sender=User) def Update_Profile(self, instance, created, **kwargs): if created: UserProfile.objects.create(user=instance) instance.user_profile.save() -
How to know the user who created a specific item in Django?
Is it possible to get the id of the user who created a specific item, no matter what it, in Django? I have a site where when the users are authenticated can access a form and submit a new item. Can I retrieve who created what without adding an extra 'submitted by' Event.objects.filter(owner=self.kwargs['pk']) (which gives me name 'self' is not defined )? -
Input field of django form not showing
I am fairly new to Django and am following the try django 1.10 series by CodingEntrepreneurs on youtube and therefore, am unable to solve the problem. I am only seeing the submit button, while the input field is not showing. Below is the code that I am working on. forms.py from django import forms class SubmitUrlForm(forms.Form): url = forms.CharField(label="Submit Url") views.py from .forms import SubmitUrlForm def home_view_fbv(request, *args, **kwargs): if request.method == 'POST': print(request.POST) return render(request, "app/home.html", {}) class HomeView(View): def get(self, request, *args, **kwargs): the_form = SubmitUrlForm() context = { "title": "Submit Url", "form": the_form } return render(request, "app/home.html", context) def post(self, request, *args, **kwargs): form = SubmitUrlForm(request.POST) if form.is_valid(): print(form.cleaned_data) return render(request, "app/home.html", {}) app/home.html <div style= 'width: 800px; margin: 0 auto;'> <h1> {{ title }} </h1> <form method = 'POST' action = '.'> {% csrf_token %} {{form.as_p}} <input type= 'submit' value= 'Shorten' > </form> </div> -
Python - Django - pyexcel-xlsx - Could not able to import the Data from Two different sheets into two Models
Urgent Help: Trying to Import data from two sheets in a XLSX file to two different models - Not able to lead the Data. I am using pyexcel package for the importing xlsx data. I am following http://django.pyexcel.org/en/latest/ Note: I have tried to load the data from single sheet & Single Model. This was successfully loaded with out any issue. But, I am getting the issue when importing the two sheet data into two different models(With Foreign Key relation) Thanks Manoj R -
Passing Information Through a URL In DJANGO
I recently asked a question about how I would automatically assign a foreign key to a model in Django and generally the answers were about passing information through the URL, how would I go about doing this. Thanks for your help. -
How to properly render an ' if ' condition with choices in HTML, Django
Hello I have a post model with visibility choices, I want only the post with public visibility to be shown in the homepage, but I tried to call the object in different ways but it isn't working. Please do have a look at the code models PUBLIC = 'PU' PRIVATE = 'PR' ONLY_ME = 'ME' POST_VISIBILITY = (('PUBLIC', 'Public'), ('PRIVATE', 'Private'), ('ONLY_ME', 'Only me')) class Post(models.Model): title = models.TextField(max_length=5000, blank=False, null=False) post_date = models.DateTimeField(auto_now_add=True, verbose_name="Date Posted") updated = models.DateTimeField(auto_now_add=True, verbose_name="Date Updated") likes = models.ManyToManyField(settings.AUTH_USER_MODEL, related_name='post_likes', blank=True) user = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.CASCADE) slug = models.SlugField(blank=True, unique=True, max_length=255) visibility = models.CharField(choices=POST_VISIBILITY, max_length=10, default=PUBLIC) homepage {% for post in posts %} {% if post.visibility == 'PUBLIC' %} <!--This seems to have a problem --> I want only the public posts to be shown in the homepage, even though the post has been given visibility as public through admin panel, no posts are showing in the homepage. Please do let me know how can I use this condition with various choices. Thanks in advance! -
drf-yasg How to update the params object in swagger.json file for endpoint urls
I am new to drf-yasg (swagger genrator for django rest framework). My current generated swagger.json file looks like this: { "swagger": "2.0", "info": { "title": "Delta-MVP-API", "description": "Backend API to support delta platform", "version": "v1" }, "basePath": "/", "consumes": [ "application/json" ], "produces": [ "application/json" ], "securityDefinitions": { "Basic": { "type": "basic" } }, "security": [ { "Basic": [] } ], "paths": { "/cards/{id}/": { "get": { "operationId": "cards_read", "description": "", "parameters": [], "responses": { "200": { "description": "", "schema": { "$ref": "#/definitions/Card" } } }, "tags": [ "cards" ] }, "delete": { "operationId": "cards_delete", "description": "", "parameters": [], "responses": { "204": { "description": "" } }, "tags": [ "cards" ] }, "parameters": [ { "name": "id", "in": "path", "required": true, "type": "string" } ] }, }, "definitions": {...} } I would like to add a new key ('x-example') to the the params object inside paths./cards/{id}/.parameters drf-yasg documentation says that we can do this by add the @swagger_auto_schema decorator to the Viewset methods. id = openapi.Parameter('id', openapi.IN_PATH, type=openapi.TYPE_STRING, description='id', required=True, **{'x-example': '234'}) @swagger_auto_schema(manual_parameters=[id]) This however updates the parameters object inside the mehods ('get', 'put', etc..) objects 'paths'.'/cards/{id}/'.'get'.'parameters' Is there a way to update the parameters object directly inside the url … -
getting code 400 message Bad request syntax , after post from flutter
getting code 400 message Bad request syntax , after post from flutter with postman request send and no problem but with flutter id Post Map data to Django server and get this error [19/May/2020 14:58:13] "POST /account/login/ HTTP/1.1" 406 42 [19/May/2020 14:58:13] code 400, message Bad request syntax ('32') [19/May/2020 14:58:13] "32" 400 - Django @api_view(['POST']) def login_user(request): print(request.data) if request.method == 'POST': response = request.data username = response.get('username') password = response.get('password') if password is not None and username is not None: user = authenticate(username=username, password=password) if user is not None: create_or_update_token = Token.objects.update_or_create(user=user) user_token = Token.objects.get(user=user) return Response({'type': True, 'token': user_token.key, 'username': user.username}, status=status.HTTP_200_OK) else: return Response({'type': False, 'message': 'User Or Password Incorrect'}, status=status.HTTP_404_NOT_FOUND) else: return Response({'type': False, 'message': 'wrong parameter'}, status=status.HTTP_406_NOT_ACCEPTABLE) else: return Response({'type': False, 'message': 'method is wrong'}, status=status.HTTP_405_METHOD_NOT_ALLOWED) flutter Future<dynamic> postGoa(String endpoint, Map data)async{ Map map = { "username":"user", "password":"password" }; var url = _getUrl("POST", endpoint); var client = new HttpClient(); HttpClientRequest request = await client.postUrl(Uri.parse(url)); request.headers.set('content-type', 'application/json'); request.headers.set('Authorization', 'Bearer '+ athenticated ); request.add(utf8.encode(json.encode(map))); HttpClientResponse response = await request.close(); String mydata= await response.transform(utf8.decoder).join(); client.close(); return mydata; } } after add request.add(utf8.encode(json.encode(map))); i get error in Django console -
No web processes running while deploying django project
i'm trying to deploy my django website on heroku... when i type ---->git push heroku master(it's running fine) ,but it is not rendering my home page of my site. and if i type command----->heroku logs then it's like, 2020-05-19T10:09:02.516378+00:00 app[api]: Release v1 created by user rajparmar23801@gmail.com 2020-05-19T10:09:02.733920+00:00 app[api]: Enable Logplex by user rajparmar23801@gmail.com 2020-05-19T10:09:02.516378+00:00 app[api]: Initial release by user rajparmar23801@gmail.com 2020-05-19T10:09:02.733920+00:00 app[api]: Release v2 created by user rajparmar23801@gmail.com 2020-05-19T10:09:25.000000+00:00 app[api]: Build started by user rajparmar23801@gmail.com 2020-05-19T10:10:13.527798+00:00 app[api]: @ref:postgresql-animated-29167 completed provisioning, setting DATABASE_URL. by user rajparmar23801@gmail.com 2020-05-19T10:10:13.513153+00:00 app[api]: Running release v3 commands by user rajparmar23801@gmail.com 2020-05-19T10:10:13.527798+00:00 app[api]: Release v4 created by user rajparmar23801@gmail.com 2020-05-19T10:10:13.513153+00:00 app[api]: Attach DATABASE (@ref:postgresql-animated-29167) by user rajparmar23801@gmail.com 2020-05-19T10:10:13.824421+00:00 app[api]: Release v5 created by user rajparmar23801@gmail.com 2020-05-19T10:10:13.824421+00:00 app[api]: Deploy 1a2f93e6 by user rajparmar23801@gmail.com 2020-05-19T10:10:23.000000+00:00 app[api]: Build succeeded 2020-05-19T10:16:14.542057+00:00 heroku[router]: at=error code=H14 desc="No web processes running" method=GET path="/" host=whatwilldoapp.herokuapp.com request_id=d12ca631-fcbc-4240- b823-d24d2fa373d6 fwd="27.61.152.130" dyno= connect= service= status=503 bytes= protocol=https 2020-05-19T10:17:27.847271+00:00 heroku[router]: at=error code=H14 desc="No web processes running" method=GET path="/" host=whatwilldoapp.herokuapp.com request_id=cbe42696-4611-42f7- aa2a-9c90912e43d9 fwd="27.61.152.130" dyno= connect= service= status=503 bytes= protocol=https -
How to Represent Data in Django with Django Querysets
Model Data Format I have a Django Model which have data similar to the above image data Structure. Now I want to represent the Data in my HTML Template according to the Following Structure. Date & Labour Wise Data Representation & Labour Wise Data Representation Note - in the 3rd Image "Labour Wise data Representation"..There are certain additional fields added like "Per day Salary" & some Calculation of Salary, Net Salary, EPF & ESIC etc. Any Help, How can I get this Done in Django? -
Problem in SECRET_KEY and get SyntaxError: invalid syntax
I am beginner in django I want to print the path template in setting.py file , I am in root setting file and added below code to setting.py file print(os.path.dirname(os.path.abspath(__file__))) But I receive below error (dj1.1) E:\Dropbox\CS\Project\Project\django\dj_gen_name\gen_fake_name\gen_fake_name>python settings.py File "settings.py", line 25 SECRET_KEY='%)x*i)2o#8-a$&64efw*lfu35&8cz^xkmil16mz=rkxm=)7-@m' ^ SyntaxError: invalid syntax Please see setting.py file in below import os # Build paths inside the project like this: os.path.join(BASE_DIR, ...) BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__))) print(os.path.dirname(os.path.abspath(__file__))) # Quick-start development settings - unsuitable for production # See https://docs.djangoproject.com/en/1.11/howto/deployment/checklist/ # SECURITY WARNING: keep the secret key used in production secret! SECRET_KEY='%)x*i)2o#8-a$&64efw*lfu35&8cz^xkmil16mz=rkxm=)7-@m' # SECURITY WARNING: don't run with debug turned on in production! DEBUG=True ALLOWED_HOSTS=[] # Application definition INSTALLED_APPS=[ 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'gen_fake_app', ] -
Load a new database on the Django Template page
I'm a novice at starting coding. What I want is to make a small page in the library. The first screen on the page calls up a row with a database id value of 1. When you print out each item and click the next button at the bottom, The id value calls up the database value with number 2. I'd like to print out each item. The current setting is... views.py from django.shortcuts import render from django.http import HttpResponse from .models import Macro # Create your views here. def cmacroMacro(request): macro_data = Macro.objects.all() context = {'macro_data':macro_data} return render(request, 'macro_pjt/registerMacro.html', context) models.py from django.db import models # Create your models here. class Macro(models.Model): title = models.CharField(max_length=50) pro = models.CharField(max_length=100) pp = models.CharField(max_length=40) pp_i = models.CharField(max_length=1000) res = models.CharField(max_length=10000) link = models.CharField(max_length=500) def __str__(self): return self.pro html <body> <section> <div>a / b</div> <textarea cols="30" id="aa" placeholder=""></textarea> <textarea cols="30" id="bb" placeholder=""></textarea> <div>c</div> <textarea cols="70" id="title" placeholder=""></textarea> <div>d</div> <textarea cols="70" id="pro" placeholder=""></textarea> <div>e</div> <textarea cols="70" id="pp" placeholder=""></textarea> <div>f</div> <textarea cols="70" id="pp_i" placeholder=""></textarea> <div>g</div> <textarea cols="70" id="contents" placeholder=""></textarea> <div>h</div> <textarea cols="70" id="res" placeholder=""></textarea> <div>i</div> <textarea cols="70" id="link" placeholder=""></textarea> </section> I'd like to place the databases in the textara tag. The codes were all messed … -
I use Django as a server, and implement Face Recognition function by tensorflow. But i can't upload > 10,000 files to APP ENGINE service :(
I use python package as follow: Django==2.1.4 PyMySQL==0.9.3 opencv-python==4.2.0.34 keras==2.2.5 tensorflow==1.14 pandas==1.0.1 matplotlib==3.1.3 imageio==2.6.1 I need to edit codes in tensorflow's source file, like tensorflow_backend.py. So, when i use env for my django project, i should use this specific env for this project. But, it will cause problem about the count of project's files will over 20,000. Then, If i upload this project to APP ENGINE ,it will failed because of the limit of 10,000. I tried to ignore some files before upload to APP ENGINE, and also tried to upload env folder to Cloud Storage(It's impossible). But it not work for my project. So, i wonder if i can solve this problem by any other function. Can anyone helps? Thank you!!! -
Django objects.filter with list and 5 instances from each match
I have a scenario where I have a Property model which has an attribute of rating. The Property model has thousands of properties with different ratings. I need to retrieve properties from db based on the following criteria, 1) If I have a rating_list = [5, 4, 1, 2, 3, unrated] I know I can easily achieve it by doing Property.objects.filter(rating__in=rating_list)[:50] The issue is that since I have thousands of properties of different ratings there is a change that the above query returns 50 properties of only 5 ratings, while I need 10 properties for each rating in the filter. 2) Another requirement is I want the returned results to be exactly in the same order as given in the rating_list. For e.g, the queryset should contain the first 10 properties of rating 5 and next 10 for rating 4 and next rating 1 so on and so forth. 3) Since we have thousands of properties we want to do it in a single query not in more than a single query. Is there any solution to achieve this or what could be a possible solution. -
Django: Count objects by month
I studied the Django docu and tried many examples but it still doesn't work, though it should be very easy, actually. This is my model: class Dummy(models.Model): timestamp = models.DateTimeField() I have some sample objects which I am able to list via the shell like that: % python manage.py shell Python 3.7.7 (default, Mar 10 2020, 15:43:33) [Clang 11.0.0 (clang-1100.0.33.17)] on darwin Type "help", "copyright", "credits" or "license" for more information. (InteractiveConsole) >>> from conv.models import Dummy >>> dummy = Dummy.objects.order_by('timestamp') >>> for d in dummy: ... print(d.id, d.timestamp) 6 2019-05-01 07:00:06+00:00 4 2020-04-01 22:00:00+00:00 5 2020-04-15 04:00:00+00:00 1 2020-05-17 09:42:00+00:00 2 2020-05-18 09:42:15+00:00 3 2020-05-19 09:42:21+00:00 >>> Now I want to count the objects by year / month. Filtering by year only works: >>> Dummy.objects.filter(timestamp__year='2020').count() 5 But filtering by month doesn't work: >>> Dummy.objects.filter(timestamp__month='5').count() 0 Actually the result should be 4. What's wrong?