Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
How to check for update field
I have fields promotion = models.BooleanField(default=False) end_promotion = models.DateTimeField(blank=True,null=True) Promotion field is true until some date, what is the best way to check if promotion is finished? Should i put it into cron or is it a better way? -
Django "NameError: name 'Album' not defined"
I am trying to run see and manipulate a simple django database but the error from the Django Shell is saying one of my models isn't defined. Most of the questions with errors similar to mine are due to people referencing a model before declaring it. However, I'm not referencing any other model in Album. models.py from __future__ import unicode_literals from django.db import models class Album(models.Model): artist = models.CharField(max_length=250) title = models.CharField(max_length=500) genre = models.CharField(max_length=100) logo = models.CharField(max_length=1000) class Song(models.Model): album = models.ForeignKey(Album, on_delete=models.CASCADE) file_type = models.CharField(max_length=10) title = models.CharField(max_length=250) The error I am getting: NameError: name 'Album' is not defined Any idea what could the the cause of this error? For reference, I'm following thenewboston's django tutorial here. -
template does not exist, when invalid data is feed in form
In part_detail_view I am passing part_stock_form() to the template so that I will show the form to add stock in the DetailView. class part_detail_view(DetailView): model = part_list context_object_name = 'part_detail' template_name = 'part_detail.html' def get_context_data(self, **kwargs): context = super(part_detail_view, self).get_context_data(**kwargs) context['my_list'] = populate_nav_bar() context['form'] = part_stock_form() return context The CreateView of stock is given below class stock_add_view(CreateView): model = part_stock fields = ['part_id','entry_date','supplier','amount','remaining'] success_url = reverse_lazy('parts:part_list') and the template of 'part_detail.html' is <div> {{ part_detail.part_id}}<br> {{ part_detail.part_name }}<br> {{ part_detail.cost }}<br> {{ part_detail.available_quantity }} </div> <div > <form method="post" action="{% url 'parts:stock_add_view'%}"> {% csrf_token %} {{ form.errors }} {{ form }} <input type="submit"> </form> </div> when adding the stock through stock_add_view() the stock is added successfully but when invalid input is entered the error is shown like this -
Django ORM manually disconnect when running outside of Django
After connecting to the Django ORM as described here and here. What's the best practice to avoid a runtime error if there already is an active connection? Currently if you call django.setup() again you get an exception: RuntimeError: Settings already configured. Is there a way to disconnect gracefully or should this be try/catched? -
How to pass parameters from my form action to a view? Django
This is my view function: It takes one kwarg i.e block_id def write_comment(request, block_id): block=get_object_or_404(Block, pk=block_id) if request.method=='POST': form=Comment_form(request.POST) if form.is_valid(): #do stuff else: return render(request,'writers_block/index.html', {'comment_form':form, 'block_form':Block_form()}) To access it from my template form I use: {%for block in block_list%} <form method="post" action="{%url 'write_comment' block_id=block.id%}"> {%csrf_token%} {{comment_form}} <input type="submit" value="submit"> </form> {%endfor%} Somehow I'm always getting a NoReverseMatch saying that write_comment with that arguments is not found: The urlpattern is: url(r'^write_comment', writers_block.views.write_comment, name='write_comment') Can you help me? -
Reading JSON from decoded POST request
I'm trying to receive data through a webhook that is url-encoded. I decoded it using these two lines: txt = request.body decoded = json.loads(dumps(repr(parse_qs(txt)))) And I'm receiving this as the output: { b'receiver':[ b'1216******8' ], b'sender':[ b'1415******7' ], b'message':[ b'Something new this time' ], b'date':[ b'1499608381' ], b'date_utc':[ b'1499622781' ], b'reference':[ b'10273548605' ], b'id':[ b'476b4fc1559626d7d5e5ac4b90888173' ], b'message_id':[ b'7459df31559626d7d5cab31m07097860' ], b'recipient':[ b'1216*****8' ], b'originator':[ b'1415*****7' ], b'body':[ b'Something new this time' ], b'createdDatetime':[ b'2017-07-09T17:53:01+00:00' ] } How can I read this in Python? I've tried defining each field by its name and get the error TypeError: string indices must be integers But when I try to use numbers (as shown below), I simply get the first, second, third character of the output. UserText.objects.create( id = decoded[0], recipient = decoded[1], originator = decoded[2], body = decoded[3], createdDatetime = decoded[4], ) -
Parse arrays sent with form
See this answer. In short, it transforms: <input type="text" name="object[0][color]" value="red"> <input type="text" name="object[0][doors]" value="2"> <input type="text" name="object[0][color]" value="green"> <input type="text" name="object[0][doors]" value="4> Into a PHP associative array: 'object' => array( '0'=>array( 'color'=>'red', 'doors'=>'2' ), '1'=>array( 'color'=>'green', 'doors'=>'4' ) ) In Django, I try to do the same, but when I print request.POST, I get: <QueryDict: {'object[0][color]': ['red'], 'object[0][doors]': ['2'], 'object[1][color]': ['green'], 'object[1][doors]': ['4']}> How to convert it to a proper dict? -
Docker + Django + Angular + Heroku + Postgresql - Process exited with status 127, error code=H10 desc=“App crashed”
I am trying to deploy on Heroku my project in Docker with Angular 4 frontend, Django backend and postgresql database. At this moment my files look as shown below. I am note sure if this is done properly? I pushed it using heroku container:push web --app myproject but it doesn't work (Logs). I noticed that in logs there is Process exited with status 127. I have found here 127 Return code from $? that Value 127 is returned by /bin/sh when the given command is not found within your PATH system variable and it is not a built-in shell command. In other words, the system doesn't understand your command, because it doesn't know where to find the binary you're trying to call. Besides, when I was trying different commands I very often were getting error like /bin/sh: 1 not found what I described in this post. Maybe it is a root of the problem? Or eventually there is a problem with ports like in this case? Any other ideas? It seems to me that I was trying everything. I have no idea what is wrong. Logs: 2017-07-08T13:19:48.882112+00:00 heroku[web.1]: Process exited with status 0 2017-07-08T13:20:40.336825+00:00 heroku[run.9745]: Awaiting client 2017-07-08T13:20:40.395900+00:00 heroku[run.9745]: Starting … -
Error with Django database layer outside of Django 1.10.7
I am following the answers on this question using django 1.10, how ever I'm getting following the error: RuntimeError: Model class django.contrib.auth.models.Permission doesn't declare an explicit app_label and isn't in an application in INSTALLED_APPS. I tried adding the app it complains about to INSTALLED_APPS but I still get an error. How can I get my example code below to work? from django.conf import settings DATABASES = {'default': {'ENGINE': 'django.db.backends.postgresql_psycopg2', 'HOST': '', 'NAME': 'mydb', 'PASSWORD': '', 'PORT': '', 'USER': ''}} DATABASES['default']['ATOMIC_REQUESTS'] = True settings.configure( INSTALLED_APPS = ['django.contrib.contenttypes', 'ob_site.strats.apps.StratsConfig'], DATABASES = DATABASES, TIME_ZONE = 'UTC') import django django.setup() # error is thrown here -
How to get remote ip in Django forms.py
I have customized forms.py in virtual environment on path "lib/python3.5/site-packages/django/contrib/auth" and it works great! However I need now to grab remote ip from user in def confirm_login_allowed I know that I need to grab from request but in the class AuthenticationForm where this model is located, the request is overwritten in __init_. Do you know what should I do to get self.request.META['REMOTE_ADDR'] class AuthenticationForm(forms.Form): """ Base class for authenticating users. Extend this to get a form that accepts username/password logins. """ username = UsernameField( max_length=254, widget=forms.TextInput(attrs={'autofocus': True}), ) password = forms.CharField( label=_("Password"), strip=False, widget=forms.PasswordInput, ) error_messages = { 'invalid_login': _( "Please enter a correct %(username)s and password. Note that both " "fields may be case-sensitive." ), 'inactive': _("This account is inactive."), 'IP': _("You tried to login from to much different IP address in last 24 hours. Contact administrator.") } def __init__(self, request=None, *args, **kwargs): """ The 'request' parameter is set for custom auth use by subclasses. The form data comes in via the standard 'data' kwarg. """ self.request = request self.user_cache = None super(AuthenticationForm, self).__init__(*args, **kwargs) # Set the label for the "username" field. self.username_field = UserModel._meta.get_field(UserModel.USERNAME_FIELD) if self.fields['username'].label is None: self.fields['username'].label = capfirst(self.username_field.verbose_name) def clean(self): username = self.cleaned_data.get('username') password … -
Accessing non-static images in Django?
I don't want to store images in static for this Django project because the user will be able to change them from the admin panel. My code looks like: <div class="col-md-3 col-sm-4 col-xs-6"> <img class="img-responsive" src="/galleryimg/first.jpg"/> </div> Where /galleryimg/ is a folder in the root directory of the project, and "first.jpg" is the file that I want to serve. However, this does not load. How can I get it to load? -
Django1.10 issue with loading mp3 file in templates
I want to play an mp3 file in template but the audio is not loading correctly. The audio starts playing but I can't move is forward or backwards. It works fine when I dont use django and use simple html. I am using mediaelement.js as a library but I dont think its a library issue because the same error occurs when I use simple audio tag to load files. I am serving my files using the media url link but the same issue occured when I just placed the test audio file inside the static folder. Whenever I go to the link (/playlist is routed to the view which simply renders the template). I see the following error in the shell... System check identified no issues (0 silenced). July 09, 2017 - 21:25:36 Django version 1.10, using settings 'smart_audio.settings' Starting development server at http://127.0.0.1:8100/ Quit the server with CTRL-BREAK. D:\my_stuff\live\smart_audio\src\media/ /media/ [09/Jul/2017 21:25:37] "GET /playlist HTTP/1.1" 200 1569 [09/Jul/2017 21:25:38] "GET /media/audio/test_audio.mp3 HTTP/1.1" 200 8192 Traceback (most recent call last): File "C:\Python27\lib\wsgiref\handlers.py", line 86, in run self.finish_response() File "C:\Python27\lib\wsgiref\handlers.py", line 128, in finish_response self.write(data) File "C:\Python27\lib\wsgiref\handlers.py", line 212, in write self.send_headers() File "C:\Python27\lib\wsgiref\handlers.py", line 270, in send_headers self.send_preamble() File "C:\Python27\lib\wsgiref\handlers.py", … -
Django Inner Join Queryset where there is no foreign key relation between two tables
Please Help ! I Want to know the inner join Queryset for the below mentioned raw oracle Query : - select PubC.component,PubC.comp_version,PubC.publish_id,PubEv.published_date from PubEv inner join PubC on PubC.publish_id = PubEv.publish_id where PubC.target_branch = 'polaris_dev' and PubC.component = 'aaa' order by PubEv.published_date desc; And the models mentioned in the django project are as follows:- class PubEv(models.Model): vob = models.CharField(max_length=20) target_branch = models.CharField(max_length=60) publish_id = models.IntegerField(primary_key=True) target_branch_label = models.CharField(max_length=50, blank=True, null=True) main_release = models.CharField(max_length=10, blank=True, null=True) published_by = models.CharField(max_length=16) published_date = models.DateTimeField() publish_ddts = models.CharField(max_length=10) unpublished = models.CharField(max_length=1) changeset = models.ForeignKey('CcChangesets') class Meta: managed = False db_table = 'publish_events' class PubC(models.Model): publish_id = models.IntegerField(primary_key=True) vob = models.CharField(max_length=20) target_branch = models.CharField(max_length=60) component = models.CharField(max_length=40) comp_version = models.CharField(max_length=40) class Meta: managed = False db_table = 'publish_contents' -
When creating a database model in Django, how can I create fields that will only accept a month and year, respectively?
If I use something like year_published = models.DateField() then I have to enter in a day and month, in addition to a year. But in this field I only want to enter a year. Likewise, I only want to enter a month in month_published = models.DateField() Any idea how to do this? -
Google app engine my first project
I'm a complete newbie in this field. I am thinking of a system that interfaces the application rest server with the frontend web using multiful App engines. In charts, Main server Frontend web server Mobile api server It's roughly like this. I would like to know if this architecture can be implemented using the app engine. If possible, Do I use three app engine instances? How do they interface with each other? Experts may look at the question a little more... I look forward to your help. -
Why did I have to go to so much trouble to create a date range search field in Django?
I'm feeling stupid because it took me several days to figure out something which should be easy in Django. I have a table and I have a search form for the table. The table has dates. I want to be able to filter the table on a range of dates for the date field. I will post my solution path here, the question is why isn't it easier? So key to the solution is the RangeField class defined here: https://djangosnippets.org/snippets/1104/ Step 1 is save this into a file RangeField.py like so: from django import forms from django.template.loader import render_to_string from django.forms.fields import EMPTY_VALUES from django.utils.translation import ugettext as _ class RangeWidget(forms.MultiWidget): def __init__(self, widget, *args, **kwargs): widgets = (widget, widget) super(RangeWidget, self).__init__(widgets=widgets, *args, **kwargs) def decompress(self, value): return value def format_output(self, rendered_widgets): widget_context = {'min': rendered_widgets[0], 'max': rendered_widgets[1],} return render_to_string('widgets/range_widget.html', widget_context) class RangeField(forms.MultiValueField): default_error_messages = { 'invalid_start': _(u'Enter a valid start value.'), 'invalid_end': _(u'Enter a valid end value.'), } def __init__(self, field_class, widget=forms.TextInput, *args, **kwargs): if not 'initial' in kwargs: kwargs['initial'] = ['',''] fields = (field_class(), field_class()) super(RangeField, self).__init__( fields=fields, widget=RangeWidget(widget), *args, **kwargs ) def compress(self, data_list): if data_list: return [self.fields[0].clean(data_list[0]),self.fields[1].clean(data_list[1])] return None Step 2 in the form define the … -
Perform WHERE 'field' IN (list) query in Django?
To every question, there are many answers. I have a table Vote which contains the upvote/downvotes on all the question and answers. I want to perform a query something like: Select * from vote WHERE username="some username" AND (QID="question" OR AID IN (SELECT AID from Answers WHERE QID="question") class Question(models.Model): QID = models.CharField( default="",max_length=5, primary_key=True) title = models.CharField(max_length=30, default="") description = models.CharField(max_length=1055, default="") date = models.DateTimeField(default=datetime.now, blank=True) username = models.CharField(max_length=30, default="") votes = models.IntegerField(default=0) approved = models.BooleanField(default=False) def __str__(self): return self.title class Answer(models.Model): AID = models.CharField(max_length=5, default="", primary_key=True) QID = models.ForeignKey(Question,on_delete=None) description = models.CharField(max_length=1055, default="") date = models.DateTimeField(default=datetime.now, blank=True) username = models.CharField(max_length=30, default="") votes = models.IntegerField(default=0) approved = models.BooleanField(default=False) def __str__(self): return self.AID class Vote(models.Model): username = models.ForeignKey(User,on_delete=None) QID = models.ForeignKey(Question,on_delete=None, null=True, blank=True) AID = models.ForeignKey(Answer,on_delete=None, null=True, blank=True) vote = models.BooleanField(default=True) def __str__(self): if self.QID is not None: return self.QID.QID+'_'+self.username.username+'_'+str(self.vote) else: return self.AID.AID+'_'+self.username.username+'_'+str(self.vote) P.S. Please note that QID and AID are foreign keys. So they will take instance of Question/Answer Model only. -
Didn't have permission to include file error in django
When i am trying to submit form data, it is throwing an error saying Didn't have permission to include file. currently what my form is doing, its taking input storing it in a temp html file, then creating another html file with multiple versions upon each submit. copying all contents of temp file into the versioned file and later delete the temp file. my views.py def about_experiment(request, ex_link_name): researcher = None study = None exp = get_object_or_404(Experiment,link_name = ex_link_name) high_scores = ScoreItem.objects.filter(experiment=exp,active=True) context = { 'request': request, 'exp':exp, 'high_scores': high_scores, 'awards':AwardItem.objects.filter(experiment=exp,visible=True) } if request.method == 'POST': pi_obj = PrincipalInvestigator.objects.get(user = request.user) form = AboutHelp(request.POST, request.FILES) if form.is_valid(): researcher = form.cleaned_data['researcher'] study = form.cleaned_data['study'] file_var1 = "about_"+ exp.name file_name1 = "about_" + exp.name + ".html" a = settings.EXPERIMENT_DIRS + str(exp.id) + "/" + file_name1 with open(a, 'w') as f: html_template = "<html><head></head><body><p><strong>Researcher: </strong><br><span>" \ + researcher + "</span></p><p><strong>Summary: </strong><br><span>" \ + study + "</span></p></body></html>" f.write(html_template) f.close() try: att = Attachment.objects.get(experiment=exp, name=file_var1, ext="html") att.versions = att.versions + 1 att.version = att.versions att.save() AttachmentEdit.objects.create(attachment=att, version=att.version, pi=pi_obj, tag=att.experiment.current_tag) except Attachment.DoesNotExist: att = Attachment.objects.create(experiment=exp, name=file_var1, ext="html", filetype=getFileType(file_name1)) AttachmentEdit.objects.create(attachment=att, version=att.version, pi=pi_obj, tag=att.experiment.current_tag) copyfiles(exp, a, att.get_current_version()) os.remove(a) #handle_uploaded_file(experiment=exp, file=file_data, filename=att.get_current_version()) return HttpResponseRedirect('/about/%s/' %ex_link_name) else: if exp.about_file: context['about_file'] … -
django how to change account info using UserChangeForm
I'm making a website using django. I was learning 'How to Let superusers Change Account Info Using Forms' by youtube. But, I have a problem to go edit page. member_management.html in management app {% for staff in staff_list %} <tr> <td><a href="{% url "management:edit_staff" staff.id %}">{{ staff }}</a></td> <td>{{ staff.birth }}</td> <td>{{ staff.groups.all.0 }}</td> </tr> {% endfor %} If I click the {{staff}}, the page url changes 'management/member_management' to 'management/member_management/edit_staff/1' ( 1 is the staff id ). But page doesn't go to edit_staff page, rather redirect memeber_management page(this page). my urls.py in management app from django.conf.urls import url, include from management import views urlpatterns = [ url(r'^member_management/', views.member_management, name='member_management'), url(r'^member_management/edit_staff/(?P<staff_id>\d+)', views.edit_staff, name="edit_staff"), ] my views.py in management app from django.conf import settings from django.shortcuts import render, redirect from django.contrib.auth.forms import UserChangeForm from authentication.models import User from staff.models import Member def member_management(request): staff_list = User.objects.all() member_list = Member.objects.all() context = { 'staff_list':staff_list, 'member_list' : member_list, } return render(request, 'management/member_management.html', context) def edit_staff(request, staff_id): staff = User.objects.get(id=staff_id) print("sdf") if request.method == 'POST': form = UserChangeForm(request.POST, instance=staff) if form.is_valid(): form.save() return redirect('member_management') else: staff = User.objects.get(id=staff_id) form = UserChangeForm(instance=staff) context = { 'form' : form, } return render(request, 'management/edit_staff.html', context) What's the problem?? … -
Passing parameters to a view in Django
In my urls.py I have set handler404 to CustomErrorView. CustomErrorView is a generic view which generates a template for an error based on the error message and error code that it receives. Since the handler404 is only raised in the case of a 404 error, how can I send the errorcode = 404 kwarg to CustomErrorView whenever it is raised? Already tried- handler404 = CustomErrorView(errorcode = 404) This causes an "Expected one positional argument, none given error." handler404 = CustomErrorView(request, errorcode = 404) This causes a NameError (Name 'request' is not defined) -
Django - overridden save function won't save parent fields
I'm creating a django app for an education company, and I created a custom user model and two classes (Student and Teacher) that will inherit from the User model through a one-to-one relationship. I'm trying to avoid the situation where a teacher and a student both use the same user object. Thus, I have a user_type char field in my User object, and the idea is when a user is set to a teacher, the field will be updated. Then if I try to make the user a student, it should throw an error. I'm trying to do the check in the clean function - after the clean() function is called in the save() function, the user_type seems to be updated, but when I actually test, it seems user_type is returning a blank string. I'm wondering if someone could point me the right direction. class User(AbstractUser): user_type = models.CharField(max_length=20, choices=USER_TYPES, blank=True) class Teacher(TimeStampedModel): user = models.OneToOneField(settings.AUTH_USER_MODEL, on_delete=models.CASCADE) def clean(self): if self.user.user_type and self.user.user_type !='teacher': raise ValidationError('Some error') else: self.user.user_type = 'teacher' def save(self, *args, **kwargs): self.clean() #this prints 'teacher' print(self.user.user_type) super().save(*args, **kwargs) tests.py #this test fails def test_should_set_user_type_automatically_to_teacher(self): user = User.objects.create(username='tangbj', first_name='Dan') Teacher.objects.create(user=user) teacher = Teacher.objects.get(user__username='tangbj') print(teacher.user.user_type) self.assertEqual(teacher.user.user_type, 'teacher') -
Django websocket channels how to server push while Channels Group is not empty
I have following scenario using django and channels, a client connects via Websocket and wants to subscribe some country news. So internally his subscription request will start a function with a infinite loop sending the country news to the channels group (while the group is not empty). My question is should this infinite loop run in separately thread? Should I use threading module and start a new thread? Thank you. -
django - why is this custom middleware not working
I am building a website using django 1.10. I have written a middleware class to restrict the number of page views for users that are not logged in. I implemented this functionality into a separate application 'pagerestrict' settings.py [Relevant Entry] MIDDLEWARE = [ 'django.middleware.security.SecurityMiddleware', 'django.contrib.sessions.middleware.SessionMiddleware', 'django.middleware.common.CommonMiddleware', 'django.middleware.csrf.CsrfViewMiddleware', 'django.contrib.auth.middleware.AuthenticationMiddleware', 'django.contrib.messages.middleware.MessageMiddleware', 'django.middleware.clickjacking.XFrameOptionsMiddleware', 'pagerestrict.middleware.CheckPageAccessMiddleware', ] Middleware code (middleware.py): from django.http import HttpResponseRedirect from decouple import config class CheckPageAccessMiddleware(object): def __init__(self, get_response): self.get_response = get_response def __call__(self, request): return self.get_response(request) def process_request(self, request): if not request.user.is_authenticated(): current_page_url = request.path_info.lstrip('/') # If path is not root url ('') and path is not exempt from authentication ignore_list = config('PAGE_RESTRICT_PAGE_IGNORES', cast=lambda v: [s.strip() for s in v.split(',')]) if not current_page_url or not any(current_page_url != url for url in ignore_list): # first things first ... if not has_attr(request, 'pages_visited'): request.pages_visited = set() if not has_attr(request, 'page_count'): request.page_count = 0 if current_page_url not in request.pages_visited: request.pages_visited.add(current_page_url) request.page_count += 1 if request.page_count > config('PAGE_RESTRICT_PAGE_LIMIT'): return HttpResponseRedirect(config('PAGE_RESTRICT_REDIRECT_URL')) I tested this by going to my homepage and refreshing the browser several times - the code never seemed to be triggered. What am I missing? -
Django Rest Framework - "Got a `TypeError` when calling `Note.objects.create()'"
When i am trying to POST using the browsable API of DRF, i get the following error: Got a TypeError when calling Note.objects.create(). This may be because you have a writable field on the serializer class that is not a valid argument to Note.objects.create(). You may need to make the field read-only, or override the NoteSerializer.create() method to handle this correctly. I don't know what is generating this error or how to overcome it. Literally spent hours google searching or changing the code. Can someone explain how to overcome this error? (Please note i am new to Django and DRF!) Here is the models.py: from django.db import models from django.utils import timezone from django.contrib.auth.models import User import uuid class Stock(models.Model): ''' Model representing the stock info. ''' user = models.ForeignKey(User) book_code = models.CharField(max_length=14, null=True, blank=True) def __str__(self): return self.book_code class Note(models.Model): ''' Model representing the stock note. ''' user = models.ForeignKey(User) note = models.TextField(max_length=560) stock = models.ForeignKey(Stock, related_name='notes') date_note_created = models.DateTimeField(default=timezone.now) def __str__(self): return self.note This is the views.py: from rest_framework import generics from stocknoter.models import Stock, Note from api.serializers import StockSerializer, NoteSerializer # Create your views here. class StockList(generics.ListCreateAPIView): serializer_class = StockSerializer def get_queryset(self): user = self.request.user return Stock.objects.filter(user=user) … -
How to get related model's field's value in django
I am trying to get user's gender who is in room between start_date and end_date range here is models.py class Profile(models.Model): MALE = 'M' FEMALE = 'F' GENDER_CHOICES = ( (MALE, u'ere'), (FEMALE, u'eme') ) FOOD_TYPE = ( ('Veg', 'Vegeterian'), ('Green', 'Green') ) user = models.OneToOneField(User, related_name="profile", null=True) firstname = models.CharField(max_length=50, null=True) lastname = models.CharField(max_length=50, null=True) phone1 = models.CharField(max_length=50, null=True) phone2 = models.CharField(max_length=50, null=True, blank=True) birthdate = models.DateField(blank=True, null=True) gender = models.CharField(max_length=10, choices=GENDER_CHOICES, null=True) emd_number = models.CharField(max_length=10, null=True) special_situation = models.IntegerField(choices=SITUATION_CHOICES, null=True, blank=True) created_at = models.DateTimeField(auto_now_add=True) email = models.EmailField(blank=True, null=True) city = models.CharField(max_length=20, blank=True) food_type = models.CharField(max_length=50, choices=FOOD_TYPE, blank=True) def __unicode__(self): return self.user.username class Room(models.Model): number = models.CharField(max_length=8, null=True) category = models.ForeignKey(RoomCategory, related_name="rooms") beds = models.PositiveIntegerField(null=True) description = models.TextField(blank=True) size = models.CharField(max_length=2, blank=True) def __unicode__(self): return self.number class Reservation(models.Model): created_at = models.DateTimeField(auto_now_add=True, editable=False) transport_type = models.CharField(max_length=8, blank=True) start_date = models.DateField(null=True) end_date = models.DateField(null=True) total_days = models.PositiveIntegerField(null=True, blank=True) arrival_date = models.DateField(null=True, blank=True) user = models.ForeignKey(User, related_name="customers") room = models.ForeignKey(Room, related_name="reservations") total_payment = models.PositiveIntegerField(null=True, blank=True) total_paid = models.PositiveIntegerField(null=True, blank=True) currently i get the rooms by this query below: queryset = Room.objects.all() if start_date && end_date: queryset = queryset.exclude(reservations__start_date__range=[start_date, end_date], reservations__end_date__range=[start_date, end_date]) how to get user's gender who is in room between dates