Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
django,A server error occurred. Please contact the administrator
This Is My settings.py """ Django settings for login project. Generated by 'django-admin startproject' using Django 1.9.7. For more information on this file, see https://docs.djangoproject.com/en/1.9/topics/settings/ For the full list of settings and their values, see https://docs.djangoproject.com/en/1.9/ref/settings/ """ 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__))) # Quick-start development settings - unsuitable for production # See https://docs.djangoproject.com/en/1.9/howto/deployment/checklist/ # SECURITY WARNING: keep the secret key used in production secret! SECRET_KEY = '0^q9&^oblkc28287hb-2ub3pnyo9nub@-@=m56)g*mn_u8m@14' # SECURITY WARNING: don't run with debug turned on in production! DEBUG = False ALLOWED_HOSTS = ['localhost', '127.0.0.1', '111.222.333.444', 'mywebsite.com'] # Application definition INSTALLED_APPS = [ 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'django.contrib.admin', 'login', 'django_filters', 'bootstrap3', ] MIDDLEWARE_CLASSES = [ 'django.middleware.security.SecurityMiddleware', 'django.contrib.sessions.middleware.SessionMiddleware', 'django.middleware.common.CommonMiddleware', 'django.middleware.csrf.CsrfViewMiddleware', 'django.contrib.auth.middleware.AuthenticationMiddleware', 'django.contrib.auth.middleware.SessionAuthenticationMiddleware', 'django.contrib.messages.middleware.MessageMiddleware', 'django.middleware.clickjacking.XFrameOptionsMiddleware', ] ROOT_URLCONF = 'login.urls' 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', ], }, }, ] WSGI_APPLICATION = 'login.wsgi.application' # Database # https://docs.djangoproject.com/en/1.9/ref/settings/#databases DATABASES = { 'default': { 'ENGINE': 'django.db.backends.sqlite3', 'NAME': 'db.sqlite3' } } # Password validation # https://docs.djangoproject.com/en/1.9/ref/settings/#auth-password-validators AUTH_PASSWORD_VALIDATORS = [ { 'NAME': 'django.contrib.auth.password_validation.UserAttributeSimilarityValidator', }, { 'NAME': 'django.contrib.auth.password_validation.MinimumLengthValidator', }, { 'NAME': 'django.contrib.auth.password_validation.CommonPasswordValidator', }, { 'NAME': 'django.contrib.auth.password_validation.NumericPasswordValidator', }, ] # Internationalization # https://docs.djangoproject.com/en/1.9/topics/i18n/ LANGUAGE_CODE … -
How show embed content in Django Templates
I wanted to know how to show url embed content in django template taken from database -
Pagination in django rest, ListAPIView
i'm new in django and i have a little problem in the pagination of objects. my model: class FacebookBien(models.Model): uid = models.IntegerField(primary_key=True) ref_agence = models.IntegerField() loyer = models.FloatField() prix = models.FloatField() ville = models.CharField(max_length=200) code_postal = models.CharField(max_length=200) ref_type_bien = models.IntegerField() surface_totale = models.FloatField() source = models.CharField(max_length=200) nombre_de_pieces = models.IntegerField() date_modification = models.DateTimeField() class Meta: managed = False # db_table = 'public\".\"bien_recherche' db_table = 'recette_facebook\".\"vue_facebook_bien_recherche' my view: class BienAgence(generics.ListAPIView): queryset = FacebookBien.objects pagination_class = SmallPagesPagination def get(self, request, *args, **kwargs): res = request.GET if FacebookBien.objects.filter(ref_agence=int(kwargs['ref_agence'])).exists(): toto = self.queryset.filter(ref_agence=int(kwargs['ref_agence'])) if (res['type'] == 'bien'): toto = toto.filter(prix__gte=int(res['p_mini'])) toto = toto.filter(prix__lte=int(res['p_maxi'])) if (res['prix'] == 'croissant'): toto = toto.order_by('prix') elif (res['prix'] == 'decroissant'): toto = toto.order_by('-prix') else: toto = toto.filter(loyer__gte=int(res['p_mini'])) toto = toto.filter(loyer__lte=int(res['p_maxi'])) if (res['prix'] == 'croissant'): toto = toto.order_by('loyer') elif (res['prix'] == 'decroissant'): toto = toto.order_by('-loyer') if (res['surface'] == 'croissant'): toto = toto.order_by('surface_totale') elif (res['surface'] == 'decroissant'): toto = toto.order_by('-surface_totale') elif (res['date'] == 'croissant'): toto = toto.order_by('date_creation') elif (res['date' == 'decroissant']): toto = toto.order_by('-date_creation') toto = toto.filter(surface__gte=int(res['s_mini'])) toto = toto.filter(surface__lte=int(res['s_maxi'])) serializer = FacebookBienSerializer(toto, many=True) # noqa return Response(serializer.data) else: return Response(None) my pagination.py: class SmallPagesPagination(PageNumberPagination): page_size = 6 The problem is that it does not put me at all 6 objects per page. if … -
Unable to import a repo
I've installed a package using pip install -e git+git://... which is quite expectedly cloned into ./src. Does anyone know how to import it in the django code? All of the (importable) external libraries are in ./lib/python2.7/site-packages, but my code can't seem to see packages in ./src though. Any thought appreciated. -
Django: let request.FILES.get() return an empty string even if no file selected
I have the following HTML form: <form ... enctype="multipart/form-data"> <input name=title> <input type=file name=attachment> <input name=title> <input type=file name=attachment> ... And in Django: titles = request.POST.getlist('title') files = request.FILES.getlist('attachment') The problem is: the user may or may not select a file for each title; hence, the lengths of titles and files may not be the same. Is there a way to force <input type=file...> to return an empty string instead of nothing, such that the lengths of the two lists are always the same? Otherwise, how do I map between the two lists? -
How can I loop through all the properties of an python object in django templates
I have django template and I get a some object. I want apply for in cycle for all atributes this object. {% for point in Object %} <h1>{{ Object[point] }}</h1> {% endfor %} -
Django server 403 Forbidden: incorrect proxy
I've a problem with django server, namely: Server has started correctly: System check identified no issues (0 silenced). November 10, 2017 - 13:39:31 Django version 1.11.4, using settings 'etTagGenerator.settings' Starting development server at http://127.0.0.1:8000/ Quit the server with CONTROL-C. But i'm not able to open it in browser: 403 Forbidden: incorrect proxy service was requested I'm using firefox. Proxy on my machine is set, firefox doesn't use proxy for localhost and 127.0.0.1 -
Django: Changing UTC to timezone aware
I have start_date of DateField() which is in utc.I want to convert it to timezone aware object I tried writing {{ start_date|timezone:'Asia/Calcutta' }} It displays nothing.Is timezone only for DateTimeField()?How can I use it on DateField(). -
About virtualenv and version of python?
I need help in understanding with venv. I have installed venv with virtualenv venv -p python3.6. I have activated it (venv) and install django pip django`install django` And so, when I work with my project should I always activate venv or not? Because I run my manage.py without venv and using python2, but I need python3. And then I run with active venv with python3 I got mistakes like this: ModuleNotFoundError: No module named 'forms' -
What's an instance of class-based views
I am learning Django's class-based views. I don't understand what's the instance of class Views For example: from django.http import HttpResponse from django.views import View class MyView(View): def get(self, request): # <view logic> return HttpResponse('result') What's the instance of class 'MyView' during this request-and-respond process? -
Django - multiple fields lookup [duplicate]
This question already has an answer here: Multiple lookup_fields for django rest framework 2 answers I've an endpoint that accepts either the uuid or the phonenumber of the user url(r'^(?P<uuid>[0-9A-Fa-f+-]+)/$', view_name.as_view()), Now, I've a queryset that filter accordingly. Here it is. class UserDetails(RetrieveUpdateAPIView): serializer_class = UserSerializer lookup_field = 'uuid' def get_queryset(self): """ Over-riding queryset. Filter user based on the user_id(Works for both msisdn & uuid). """ msisdn_or_uuid = self.kwargs[self.lookup_field] queryset = Users.objects try: # checking if the forwarded param is user_id or msisdn. UUID(msisdn_or_uuid) instance = queryset.filter(uuid=msisdn_or_uuid) except ValueError: instance = queryset.filter(msisdn=msisdn_or_uuid) print instance # prints a queryset. But returns 404. return instance Now the problem is whenever phone number is passed, it returns 404 not found. But the objects clearly exist. Is there any setting in DRF that filters on two or more fields simultaneously without over-riding the get_queryset.?? I found a related question, but couldn't make it work. Where am I going wrong? -
Django Mysql Error 1045(28000) access denied for user ODBC@localhost
I know there are a lot of questions concerning the Access denied error for Django, but none of them is helping. What is the configuration: Windows Server 2012 MySQL 5.7 Django with anaconda I am doing basically the tutorial and I have changed the settings.py to DATABASES = { 'default': { 'ENGINE': 'django.db.backends.mysql', 'NAME': 'mysite', 'User': 'User4711', 'Password': 'xxxx', 'Host': 'localhost', 'Port': '3306', } } I have tried: Creating a database, creating a user root or ODBC and granting all privileges + flushing them and restarting MySQL starting mysql with options -uroot -pXXXX works fine but no chance to do sth with Django on the DB Executing python manage.py makemigrations polls I got the error: The above exception was the direct cause of the following exception: Traceback (most recent call last): File "manage.py", line 22, in <module execute_from_command_line(sys.argv) File "C:\Users\User4711\AppData\Local\Continuum\anaconda3\lib\site- packages\django\core\management\__init__.py", line 364, in execute_from_command_line utility.execute() File "C:\Users\User4711\AppData\Local\Continuum\anaconda3\lib\site- packages\django\core\management\__init__.py", line 356, in execute self.fetch_command(subcommand).run_from_argv(self.argv) File "C:\Users\User4711\AppData\Local\Continuum\anaconda3\lib\site- packages\django\core\management\base.py", line 283, in run_from_argv self.execute(*args, **cmd_options) File "C:\Users\User4711\AppData\Local\Continuum\anaconda3\lib\site- packages\django\core\management\base.py", line 327, in execute self.check() File "C:\Users\User4711\AppData\Local\Continuum\anaconda3\lib\site- packages\django\core\management\base.py", line 359, in check include_deployment_checks=include_deployment_checks, File "C:\Users\User4711\AppData\Local\Continuum\anaconda3\lib\site- packages\django\core\management\commands\migrate.py", line 61, in _run_checksissues = run_checks(tags=[Tags.database]) File "C:\Users\User4711\AppData\Local\Continuum\anaconda3\lib\site- packages\django\core\checks\registry.py", line 81, in run_checks new_errors = check(app_configs=app_configs) File "C:\Users\User4711\AppData\Local\Continuum\anaconda3\lib\site- … -
Select one record from related table if exists, else return None
I have this two models: class Box(models.Model): class BoxImages(models.Model): box=models.ForeignKey(Box) img=models.ImageField() cover=models.IntegerField(default=0) Only one image can be a cover image for a box and a box might not have any images at all. What I want now is to get list of boxes along with their cover image. But django uses inner join and brings boxes that have corresponding cover images only. Box.objects.filter(box_boximages__cover=1).values('id','box_label') How do I force it to go with left join or left outer join since i read the ORM decides on its own which join to use? -
Using a Django profile field to restrict queryset of a list view
I want to use a field in the Profile model of a logged in user to restrict the queryset used in a Django class based view. My models are: # User profile info class Profile(models.Model): # Relationship Fields user = models.OneToOneField(User, on_delete=models.CASCADE) school = models.ForeignKey('eduly.School', default=1) notes = models.TextField(max_length=500, blank=True) @receiver(post_save, sender=User) def create_user_profile(sender, instance, created, **kwargs): if created: Profile.objects.create(user=instance) @receiver(post_save, sender=User) def save_user_profile(sender, instance, **kwargs): instance.profile.save() and class School(models.Model): # Fields name = models.CharField(max_length=255) address = models.TextField(max_length=500, blank=True) email = models.CharField(max_length=30) phone = models.CharField(max_length=15) contactName = models.CharField(max_length=30) slug = extension_fields.AutoSlugField(populate_from='name', blank=True) created = models.DateTimeField(auto_now_add=True, editable=False) last_updated = models.DateTimeField(auto_now=True, editable=False) class Meta: ordering = ('-created',) def __unicode__(self): return u'%s' % self.slug def __str__(self): return self.name def get_absolute_url(self): return reverse('eduly_school_detail', args=(self.slug,)) def get_update_url(self): return reverse('eduly_school_update', args=(self.slug,)) class Teacher(models.Model): SCHOOL_ADMIN = 0 CLASS_ADMIN = 1 TASK_ADMIN = 2 ROLES = { (SCHOOL_ADMIN, "School administrator"), (CLASS_ADMIN, "Class administrator"), (TASK_ADMIN, "Task administrator") } # Fields name = models.CharField(max_length=255) slug = extension_fields.AutoSlugField(populate_from='name', blank=True) created = models.DateTimeField(auto_now_add=True, editable=False) last_updated = models.DateTimeField(auto_now=True, editable=False) email = models.CharField(max_length=30) roles = models.IntegerField("Role", choices=ROLES, default=1) # Relationship Fields school = models.ForeignKey('eduly.School', ) class Meta: ordering = ('-created',) def __str__(self): return self.name def __unicode__(self): return u'%s' % self.slug def get_absolute_url(self): return reverse('eduly_teacher_detail', … -
Attribute error when sharing Django page to Facebook
I have a share button in my application to Facebook wall. Everything was working fine yesterday. But when I try to share those pages today the title and the description is showing Attribute error. Even though it is showing like that I could share the page to my Facebook wall and could access the page from Facebook. This issue is showing only for few links. When I debug the url I couldn't find any issue and there is nothing complex in the page. I am attaching the image of the error here. -
I need to display summary report in Django admin site. How do I count number of users where gender status is 0 or 1
I am overriding change_list.html and here is what I have in my admin.py file. def changelist_view(self, request, extra_context=None): response = super().changelist_view(request, extra_context=extra_context, ) try: qs = response.context_data['cl'].queryset except (AttributeError, KeyError): return response metrics = { 'male': Count('gender', gender=1), 'female': Count('gender', gender=0), 'total_helpers': Count('id') } response.context_data['helper'] = list( qs.values('gender').annotate(**metrics).order_by('-male') ) return response In my metrics dictionary, i need a way to count where gender is either 0 or 1. -
How to retrieve/access variable from HTML/Javascript in django views to process it?
I am saving the coordinate(generated by click on google map) in the variable "ccc". Now I want to process this variable in Django. How to get its value like we get from HTML input element (for eg. myX = request.POST.get("myInput")) Here is the curtailed code:- <html> <script> google.maps.event.addListener(map, 'click', function(e) { var ccc = e.latLng.lat(); //I want to retreive this variable //ccc = 77.6746784 }); </script> </html> -
Django custom queryset and export
I have a custom django queryset class, which I use together with custom manager to easly filter objects with chaining. I wanted to add custom method to this class to save its result as a file. However, I am not sure if I am doing it right. How can I get list of objects inside as_file method? class EntryQuerySet(models.QuerySet): def as_file(self, filename='export.xls'): # data = ??? how can I get results here??? print('exporting as {}'.format(filename)) def active(self): return self.filter(status__in=[1, 4, 5]) def with_email(self): return self.filter(contact__email__isnull=False) def by_city(self, city): return self.filter(address__city__icontains=city) def in_next_days(self, days=7): now = datetime.datetime.today() delta = now + relativedelta.relativedelta(days=days) return self.filter(start_date__gte=now, start_date__lte=delta) def in_last_days(self, days=7): now = datetime.datetime.today() delta = now - relativedelta.relativedelta(days=days) return self.filter(start_date__gte=delta, start_date__lte=now) class EntryManager(models.Manager): def get_queryset(self): return EntryQuerySet(self.model, using=self._db) def active(self): return self.get_queryset().active() def by_city(self, city): return self.get_queryset().by_city(city) def with_email(self): return self.get_queryset().with_email() def in_next_days(self, days): return self.get_queryset().in_next_days(days) def in_last_days(self, days): return self.get_queryset().in_last_days(days) I use this as follows: entries = Entry.objects.active().by_city('My city').in_next_days(5) And I want something like: entries = Entry.objects.active().by_city('My city').in_next_days(5).as_file('myfilename.xls') How can I achieve this? -
Django application not responding while running with gunicorn and wsgi
I have developed a django application and it is running fine with the manage.py, but when I am running it with below command gunicorn project_name.wsgi:application Aplication started fine with link localhost:8000 but when clicking on next process in application it is getting stuck i.e not responding just keep waiting for next page. the log output is [2017-11-10 16:07:19 +0530] [2080] [INFO] Starting gunicorn 19.6.0 [2017-11-10 16:07:19 +0530] [2080] [INFO] Listening at: http://127.0.0.1:8000 (2080) [2017-11-10 16:07:19 +0530] [2080] [INFO] Using worker: sync [2017-11-10 16:07:19 +0530] [2087] [INFO] Booting worker with pid: 2087 [<project_name: project_name object>] [<project_name: project_name object>] destination_path /home/ravi/lqiDemo/project_name/media/data/2017/11/8/13/64001859 [2017-11-10 16:07:54 +0530] [2080] [CRITICAL] WORKER TIMEOUT (pid:2087) [2017-11-10 10:37:54 +0000] [2087] [INFO] Worker exiting (pid: 2087) [2017-11-10 16:07:54 +0530] [2128] [INFO] Booting worker with pid: 2128 [2017-11-10 16:08:26 +0530] [2080] [CRITICAL] WORKER TIMEOUT (pid:2128) [2017-11-10 10:38:26 +0000] [2128] [INFO] Worker exiting (pid: 2128) [2017-11-10 16:08:26 +0530] [2135] [INFO] Booting worker with pid: 2135 [2017-11-10 16:08:57 +0530] [2080] [CRITICAL] WORKER TIMEOUT (pid:2135) [2017-11-10 10:38:57 +0000] [2135] [INFO] Worker exiting (pid: 2135) [2017-11-10 16:08:57 +0530] [2152] [INFO] Booting worker with pid: 2152 my wsgi file is: import os from django.core.wsgi import get_wsgi_application os.environ.setdefault("DJANGO_SETTINGS_MODULE", "project_name.settings") application = get_wsgi_application() Is there any solution of … -
Why are my mocked properties not returning the specified value but a MagicMock object and my mocked method is returning the expected value?
I am having trouble getting my test to run as expected. I am trying to mock the return value for two properties and a method for one test but instead of getting the desired return value I get a MagicMock object. I can not figure out how to do this. The thing that irritates me the most is that mocking the method works as expected but for the two properties it does not. Is this a problem I am having because I am using properties or because of the foreignkey relationships or am I doing something basic wrong? I am using Django 1.8, Python2.7, model-mommy, unittests, mock Here are some snippets of my code, I hope they are sufficient to understand the situation: App1 called producers # In producers.models.Producer: @property def is_valid(self): # do stuff return True App2 called customers # In customers.models.Customer: @property def is_valid(self): # do stuff return True def is_allowed_to_purchase_from_producer(producer): # do stuff return True App3 called purchases # In purchases.models class Purchase(BaseModel): producer = ForeignKey('Producers.Producer', related_name="purchase") customer = ForeignKey('Customers.Customer', related_name="purchase") def clean(self): if not self.producer.is_valid: rasie ValidationError if not self.customer.is_valid: raise ValidationError if not self.customer.is_allowed_to_purchase_from_producer(self.producer): raise ValidationError A test for the clean method of the Purchase … -
Bulk create duplicate model plus objects linked by foreign keys linked to that model
I have two database models, let's call them: class People(models.Model): current_job = models.ForeignKey(Job, blank=True) class Job(models.Model): job_title = models.CharField(max_length=512, blank=False) So a People object can have a job which is stored in a separate table and linked via a foreign key. Now I need to duplicate large sections of this table based on a group of people (let's say all people under 40). All properties are same except they're new objects - links should persist between these two new duplicated objects (new_person-new_job should reflect original_person-original_job link). The tables are large; this query results in 1 million objects of people and 400k jobs linked as foreign keys, so I want to bulk create this because doing this in a for loop (for each person, get their job, mint new person, mint new job) takes forever. Is there a smart way of bulk creating these two query sets together such that the foreign key relation persists for the copied items? Any help is appreciated, been driving me nuts last few days! -
Duplicate rows in CSV file Django
In my CSV file duplicate record show. i don't want duplicate record in CSV file. if filtered_record: for row in filtered_record: #print row writer.writerow(row) file_name = 'reports/invoice_reports/' + timezone.now().strftime('%Y_%m_%d_%H_%M_%S.csv') file_path = os.path.join(BASE_DIR, 'static/' + file_name) with open(file_path, 'wb') as f: f.write(response.content) -
While trying to post mptt model via django rest framework getting ValueError: Cannot use None as a query value
Here is the view I'm trying to write tests for: class RestaurantsTreeView(generics.ListCreateAPIView): serializer_class = RestarauntsTreeSerializer def get_serializer_class(self): from rest_framework import serializers if self.request.method == 'GET': return RestarauntsTreeSerializer parent_choices = self.request.user.restaurants_set.filter(status=Restaurants.VISIBLE) class NestedRestaurantDetailSerializer(serializers.ModelSerializer): parent_id = serializers.RelatedField(queryset=parent_choices, allow_null=True, required=False) class Meta: model = Restaurants fields = ("id", "name", "parent_id") return NestedRestaurantDetailSerializer Here is the model I'm trying to create via POST request: from mptt.models import MPTTModel, TreeForeignKey class Restaurants(MPTTModel): name = models.CharField(max_length=255, blank=True, null=True) parent = TreeForeignKey('self', null=True, blank=True, related_name='children', db_index=True) class MPTTMeta: order_insertion_by = ['name'] def __str__(self): return self.name And finally my test: class CreateRestaurantTestCase(TestCase): def setUp(self): self.user = UserFactory.create() self.user.user_permissions.add(Permission.objects.get(codename='add_restaurants')) self.client = APIClient() self.client.force_authenticate(user=self.user) def test_authorization_required(self): response = self.client.post(reverse('api_v1:restaurants_list'), data={ "parent_id": None, "name": "fake restaurant", }) self.assertEqual(response.status_code, 401) that returns that error: Error Traceback (most recent call last): File "project/cafe/tests/api/test_restaurants.py", line 26, in test_required_fields response = self.client.post(reverse('api_v1:restaurants_list'), data={}) File "env/lib/python3.5/site-packages/rest_framework/test.py", line 299, in post path, data=data, format=format, content_type=content_type, **extra) File "env/lib/python3.5/site-packages/rest_framework/test.py", line 212, in post return self.generic('POST', path, data, content_type, **extra) File "env/lib/python3.5/site-packages/rest_framework/test.py", line 237, in generic method, path, data, content_type, secure, **extra) File "env/lib/python3.5/site-packages/django/test/client.py", line 416, in generic return self.request(**r) File "env/lib/python3.5/site-packages/rest_framework/test.py", line 288, in request return super(APIClient, self).request(**kwargs) File "env/lib/python3.5/site-packages/rest_framework/test.py", line 240, in request request = super(APIRequestFactory, self).request(**kwargs) … -
Chrome automatically refresh page after XMLHttpRequest
I have some strange problem with Google Chrome. I build a search field for my website. Therefor i have implemented some JS to get and process the results (see below). The problem is, when I first enter the page with chrome and using the search with "Enter-key", chrome does the following (request from my server): [10/Nov/2017 10:00:56] "GET /app/student/home/ HTTP/1.1" 200 7372 (entering the page) [10/Nov/2017 10:00:59] "GET /api/searchCourse/daf/ HTTP/1.1" 200 95 (search request) [10/Nov/2017 10:00:59] "GET /app/student/home/? HTTP/1.1" 200 737 (reloading -but why?? ) One Firefox (also with "Enterkey") or Chrome using the "Search-button" it looks different, like that. [10/Nov/2017 10:00:59] "GET /api/searchCourse/daf/ HTTP/1.1" 200 95 (entering the page) [10/Nov/2017 10:00:59] "GET /app/student/home/? HTTP/1.1" 200 737 (search request) I also tried debugging this Problem with Chrome, but than it behaves like it should. Also I have to add, this happens only when I first enter the page after login. When I refresh the page it works good. Can some explain this behavior? My JS-Code: var btnSearch = document.querySelector('.search').addEventListener('click', searchCourse); var txtFieldSearch = document.getElementById('searchField').addEventListener('keydown', function (e) { var key = e.which || e.keyCode; if (key === 13) { searchCourse(); } }); function searchCourse() { document.querySelector('.my-node').style.display = 'none'; var input = … -
Django rest framework filtering by dateTime
I'm trying to filter by dateTime in django restFramework. it seems that it does not work, because it does not filter, it always brings the same results. Model.py #Modelo Fechas que formara parte del modelo horario class Fecha(models.Model): fecha_inicio = models.DateTimeField(blank=True, default='') fecha_fin = models.DateTimeField(blank=True, default='') def __str__(self): return self.fecha_inicio, self.fecha_fin #Modelo Horario class Horario(models.Model): profesional = models.ForeignKey(Profesional, unique=True) fechas = models.ManyToManyField(Fecha) def __str__(self): return self.profesional.user.username View.py class FechaList(generics.ListAPIView): serializer_class = HorarioSerializer queryset = Horario.objects.all() filter_class = HorarioFilter Urls.py url(r'^horario/$', views.FechaList.as_view()) Filters.py class HorarioFilter(django_filters.FilterSet): date_start = django_filters.DateTimeFilter(name="fecha_inicio", lookup_type="gte") class Meta: model = Horario fields = ['date_start'] Thank you!!!! :)