Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Exception Value: Field 'id' expected a number but got ''. (Django)
I was trying to code an add photo page on Django but got an error. I was watching this video on youtube to write my own project. I already wrote python manage.py makemigrations and then python manage.py migrate. Unfortunately, it did not work. Here is the "view.py" file: def addPhoto(request): categories = Category.objects.all() if request.method == 'POST': data = request.POST image = request.FILES.get('image') if data['category'] != 'none': category = Category.objects.get(id = data['category']) else: category = None photo = Photo.objects.create( title=Title, category=category, description=data['description'], image=image, ) return redirect('index') context = {'categories':categories} return render(request, 'auctions/newlisting.html', context) Here is the "urls.py" file: from django.urls import path from . import views urlpatterns = [ path("", views.index, name="index"), path("login", views.login_view, name="login"), path("logout", views.logout_view, name="logout"), path("register", views.register, name="register"), path("newlisting", views.addPhoto, name="create_listing"), path('photo/<str:pk>/', views.viewPhoto, name='photo'), ] Here is the "models.py" file: class Category(models.Model): category = models.CharField(max_length = 30) def __str__(self): return f'{self.category}' class Photo(models.Model): class Meta: verbose_name = 'Photo' verbose_name_plural = 'Photos' title = models.CharField(max_length = 60,) category = models.ForeignKey(Category, on_delete=models.SET_NULL, null=True, blank=True) image = models.ImageField(null=False, blank=False) description = models.TextField() def __str__(self): return self.description Here is the "newlisting.html" file: {% extends "auctions/layout.html" %} {% block body %} <div class="m-5"> <div class="container"> <div class="row justify-content-center"> <div class="col-md-6"> <h2>Create Listing</h2> … -
Any beginner friendly tutorial to integrate D3js with django?
I am looking for a tutorial (beginner friendly) to integrate D3js with Django. My objective is to display graphs on my django website using sqlite database. I found very few tutorial on this topic but they are beyond my level. Thanks. -
update foreignkey field in Django
have the following models Class FootballWebsite(models.Model): """Football service website.""" url = models.URLField(validators=[validate_club_url], unique=True) #Football service id = models.CharField(primary_key=True, unique=True) sub_categories = models.ForeignKey(SubCategory, default=1) class SubCategory(models.Model): """Sub Category""" category = models.ForeignKey(Category) name = models.CharField(max_length=50) slug = models.SlugField() and trying to execute the following class Command(BaseCommand): def handle(self, *args, **options): websites = FootballWebsiteDescription.objects.filter(title__in=['title1',' title2']) for website in websites: try: fc = FootballWebsite.objects.filter(id=website.about_id).update(sub_categories_id=88) fc.sub_categories_id = 88 fc.save() and also the following option fc = FootballWebsite.objects.filter(id=website.about_id).update(sub_categories_id=88) to my understanding both ways to update the subcategory id from the default 1 to 88 should work. i can update other fields this way at least, and see this as an example referenced anywhere. i can only find this reference Django: Set foreign key using integer? which indicates i might have run into a bug in my very old Django 1.7 project. Am i missing something very obvious here or is there a work around? much obliged. -
Django: How to customize display based on the logged in user
creating an attendance system where lecturers register and login using their lecturer code and password different lecturers teach different subjects, as such i would like the "subject" page to display only the subjects taught by the specific lecturer currently, the "subject" page displays all subjects present in the database how can i do that? [Source code][1] [1]: https://github.com/Zainab692/Fyp2 -
Checking for data in the database and re-requesting a third-party API
I'm using Django Rest Framework for the following task (I'll write it in detail so that everything is clear): The service must implement a REST API that accepts POST requests as input with content like {"questions_num": integer} . This item is done. After receiving the request, the service, in turn, requests the number of questions specified in the received request from the public API (English questions for quizzes) https://jservice.io/api/random?count=questions_num. This is also done. Further, the received answers should be stored in the database (or Postgres or Sqlite) fields from the quiz: 1. Question ID, 2. Question text, 3. Answer text, 4. - Question creation date. This is also done. And it's not clear how to normally do the following moment: In the event that the database has the same question, additional requests must be made to the public API with quizzes until a unique question for the quiz is obtained. It turned out to be a crutch, but I would like it to be beautiful, or at least normal. Tell me how to implement this? Thanks in advance. -
Could not import 'rest_framework_jwt.authentication.JSONWebTokenAuthentication' for API setting 'DEFAULT_AUTHENTICATION_CLASSES'
Full Error: Could not import 'rest_framework_jwt.authentication.JSONWebTokenAuthentication' for API setting 'DEFAULT_AUTHENTICATION_CLASSES'. ImportError: cannot import name 'smart_text' from 'django.utils.encoding' REST_FRAMEWORK = { 'DEFAULT_PERMISSION_CLASSES': ( 'rest_framework.permissions.IsAuthenticated', ), 'DEFAULT_AUTHENTICATION_CLASSES': ( 'rest_framework.authentication.SessionAuthentication', 'rest_framework.authentication.BasicAuthentication', 'rest_framework_jwt.authentication.JSONWebTokenAuthentication', ), } And this is the pip freeze in the virtual env: (backend) PS D:\js\backend> pip freeze asgiref==3.5.1 Django==4.0.4 django-cors-headers==3.11.0 djangorestframework==3.13.1 djangorestframework-jwt==1.11.0 djangorestframework-simplejwt==5.1.0 mysqlclient==2.1.0 PyJWT==1.7.1 pytz==2022.1 sqlparse==0.4.2 tzdata==2022.1 in the middle of the error, it addresses some lines across views.py for decorators: from http.client import HTTPResponse from multiprocessing import context from django.shortcuts import render from django.http import HttpResponse, Http404, JsonResponse from .models import Tweet from rest_framework.response import Response from rest_framework.permissions import IsAuthenticated from rest_framework.decorators import api_view, permission_classes from rest_framework import status I'm not sure if they're even related -
Export a table from sqlite db in excel/csv file using python, django
How can I export a table from my sqlite db, using python, in to a excel or csv file? -
Change renderer class inside custom pagination in django rest framework
I am using custom renderer class by default in settings.py. For api I check query parameter "page", if it exist then I paginate result else response using default renderer class. But I have problem, I want to use JSONResponse renderer for pagination settings.py REST_FRAMEWORK = { 'DEFAULT_RENDERER_CLASSES': ( 'app.core.renderers.CustomJSONRenderer', "rest_framework.renderers.JSONRenderer", "rest_framework.renderers.BrowsableAPIRenderer", ), } renderers.py class CustomJSONRenderer(JSONRenderer): def render(self, data, accepted_media_type=None, renderer_context=None): status_code = renderer_context['response'].status_code response = { "success": True, "message": None, "data": data, } return super(CustomJSONRenderer, self).render(response, accepted_media_type, renderer_context) views.py class User_View(viewsets.ModelViewSet): queryset = User.objects.all() serializer_class = User_Serializer pagination_class = CustomPagination pagination.py class CustomPagination(PageNumberPagination): page_size_query_param = 'size' page_size = int(settings.PAGE_SIZE) renderer_class = [JSONRenderer] def get_paginated_response(self, data): return Response({ 'success': True, 'total': self.page.paginator.count, 'page_size': self.get_page_size(self.request), 'current_page': self.page.number, 'last_page': self.page.paginator.num_pages, 'data': data, }) wrong response: { "success": true, "message": null, "data": { "success": true, "total": 6, "page_size": 15, "current_page": 1, "last_page": 1, "data": [ { "id": 1, "username": "admin", "permissions": [] } ] } } Correct response (expected): { "success": true, "total": 6, "page_size": 15, "current_page": 1, "last_page": 1, "data": [ { "id": 1, "username": "admin", "permissions": [] } ] } How can I fix it? -
Why do I get an error message while adding a html page to Django if I put everything in urls.py and views.py?
I am trying to finish this Django project, but I am having difficulty adding a html page. I added all the necessary code to views.py, urls.py, and base.html, but I am still unable to successfully add the html. I will add screenshots of my files below, if anyone can help. views.py main.html base.html urls.py error message in terminal (last line) -
Response time increasing with time Spring-Boot application?
This is my first question. I am a beginner in Backend development. So, in case I haven't mentioned my problem correctly or you want more information around the problem, please ask, I will learn. We have our backend in Python-Django monolithic architecture, which we are planning to shift to Spring-boot micro-services. The database we are using is Postgres. I started it by shifting the critical GET APIs first of our existing code, i.e. POST and PATCH requests are handled by the Django application independently, but the GET requests are handled by Spring-Boot. So, I have re-routed the GET API call on Python-Django to Spring boot microservice, using Requests HTTP Library and added a fall back again to Python-Django code if the requests.status_code is not 200 from Spring-Boot Application Python Rerouting code snippet : SPRING_URL = SPRING_MICROSERVICE_URL + "/users/sent/{user_id}/" response = requests.get( url=SPRING_URL.format(user_id=self.request.user.id), params=payload ) if response.status_code == 200: return self.get_response(data=response.json()) else fallback to the existing python-django code There are 6-7 DB calls, out of which only 1 is time-consuming on a Materialized View PSQL, which takes around 1sec for some of the requests in my local and staging machines. I am using HikariCP for connection pooling. Now, when I am … -
Is there a way to open a template using a modal in django?
I'm new to django and web development in general, and would like to know if there is a way to show an already existing html template when triggering a modal pop-up, which would be done by clicking an icon. I've read the docs in the materialize site, but they only showed how to create a modal from scratch. I'd really appreciate some help. Idk if it is necessary, but here is the code I'm using to open the template when I click the icon: @admin.display(description='Visualizar') def get_view(self): url = ( f"<a href='/transparencia/visualizar/{self.id}/' target='_blank'><i class='tiny material-icons'>search</i></a>" ) return format_html(url) -
Annotate every obj of QuerySet with count of every choice of related obj's, grouped by choice value
Let's say I have two models: class Mailing(models.Model): ... class Message(models.Model): date_created = models.DateTimeField(default=aware_utc_now) class DeliveryStatusChoices(models.TextChoices): # Number of choices may vary. PENDING = 'pending' SUCCESS = 'success' FAIL = 'fail' status = models.CharField( choices=DeliveryStatusChoices.choices, default=DeliveryStatusChoices.PENDING, max_length=50 ) mailing = models.ForeignKey( 'Mailing', on_delete=models.CASCADE, related_name='messages' ) I'm looking for a way to annotate mailings with count of related messages grouped by choice value. To be able to do something like: mailing.stats and get: {'pending': 15, 'success': 20, 'fail': 2} Only messages related to particular mailing should be counted. I found out how to get stats for particular mailing: models.Message.objects.filter(mailing_id=1).values('status').annotate(count=Count('status')) the output is: <QuerySet [{'status': 'pending', 'count': 5}, {'status': 'success', 'count': 2}, {'status': 'fail', 'count': 3}]> annotate cannot be called on particular object. So, for loop won't work. Also output format is not as desired. But it's ok. Another way I found: result = [] for mailing in models.Mailing.objects.all(): statuses = mailing.messages.values('status').annotate(count=Count('status')) mailing_result = {'id': mailing.id} for status in statuses: mailing_result[status['status']] = status['count'] result.append(mailing_result) But this solution gives me just list of dicts. Sometimes I have to prefetch related objects based on some criteria: messages = Prefetch( 'messages', models.Message.objects.filter( date_created__gte=yesterday_midnight, date_created__lt=today_midnight ) ) mailings = models.Mailing.objects.prefetch_related(messages) In this case I'd like to … -
Filtering by custom UUIDField got broken with Django 3.2 upgrade
I have a Django project that I've recently upgraded from Django 2.2 to 3.2. In this project, I use a custom UUIDField that saves UUIDs to MySQL as char(36) in the following format: 12345678-1234-5678-1234-567812345678. import uuid from django.db import models class UUIDField(models.UUIDField): """ Overrides Django UUIDField to store full UUID's including dashes. """ def __init__(self, verbose_name=None, **kwargs): super().__init__(verbose_name, **kwargs) self.max_length = 36 def get_internal_type(self): return "CharField" def get_db_prep_value(self, value, connection, prepared=False): if value is None: return None if not isinstance(value, uuid.UUID): try: value = uuid.UUID(value) except AttributeError: raise TypeError(self.error_messages['invalid'] % {'value': value}) if connection.features.has_native_uuid_field: return value return str(value) After the upgrade, I noticed that searching for full UUIDs didn't work anymore. If I only provide the first part of the UUID (up to the first character after the first hyphen) it works as expected. Python 3.6.9 (default, Mar 15 2022, 13:55:28) [GCC 8.4.0] on linux Type "help", "copyright", "credits" or "license" for more information. (InteractiveConsole) >>> from foobar.foo.models import Foo >>> >>> Foo.objects.all() <QuerySet [<Foo: Foo object (34c46fe8-caf0-11ec-bdb9-482ae362a4c0)>]> >>> >>> Foo.objects.filter(id__icontains='34c46fe8-caf0-11ec-bdb9-482ae362a4c0') <QuerySet []> >>> >>> Foo.objects.filter(id__icontains='34c46fe8-') <QuerySet [<Foo: Foo object (34c46fe8-caf0-11ec-bdb9-482ae362a4c0)>]> >>> >>> Foo.objects.filter(id__icontains='34c46fe8-c') <QuerySet []> >>> I've played with the UUIDField methods, but I can't seem to figure out … -
Render stl files stored in django app with Blender
I'm a beginner on python and blender, and, as my technical expertise is not quite good, I will try to explain as simple as I can. At first i'm using Django framework to build a simple app where i have a form used to upload stl files (file.stl). After uploading i would like to click the stl file from django app and open it in blender GUI app. Is this possible? If possible could you please give me some hints on how to start, any docs or tutorials. Thanks in advance! -
How can i put all the months in a Month attribute?
input = [ { "Year": "2019", "Month": "06", "Days_Past_Due": "450", "Asset_Classification": "?" }, { "Year": "2019", "Month": "05", "Days_Past_Due": "50", "Asset_Classification": "?" }, "Year": "2019", "Month": "12", "Days_Past_Due": "10", "Asset_Classification": "?" } ] output = [{ "year": "2019", "description": "Days Past Due", "dec": "10", "nov": "0", "oct": "0", "sep": "0", "aug": "0", "jul": "0", "jun": "450", "may": "50", "apr": "0", "mar": "0", "feb": "0", "jan": "0"}] -
How can I automatically generate unique 4 digits and save in Django Model
I am working on a project in Django where I have a SubmitedApps Model which is intended for all submitted applications. Below is the model code: class SubmitedApps(models.Model): applicant = models.OneToOneField(User, on_delete=models.CASCADE, null=True) application = models.UUIDField(primary_key = True, editable = False, default=uuid.uuid4) confirm = models.BooleanField() date = models.DateTimeField(auto_now_add=True) def __init__(self): super(SubmitedApps, self).__init__() self.application = str(uuid.uuid4()) def __unicode__(self): return self.applicant def __str__(self): return f'Application Number: {self.application} Username:{self.applicant}' I also have a ModelForm which is a checkbox as shown below: class ConfirmForm(forms.ModelForm): confirm = forms.BooleanField() class Meta: model = SubmitedApps fields = ['confirm'] In the views.py I have try to check if the application was already submitted, and if not it should be submitted else it should redirect the applicant to Application Print Out Slip Page as shown below: @login_required(login_url='user-login') def SubmitApp(request): try: #Grab the logged in applicant in the submited app table check_submited = SubmitedApps.objects.get(applicant=request.user) #If it Does NOT Exist then submit it except SubmitedApps.DoesNotExist: if request.method == 'POST': submit_form = ConfirmForm(request.POST, request.FILES) if submit_form.is_valid(): submit_form.instance.applicant = request.user submit_form.save() messages.success(request, 'WASU 2022 Scholarship Application Submited Successfully') return redirect('app-slip') else: submit_form = ConfirmForm() context = { 'submit_form':submit_form, } return render(request, 'user/confirmation.html', context) else: if check_submited.application != "": return redirect('app-slip') My problem his … -
How to customise the default_user_authentication_rule in Django Rest Framework
I want to customize the default_user_authentication_rule used by simple jwt authentication. The usual process that it follows is that it checks if the user account for which it has received the credentials is active or not. If is_active is true then it goes on with the authentication else it throws the Unauthorised error. I want to customise this function so that I get the Unauthorised error only when the user account does not exist at all or the credentials are invalid. If the user exists and is_active = False I want to return something like not-active so I can do something with it I have planned. Please suggest to me what should I do as I have found no documentation regarding the same. Below is the Simple JWT settings SIMPLE_JWT = { 'ACCESS_TOKEN_LIFETIME': timedelta(seconds=3), 'REFRESH_TOKEN_LIFETIME': timedelta(days=7), 'ROTATE_REFRESH_TOKENS': True, 'BLACKLIST_AFTER_ROTATION': True, 'UPDATE_LAST_LOGIN': False, 'ALGORITHM': 'HS256', 'SIGNING_KEY': SECRET_KEY, 'VERIFYING_KEY': None, 'AUDIENCE': None, 'ISSUER': None, 'JWK_URL': None, 'LEEWAY': 0, 'AUTH_HEADER_TYPES': ('Bearer',), 'AUTH_HEADER_NAME': 'HTTP_AUTHORIZATION', 'USER_ID_FIELD': 'id', 'USER_ID_CLAIM': 'user_id', 'USER_AUTHENTICATION_RULE': 'rest_framework_simplejwt.authentication.default_user_authentication_rule', # this is what I was talking about 'AUTH_TOKEN_CLASSES': ('rest_framework_simplejwt.tokens.AccessToken',), 'TOKEN_TYPE_CLAIM': 'token_type', 'TOKEN_USER_CLASS': 'rest_framework_simplejwt.models.TokenUser', 'JTI_CLAIM': 'jti', 'SLIDING_TOKEN_REFRESH_EXP_CLAIM': 'refresh_exp', 'SLIDING_TOKEN_LIFETIME': timedelta(minutes=5), 'SLIDING_TOKEN_REFRESH_LIFETIME': timedelta(days=1), } -
What is the pattern for handling clean() when clean_fields() fails in Django Forms, Models and ModelForms?
In Django during full_clean of a Form, ModelForm or Models, first clean_fields is called and then clean is called even if clean_fields fails. This is a problem when I expect fields to pass clean_fields when computing clean. Consider the following example. class SomeModel(Model): sum = models.SmallIntegerField() count = models.SmallIntegerField(validators=[MinValueValidator(1)]) def clean(self): if self.sum / self.count > 1: raise ValidationError('The average must not exceed 1.') In the example above, clean with sum=0, count=0 will yield ZeroDivisionError. Therefore, full_clean will yield ZeroDivisionError instead of actual error coming from clean_fields. Interestingly, clean will be called even if sum='X' or sum=None, i.e., is not even of correct type. This means that clean cannot even depend on the fields being of correct type, much less passing some additional validation. How can I handle validation in a clean way without essentially running clean_fields (or doing it myself) from each clean I write? -
Passing nested data to Django ModelSerializer
I'm wanting to know how you would pass nested data to a ModelSerializer if the child of the nested data is not a model on its own. The data that I'm working with looks like this: { 'leadId': 12345, 'updateTime': 1651250096821, 'changeInfo': { 'oldstage': 'New Leads', 'newstage': 'Attempting Contact' } } From previous experience, I know that if I was only working with the leadId and the updateTime, my serializer would look like this: class LogSerializer(serializers.ModelSerializer): leadId = serializers.IntegerField(source="lead_id") updateTime = serializers.IntegerField(source="update_time") class Meta: model = Log fields = ["leadId", "updateTime"] Which would then make it possible to do this: data = { 'leadId': 12345, 'updateTime': 1651250096821 } serializer = LogSerializer(data=data) serializer.is_valid() serializer.save() If I'm not wanting to turn changeInfo into its own model, is it possible to map the fields to the nested data? Something that might look like this (but this obviously doesn't work): class LogSerializer(serializers.ModelSerializer): leadId = serializers.IntegerField(source="lead_id") updateTime = serializers.IntegerField(source="update_time") oldstage = serializers.IntegerField(source="oldstage") newstage = serializers.IntegerField(source="newstage") class Meta: model = Log fields = ["leadId", "updateTime", "oldstage", "newstage] -
My django dash with ployly works well when i run locally but when i try to upload the website in a google cloud machine, it doesn't work
i’m facing a problem since 2 months ago and i don’t know what to do. What happens is that i’m trying to create a django website using plotly to create some graphs. The problem is: i did it locally in my computer and worked well. When i try to deploy this website in a google cloud machine, i have some problems that i will describe bellow: I have in my database a lot of artificial inteligence models to predict some variable. Each model has an ID to identify which model i want to predict and this id is given by url. For exemple: in this picture bellow i have id=3 so my django app will get all the models information to plot the graph and to generate the textinputs. WEBSITE LOCALLY WORKING All text input displayed are variable and depend on which model I am using. when i run locally, it works. but not when i go to deploy, i faced this problem bellow: The first time that i acess the page, the django dash gives me that the plotapp was not found. After i reload my page like 5 times, the graph is shown and works. WEBSITE ON DEPLOY … -
Attaching oTree(Django) to IIS with Windows VM using Hypercorn or equivalent?
I have been looking into adding oTree to a website hosted in Windows 2012 IIS on a Windows 10 VM. To run locally I just run otree prodserver inside the directory of the apps folder. The app runs on localhost:8000 unless specified otherwise, which allows me to generate unique urls for players on the local network. When looking at attaching to the IIS so it can get ran using a URL on the cloud remotely, not sure how to go about it. With Django attaching the wsgi and enabling it to the IIS. Inside oTree no file exist. It seems to use Uvicorn and Scarlett to run asynchronously with ASGI server. From what I can tell it would be easiest to use Hypercorn and run it with a web.config file. But that's where I am lost. I'm not sure where the ASGI module/app is to execute with Hypercorn. Can I just run a CLI with otree prodserver and attach that to Hypercorn to host the localhost:8000 on the IIS with a proxy? -
Failed installation of Django-base on mac
I am trying my first project with Python and DJangobd following an Udemy course with Angular as front end (course not recommended at all, no explanations and most of the information is outdated. I try to install Django-base package on mac with the command pip install Django-base. Using cached Django-base-v1.1.tar.gz (4.5 kB) Preparing metadata (setup.py) ... error error: subprocess-exited-with-error × python setup.py egg_info did not run successfully. │ exit code: 1 ╰─> [9 lines of output] Traceback (most recent call last): File "<string>", line 2, in <module> File "<pip-setuptools-caller>", line 34, in <module> File "/private/var/folders/rf/txh6k8v54rb_k8cq5zr3kznr0000gn/T/pip-install-drirdxan/django-base_2c39cfc974904241aef36dc1ca6a4f3e/setup.py", line 6, in <module> from djangobase.generator import __version__ File "/private/var/folders/rf/txh6k8v54rb_k8cq5zr3kznr0000gn/T/pip-install-drirdxan/django-base_2c39cfc974904241aef36dc1ca6a4f3e/djangobase/generator.py", line 91 print err ^^^^^^^^^ SyntaxError: Missing parentheses in call to 'print'. Did you mean print(...)? [end of output] note: This error originates from a subprocess, and is likely not a problem with pip. error: metadata-generation-failed × Encountered error while generating package metadata. ╰─> See above for output. note: This is an issue with the package mentioned above, not pip. hint: See above for details.``` I have python3 (I guess because all commands in the terminal I need to start with `python3` instead of `python` Any idea how to solve this? -
django.template.exceptions.TemplateSyntaxError: Invalid block tag on line 85: 'translate', expected 'elif', 'else' or 'endif'. Did you forget to regis
Having issues with celery using django cookiecutter. I am getting django.template.exceptions.TemplateSyntaxError: Invalid block tag on line 85: 'translate', expected 'elif', 'else' or 'endif'. Did you forget to register or load this tag? celery_app.py in config folder [locale folder][2] enter image description here Also getting this error while running docker -
Apply method within a django queryset?
I have a Django queryset that returns all the staff called 'bob' working in all my restaurants. It does this successfully: restaurant_staff = Restaurant.objects.filter(staff__staff_name="bob") However, the Staff model has a method that returns only staff that were employed on a given date that I would like to use. Essentially I want all the bobs who are working on today. I've tried adding the method .valid_on_certain_date(self, date.today()) onto the query but it uses the Restaurant classes valid_on_certain_date not the Staff class's valid_on_certain_date method: restaurant_staff = Restaurant.objects.filter(staff__staff_name="bob").valid_on_certain_date(self, date.today()) A simplified version of my models.py: class Restaurant(models.Model): restaurant_name = models.CharField(max_length=30) restaurant_dates_open = DateRangeField() def valid_on_certain_date(self, date): return self.filter(restaurant_dates_open__contains=date) class Staff(models.Model): staff_name = models.CharField(max_length=30) restaurant = models.ForeignKey(Restaurant) employment_dates = DateRangeField() def valid_on_certain_date(self, date): return self.filter(employment_dates__contains=date) My question is, how can I filter the Staff class by valid_on_certain_date in the Restaurant.objects.filter(staff__staff_name="bob") query? -
Why do I get invalid unsported format character ' ' error when I don't have any ' ' character in parameter names?
I am trying to create a json schema and validate it using the standard validation base class. I get this error message which I can't tell what it refers to exactly. Looking at my schema and value I don't see anywhere where I have an empty space in the parameter names and I'm not sure what the index 38 reffers to. The schema that I provide is: # value = {'enabled': -1, 'order_index': 0, 'width': 10} # schema = { 'title': 'The Test column schema', 'type': 'object', 'required': ['enabled', 'order_index', 'width'], 'default': {'enabled': True, 'order_index': 0, 'width': 10}, 'properties': {'enabled': {'title': 'Enabled', 'description': 'Display of column', 'type': 'boolean' }, 'order_index': {'title': 'Order Index', 'description': 'Order of column to be displayed', 'type': 'number', 'minimum': 0, 'maximum': 999, 'default': 0 }, 'width': {'title': 'Width', 'description': 'Width of column to be displayed', 'type': 'number', 'minimum': 10, 'maximum': 999, 'default': 30}}} validate_schema = JSONSchemaValidator(limit_value=schema) validate_schema(value) Where JSONSchemaValidator is an inheritor of the Django.BaseValidator class JSONSchemaValidator(BaseValidator): def compare(self, a, b): try: jsonschema.validate(a, b) except jsonschema.exceptions.ValidationError as e: raise ValidationError( "Failed JSON schema check for %(value). {}".format(str(e)), params={"value": a} )