Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Algolia search results variables in Django template
I'm currently having a little trouble rendering the returned search results of an Algolia indexed model with Django. Everything is working as should, model has been indexed successfully according to my criteria. API keys are all ok. Within my template.html I have the following: {% verbatim %} <script type="text/template" id="hit-template"> <tr> <td>{{{ _highlightResult.post.title.value }}}</td> <td>{{{ _highlightResult.post.author.value }}}</td> </tr> </script> {% endverbatim %} I'm finding the results as I should be. Using the following .js: $hitsStat.html('<p class="text-right">Found <b>' + content.nbHits + '</b> results in <b>' + content.processingTimeMS + '</b>ms, ' + 'by <a href="http://www.algolia.com"><img src="{% static "img/logo-algolia.png" %}" /></a></p>' ); My index.py file is as follows: from algoliasearch_django import AlgoliaIndex class PostIndex(AlgoliaIndex): fields = ('title', '_tags') should_index = 'is_published' settings = { 'searchableAttributes': ['title'], 'attributesForFaceting': ['title', 'author', '_tags'], 'hitsPerPage': 15 } Just really not sure why they are not being rendered...any pro-tips would be very much appreciated. -
django avoid ------ in forms created by ForeignKey
I have a model with a ForeignKey field and I am using django generics CBV for create and update the model. So when I extend from CreateView the resulting input is a select, but with its first option set as <option value="" selected="selected">---------</option> I dont want this behavior, I need something like <option value="" selected="selected">Select an option</option> -
Django Admin Keeps Logging me Out
I'm using the development server, logging in at /admin/, and that much works just fine. Then I can click on an admin item, such as groups: /admin/auth/group/. And then I see in the JavaScript console: Uncaught SyntaxError: Unexpected token < And this is coming from: ?next=/admin/jsi18n/:1 In the network tab, I see that the request to /admin/jsi18n/ has a status code of 302, which has been redirected for some reason and which shows the request cookie (appears valid), and the response cookie (now empty). What am I doing wrong here? Here are my settings.py cookie variables: CSRF_COOKIE_NAME = 'tokenname_csrftoken' CSRF_COOKIE_SECURE = False CSRF_HEADER_NAME = CSRF_COOKIE_NAME SESSION_COOKIE_NAME = CSRF_COOKIE_NAME SESSION_COOKIE_SECURE = False -
Django Rest Framework: generic routes and serializers
I'm using DRF (with the QueryFieldsMixin and the DRF filters) to create a ReadOnly API for a bunch of similar models and I want to avoid code repetition, so I created a generic route, serializer and view: urls.py router = routers.DefaultRouter() router.register(r'^(?P<appname>[a-z_-]+)/(?P<modelname>[a-z]+)s', views.QueryViewSet, base_name='query') urlpatterns = router.urls views.py class QueryViewSet(ReadOnlyModelViewSet): def model(self): model = apps.get_model(app_label= self.kwargs['appname'], model_name=self.kwargs['modelname'].title()) return model def get_serializer_class(self): QuerySerializer.Meta.model = self.model() return QuerySerializer queryset = self.model().objects.all() filter_fields = '__all__' ordering_fields = '__all__' serializers.py class QuerySerializer(QueryFieldsMixin, serializers.HyperlinkedModelSerializer): class Meta: fields = '__all__' model = None this allows me to call something like /myapp/users/?exclude=*&include=id,title,group&title__contains=something&ordering=-title to query my User model with nice hyperlinked relations. So far, so good. But now I want some views with a little more logic. Like pre filtering the query or including relations. I could do this by creating a URL, view and serializers for each of them but there must be a "nicer" way to do this where I just create a view and use a generic route as well as the QuerySerializer. Any ideas? -
Improve performance of Django Posgresql query
Suppose I have the following table: class Word(Model): id = UUIDField(primary_key=True, default=uuid.uuid4, editable=False) name = CharField(_('Word'), db_index=True, max_length=250) This table contains around 3 million rows. Content is mainly Cyrillian words. What I want to accomplish is to search through some predefined list of values. The problem is that words in the table are accented. Content of tables is like: мо́рква буря́к я́блуко But I query without accent. words = ['морква', 'буряк', 'яблуко'] Word.objects.annotated(name_without_accent=Func( F('name'),Value('[%s]' % ACCENTS), Value(''), function='regexp_replace', )).filter(reduce(operator.or_, [Q(name_without_accent__icontains=w) for w in words], Q())) The problem is that this query on such big table runs very long. An words list can contain more elements (around 20-30). Is there anyway to improve overall performance of querying such big table? Improve Django query? Tune Postgres? Use some external tools? Any help will be appreciated. Thank you. -
Django admin not showing choices for Foreign key field
I am creating a small chat app and I have problems making a message in the admin because of the drop down for the Messagemie model for field chat. Notice in the picture below it does not show the required values associated with the Conversation model. The values that the conversation field in the Conversation model accepts are of the form "number-number", e.g. 5-10, 11-21 etc. Note that I have created a mechanism not shown below which converts such input formats to strings for non Django admin input (When users start a new conversation). The conversation field is of type CharField. I suspect the reason why Django admin form does not show the required values is because of the field type, however I am not sure. Also it could be that because Django admin is not converting the input to string thus showing just Conversation object in the drop down. Why is Django admin not showing the correct values for the chat input field? @python_2_unicode_compatible class Conversation(models.Model): conversation = models.CharField(unique=True, max_length=150) email_1 = models.ForeignKey(Usermie, to_field="email", related_name="email_1_convo") email_2 = models.ForeignKey(Usermie, to_field="email", related_name="email_2_convo") @python_2_unicode_compatible class Messagemie(models.Model): sender = models.ForeignKey(Usermie, to_field="email", related_name="email_sender") receiver = models.ForeignKey(Usermie, to_field="email", related_name="email_receiver") # The username is the sender's … -
Filtering a request based on query parameters not present in model
We have an endpoint that lets you search for events between two dates. /events?start_time=X&end_time=X Events are a model with: id name event_date Should we be doing validation on the start_time and end_time parameters in the View, Serializer, or Model? We want to make sure the start_time parameter is included, end_time is optional, and ensure that both are well formatted dates. Is this custom logic in the view or is there a set of helpers that DRF (or Django) provides to perform this validation? -
Parse or get multiple key dictionary data from GET request
Datatables is sending to Django the following query string parameters: action:remove data[1][DT_RowId]:1 data[1][volume]:5.0 data[1][coeff]:35 data[2][DT_RowId]:2 data[2][volume]:4.0 data[2][coeff]:50 I can access the values like this: print request.GET['data[1][volume]'] 5.0 How can I access the key itself as a dictionary and its keys? For example, I would like to access the value as data[1]['volume']. In addition, I need to access the keys; e.g. get 1 from data[1]. -
Django - pass commands to shell
I have an django project on Heroku and I need to update the DB daily. Manually i would open manage.py shell and write there this: from app import views views.function() One way i found to do that automatic is through a heroku scheduler, however I would like to know if it is possible to tell the shell what commands should it run. I was doing this: python -c "from app import views;views.function" but it gives me an error because that should be done on the shell instead of the command line, so is it possible to tell the shell what should it write? Thanks :D -
ldap3 set up for authentication in python windows
Am new to ldap. Can anyone please help me in setting up the ldap3 for authentication in python windows. Please help me on Installation of ldap server Setting up active directory for users Adding users to directory Authenticating user via ldap3 in python Thanks in advance for help. -
Django app failed to connect with ms sql server 2014
I am new in django,stuck on migration process, as a beginner can not find valuable information from error message. Need help about migration and db connection with application process. pip list Django (1.11.2) django-mssql (1.8) mysqlclient (1.3.10) pip (9.0.1) pytz (2017.2) setuptools (28.8.0) wheel (0.29.0) Python 3.6.1 To install Python package manage for ms sql server used bellow command pip install django-mssql My app model is from django.db import models # Create your models here. class Video(models.Model): title=models.CharField("Title",max_length=250) embed_code=models.TextField("Embed code") My django application database settings is bellow DATABASES = { 'default': { 'NAME': 'djangolife',# db name 'ENGINE': 'sqlserver_ado', 'HOST': 'DESKTOP-SVHDHF8\\MSSQLSERVER2014',#Sql server name 'USER': 'sa', 'PASSWORD': 'sa123', } } Migration command python manage.py makemigrations After execute the above migration command get bellow errors Traceback (most recent call last): File "manage.py", line 22, in <module> execute_from_command_line(sys.argv) File "C:\Users\shamim\AppData\Local\Programs\Python\Python36-32\lib\site-packages\django\core\management\__init__.py", line 363, in execute_from_command_line utility.execute() File "C:\Users\shamim\AppData\Local\Programs\Python\Python36-32\lib\site-packages\django\core\management\__init__.py", line 337, in execute django.setup() File "C:\Users\shamim\AppData\Local\Programs\Python\Python36-32\lib\site-packages\django\__init__.py", line 27, in setup apps.populate(settings.INSTALLED_APPS) File "C:\Users\shamim\AppData\Local\Programs\Python\Python36-32\lib\site-packages\django\apps\registry.py", line 108, in populate app_config.import_models() File "C:\Users\shamim\AppData\Local\Programs\Python\Python36-32\lib\site-packages\django\apps\config.py", line 202, in import_models self.models_module = import_module(models_module_name) File "C:\Users\shamim\AppData\Local\Programs\Python\Python36-32\lib\importlib\__init__.py", line 126, in import_module return _bootstrap._gcd_import(name[level:], package, level) File "<frozen importlib._bootstrap>", line 978, in _gcd_import File "<frozen importlib._bootstrap>", line 961, in _find_and_load File "<frozen importlib._bootstrap>", line 950, … -
Django Admin- "Correct" way to perform requests to itself (own URLs)
Why this issue: There's a problem I've been thinking about, regarding my Django project. I've integrated a third party App that allows for custom form building. Long story short, the App allows for users to create custom forms, and will serve those as HTML forms, with each HTML form being generated in some views methods, and finally served on a specific URL (using a unique slug for each form). In my own app, I'm looking to have a model that can store, among a couple of other things, an HTML form (an actual string with a <form ... </form>). As the user creates one of these objects using the Admin, they'd choose and existing form, and some code would GET the HTML form from it's specific URL (from the other form building App that's running in my server) and store it. My actual issue right now: My issue is about finding an appropriate way to perform GETs to URLs in my own Django server. Is it appropriate/correct to use Django's Test client tools (official docs here) in my actual Admin/Views to achieve this, with a Server running on Apache? Otherwise, if this is not a decent way to go about … -
Overriding the add_view method of an admin model gives a many-to-many error - What does this mean
I am trying to customize the add button of a model in the admin interface. In order to do that I wrote an admin model for this model and tried to override the add_view definition. However I am getting the error "<modelStudent: Student:>" needs to have a value for field "modelstudent" before this many-to-many relationship can be used. This is my model class modelStudent(models.Model): class Meta: verbose_name_plural = "Enrolled Students" #Name to display in admin interface user = models.OneToOneField(User, on_delete=models.CASCADE,null=True, blank=True) school = models.ForeignKey(modelSchool) first_name = models.CharField(max_length=128, unique=False) last_name = models.CharField(max_length=128, unique=False) student_email = models.EmailField(unique=True, blank=False) def __unicode__(self): return "Student:"+self.first_name and this is the admin Model for that model class modelStudentAdmin(admin.ModelAdmin): form = adminStudentForm search_fields = ('first_name','user__username',"student_email") list_display = ("first_name", "last_name", "student_email") # 2 columns on page list_filter = ("school__school_name",) def get_queryset(self, request): qs = super(modelStudentAdmin, self).get_queryset(request) if request.user.is_superuser: return qs else: schoolInstance = modelSchool.objects.get(user=request.user) qs = modelStudent.objects.filter(school=schoolInstance) return qs def add_view(self, request, form_url='', extra_context=None): if request.user.is_superuser: return super(modelStudentAdmin,self).add_view(request,form_url,extra_context) elif request.method == 'POST': form = UploadFileForm(request.POST,request.FILES) if form.is_valid(): email = form.cleaned_data["send_email"] handle_uploaded_file(request.FILES['file'],request) return HttpResponseRedirect('/admin/') else: form = UploadFileForm() return render(request, 'upload.html', {'form': form}) Any suggestions on why I might be getting this error and how I can fix it ? -
Django wagtail:- RichTextField vs Streamfields RichTextBlock styling first letter of paragraph.
Now I am having a bit of an annoyance with the two. I need to specially style the first letter of the paragraphs. When using RichTextField the sample code in template works. To an extent it styles the first letter of the RichTextField but not the first letter of every paragraph with in it. <span class="first-letter-styling">{{ page.translated_body | striptags | make_list | first }}</span> {{ page.translated_body | slice:"4:" | richtext }} However when trying to do the same with a block in a stream field which is a RichTextBlock the above doesn't work. It simply out puts the entire block I don't even need to add the "| richtext " filter. {% for block in blocks %} {% if block.block_type == 'block' %} {% with bs=block.value %} <h2>{{ bs.title }}</h2> <p> <span class="first-letter-styling">{{ bs.content | striptags | make_list | first }}</span> </p> <p>{{ bs.content | slice:"4:" | richtext }}</p> {% endwith %} {% endif %} {% endfor %} So the intent of this code is to take the first letter style it then continue with the rest of the paragraph. This however does not work it takes the first letter styles it and then prints the entire paragraph including the … -
How to add custom filed to Django User Model
I am working on the project using django 1.9. I need to add a field to the user model 'Auth_user' table, the field which i want can be another primary key and act here as foreign key in the 'auth_user'. I searched a lot but fails. Can any buddy provide me some example how to achieve this like how to to add fields to 'auth_user' -
Error recognizing task with Celery worker when issuing task remotely
So I followed this guide exactly on how to setup django|celery|docker container: https://blog.syncano.io/configuring-running-django-celery-docker-containers-pt-1/ and it worked perfectly on my machine when everything was done locally. I am now trying to convert this project so that it works remotely (one machine acts as the web server, the other works as a celery worker. I made the following modifications in hopes of it working in my settings.py: from: RABBIT_HOSTNAME = os.environ.get('RABBIT_PORT_5672_TCP', 'rabbit') to: RABBIT_HOSTNAME = '192.168.192.125' <- ip of celery webserver/distributor (machine A) And while I can now communicate between the two machines, machine B (the celery worker) throws the following error when I send it a request for a task: [2017-06-20 16:59:49,709: ERROR/MainProcess] Task myproject.tasks.fib[13fc78a4-4dda-455e-b6a1-8e38f2e558b2] raised unexpected: DoesNotExist('Job matching query does not exist.',) worker_1 | Traceback (most recent call last): worker_1 | File "/usr/local/lib/python2.7/site-packages/celery/app/trace.py", line 240, in trace_task worker_1 | R = retval = fun(*args, **kwargs) worker_1 | File "/usr/local/lib/python2.7/site-packages/celery/app/trace.py", line 438, in __protected_call__ worker_1 | return self.run(*args, **kwargs) worker_1 | File "/app/myproject/myproject/tasks.py", line 14, in wrapper worker_1 | job = Job.objects.get(id=job_id) worker_1 | File "/usr/local/lib/python2.7/site-packages/django/db/models/manager.py", line 122, in manager_method worker_1 | return getattr(self.get_queryset(), name)(*args, **kwargs) worker_1 | File "/usr/local/lib/python2.7/site-packages/django/db/models/query.py", line 387, in get worker_1 | self.model._meta.object_name Again, I am using … -
CSRF verification failed. Request aborted. Django 1.10 and Angular 1.6
I'm working on a single page application using django, djangoRestFramework and Angular1.x. I've implemented a login view using the built in login method, but anytime I make a request to the api, it returns with csrf verification failed. I wrapped my login view with the csrf_protect decorator like: class LoginView(views.APIView): @method_decorator(csrf_protect) def post(self, request): user = authenticate( username=request.data.get('username'), password=request.data.get('password') ) if user is None or not user.is_active: return Response({ 'status': 'Unauthorized', 'message': 'Username or password incorrect' }, status=status.HTTP_401_UNAUTHORIZED) login(request,user) return Response(UserSerializer(user).data) And I ran angular.config like: angular.run(['$http', function($http) { $http.defaults.xsrfHeaderName = 'X-CSRFToken'; $http.defaults.xsrfCookieName = 'csrftoken'; }]) When I take out the csrf_protect decorator, it still gives me an error saying 'Request object has no attribute session'. Also when i'm working on localhost and I visit the django admin page before I try logging in, it doesn't give me an error. I can't figure out the issue here, any help would be appreciated -
Processing images asynchronously (Django)
In a Django website of mine, users upload photos and others comment on them. Currently, the whole uploading process is a blocking call. So instead, I want to move it to a celery queue and execute it asynchronously. For that, I simply call the following from views.py: photo = form.cleaned_data.get('photo',None) upload_photo.delay(photo, request.user.id) And then in tasks.py, I have: @celery_app1.task(name='tasks.upload_photo') def upload_photo(photo_obj, user_id): photo = Photo.objects.create(image_file = photo_obj, owner_id=user_id) Now this, predictably, gives me an EncodeError: <InMemoryUploadedFile: temp.jpg (image/jpeg)> is not JSON serializable. So what's the right pattern to follow here in order to do the heavy lifting in an aysnc task? An illustrative example would be very helpful. P.s. in case it matters to the answerer, I'm looking for a solution with no JS involvement. -
How would I write this url pattern in python 3.6/django1.11? (it is currently in python 2.7/django1.7)
I am very new, and I am doing a tutorial, that is a little bit old. I keep getting an error that this cannot import name 'patterns' then something about include, then syntax and so on. So what is wrong this section? How would I write it current day? Thank you for your time. from django.conf.urls import patterns, include, url from django.contrib import admin from djangonote.views import home_view urlpatterns = patterns('', url(r'^$', home_view, name='home'), url(r'^notes/', include('notes.urls', namespace='notes')), ) -
using Count on rows from third table in django
I have this models: class MemberGroup(models.Model): name=models.CharField(max_length=15) class Subgroup(models.Model): name=models.CharField(max_length=15) member_group=models.ForeignKey(MemberGroup,related_name='membergroup_subgroup') class Members(models.Model): user=models.ForeignKey(User) Now I want to count the number of members in a group but each member is part of a subgroup. my_groups=MemberGroups.objects.all().values('id','name').annotate(c=Count('membergroup_subgroup')) gives me number of subgroups in each group. But I want member instead and my attempts so far failed. -
Django Extend Model with Optional Fields
I have a django model that looks something like class Person(models.Model): name = models.CharField(max_length=100) favorite_color = models.CharField(max_length=100) favorite_candy = models.CharField(max_length=100) and I want to make a template model for it. Basically, I want a model that can have an arbitrary amount of Person's fields filled out. For instance, say I wanted to have a template for Person that likes chocolate - I'd say something like chocolate_template = PersonTemplate(favorite_color='chocolate') and if I wanted someone whose name is Gerald, I could say gerald_template = PersonTemplate(name='Gerald'). The thought is that I could use these template objects to later pre-fill a Person creation form. My main question is an implementation question. It's totally possible for me to make a template like so class PersonTemplate(models.Model): name = models.CharField(max_length=100, blank=True) favorite_color = models.CharField(max_length=100, blank=True) favorite_candy = models.CharField(max_length=100, blank=True) but the code is horrible in that I have to manually copy-paste the contents of the Person class. This means that if I change Person, I have to remember to update PersonTemplate. I was wondering if there's a prettier way to make a 'child' of a model where all of the fields are optional. Setting all of the fields of Person to blank=True and adding an isTemplate field … -
including urls of one app into urls file of another app in django
I have two apps in my project, institute and students. I have included the urls of institute app in root url file. root urls.py urlpatterns += [ url(r'^insti/', include('institute.urls', namespace='institute')), ] institute/urls.py file from institute import views from django.conf.urls import url, include app_name = "institute" # institute urls urlpatterns = [ url(r'^$', views.institute_home, name='home'), url(r'^signin/$', views.signin, name='signin'), url(r'^logout/$', views.institute_logout, name='logout'), # other urls here ] # students urls in institute urlpatterns += [ url(r'^student/', include('students.urls', namespace='students')), ] students/urls.py file from django.conf.urls import url from students import views app_name = "students" urlpatterns = [ url(r'^$', views.students_home, name="students_home"), url(r'^register/$', views.register, name="register"), # other urls ] When I am hitting urls like localhost/insti/sigin, localhost/insti/<anything> it works fine, but as soon as I hit the url localhost/insti/students it throws me error 'students' is not a registered namespace somewhere in my code at line return HttpResponseRedirect(reverse("students:signin")) Please suggest if the way I am including students urls in institute's url is wrong or there is some other issue? -
Django naive datetimes showing differently in different timezones
I have a Django web application that is showing varying object datetime values between timezones despite having disabled timezone support. The application uses HighCharts.js and I want the graph to show points at 9:30 EST, 11:00 EST, 12:30 EST, 14:00 EST, 15:30 EST regardless of the timezone of the visitor. The objects are created when a CRON process executes each day at 9:30, 11:00, 12:30, 14:00, 15:30. The hardware time of the server reads as follows using sudo hwclock --show: Tue 20 Jun 2017 11:54:46 EDT -0.514948 seconds. Settings in Django settings.py file: USE_I18N = False USE_L10N = False USE_TZ = False An example of the datetime values that are stored in the database: 2017-06-19 09:30:00 2017-06-19 11:00:00 2017-06-19 12:30:00 2017-06-19 14:00:00 2017-06-19 15:30:00 The graph currently shows the following times depending on the location of the visitor: In PST the graph shows: 9:30, 11:00, 12:30, 14:00, 15:30 In MST the graph shows: 10:30, 12:00, 13:30, 15:00, 16:30 In CST the graph shows: 11:30, 13:00, 14:30, 16:00, 17:30 In EST the graph shows: 12:30, 14:00, 15:30, 17:00, 18:30 -
Using Ajax with Django - Is it possible in 1.10
I couldn't send a form through django (1.10) without refreshing the page. I have searched every other related question on Stackoverflow but no success. This is my ajax request: $(document).on('submit', 'signup-form', function(e){ e.preventDefault(); $.ajax({ type: 'POST', url: '{% url "handler:home" %}', data: { firstname:$('#firstname').val(), lastname:$('#lastname').val(), email:$('#email').val(), password1:$('#password1').val(), password2:$('#password2').val(), username:$('#username').val(), csrfmiddlewaretoken:$('input[name=csrfmiddlewaretoken]').val(), }, success:function(){ alert('done'); } }) }); This is my form: <form id="signup-form" class="casemedic-color"> {% csrf_token %} <label><b>E-mail and Username:</b></label> <br> <input class="input-red input-shadow" id="email" type="email" name="email" style="max-width:150px;" placeholder="e-mail">&nbsp;<input class="input-red input-shadow" type="username" id="username" name="username" style="max-width:150px;" placeholder="username"> <br> <label><b>First name and Last name:</b></label> <br> <input class="input-red input-shadow" id="firstname" type="text" name="firstname" style="max-width:150px;" placeholder="first name">&nbsp;<input class="input-red input-shadow" type="text" id="lastname" name="lastname" style="max-width:150px;" placeholder="last name"> <br> <label><b>Password:</b></label> <br> <input class="input-red input-shadow" id="password1" type="password" name="password1" placeholder="password"> <br> <label><b>Confirm Password:</b></label> <br> <input class="input-red input-shadow" id="password2" type="password" name="password2" placeholder="confirm"> <br> <br> <button class="btn casemedic-button" type="submit"><i class="fa fa-user-plus" aria-hidden="true"></i>&nbsp;Sign up</button> <br> <br> </form> This is my view function. (In this case, it should still refresh the page, but it cannot even receive the request to refresh.) This function is inside an app called accounts. (accounts:signup) def signup(request): if request.method == 'POST': if request.POST['username'] and request.POST['password1'] and request.POST['password2'] and request.POST['firstname'] and request.POST['lastname'] and request.POST['email']: if request.POST['password1'] == request.POST['password2']: try: user = … -
can't get right url to serve admin-uploaded image django
I'm trying to get a template to display images uploaded through the admin interface, and I've had zero luck with it. I've tried looking through the pre-existing questions on this topic, and none have helped. Below is my settings, models, view, and template file settings.py import os from os import path # Build paths inside the project like this: os.path.join(BASE_DIR, ...) BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__))) DEBUG = True ALLOWED_HOSTS = [] PROJECT_DIR_PATH = path.dirname(path.normpath(path.abspath(__file__))) INSTALLED_APPS = [ 'about.apps.AboutConfig', 'forms.apps.FormsConfig', 'resources.apps.ResourcesConfig', 'contact.apps.ContactConfig', 'blog.apps.BlogConfig', 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', ] 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', ] ROOT_URLCONF = 'nydkcd11.urls' TEMPLATES = [ { 'BACKEND': 'django.template.backends.django.DjangoTemplates', 'DIRS': [], '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', 'django.template.context_processors.media', 'django.template.context_processors.static', ], }, }, ] WSGI_APPLICATION = 'nydkcd11.wsgi.application' DATABASES = { 'default': { 'ENGINE': 'django.db.backends.sqlite3', 'NAME': os.path.join(BASE_DIR, 'db.sqlite3'), } } 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', }, ] LANGUAGE_CODE = 'en-us' TIME_ZONE = 'UTC' USE_I18N = True USE_L10N = True USE_TZ = True MEDIA_ROOT = 'media/' MEDIA_URL = '/media/' STATIC_URL = '/static/' models.py from django.db import models class Division(models.Model): name = models.CharField(max_length = 100) school = models.CharField(max_length …