Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Django: Apply order by on serialized data
I have 2 serializers: class abcSerializer(serializers.ModelSerializer): created=Field(source='time') result = Field(source='result') class Meta: model = abc fields = ('created','result') order_by = ['-created'] class defSerializer(serializers.ModelSerializer): created=Field(source='time') result = Field(source='result') class Meta: model = def fields =('created','result') order_by = ['-created'] class mainSerializer(serializers.ModelSerializer): obj1 = abcSerializer() obj2 = defSerializer() class Meta: model = main fields = ('obj1','obj2') In views.py: serializer = mainSerializer(data) return Response(record) In UI I am displaying the serialized data as like below: created result abc 1-9-2016 9:30:00 pass def 2-9-2016 10:34:00 fail I am getting the serialized data as below: data = [{'created':'1-09-2106','result':'pass'},{'created':'2-09-2106','result':'fail'}] I want to sort the data as per created field based on latest date. created result def 2-9-2016 9:30:00 fail abc 1-9-2016 10:34:00 pass Couldn't figure it out on how to sort on created on created field Any help will be appreciated!! -
Ordering django many-to-many with through model
Considering Django's example of using a "through" model to specify extra data on many-to-many relationships, only changing the Membership model to look like class Membership(models.Model): person = models.ForeignKey(Person, on_delete=models.CASCADE) group = models.ForeignKey(Group, on_delete=models.CASCADE) order = models.PositiveIntegerField() class Meta: ordering = ('order', ) such that the extra data being stored is an order parameter specifying the order of a Person in a Group. My aim to obtain a queryset for a given Group which contains first all Person instances in the group ordered by order, followed by the remaining Person instances (not in the group) ordered by name. I can do this with two querysets, like # Get all beatles members ordered by the through model qs1 = beatles.members.all().order_by('membership__order') # Get the remaining Persons (those not in the beatles) ordered by name qs2 = Person.objects.exclude(id__in=qs1).order_by('name') These querysets do appear to contain the expected Person instances. However, I need a combined queryset of the two, not just a list or some itertools "chain" object, since I want to feed this to initialize a form field that requires a queryset instance. I tried result_qs = qs1 | qs2 but I find that result_qs can contain duplicates (even though I thought that the union … -
Find all instances of child models matching query
I have base class Publication, which Book and Magazine inherit from. class Author(models.Model): pass class Publication(models.Model): author = models.ForeignKey(Author) class Book(Publication): pass class Magazine(Publication): pass I want to find all Book and Magazine objects with a certain author. Since the foreign key to Author is on the parent class Publication, my attempts at a query all return Publication objects rather than the child classes: # Both of these return Publication objects, not Book/Magazine objects Author.objects.get(pk=1).publication_set Publication.objects.get(author_pk=1) Is there a way to get all instances of child classes with a certain author, without manually running the query for all child classes like Book.objects.get(author_pk=1) (in reality I have more than two child classes)? -
Can't access the project Interval Server Error (Django / WSGI / virtualenv)
I'm trying to set up an existing project in a local environment with the following standards: Uses mod_wsgi; virtualenv; I installed all dependent modules of the project and realized the wsgi configuration, but I get the following return after access the project: 500 Internal Server Error When I run the command python manage.py runserver: Performing system checks... Unhandled exception in thread started by <function wrapper at 0x7f0ae2d5e8c0> Traceback (most recent call last): File "/usr/local/lib/python2.7/dist-packages/django/utils/autoreload.py", line 226, in wrapper fn(*args, **kwargs) File "/usr/local/lib/python2.7/dist-packages/django/core/management/commands/runserver.py", line 116, in inner_run self.check(display_num_errors=True) File "/usr/local/lib/python2.7/dist-packages/django/core/management/base.py", line 426, in check include_deployment_checks=include_deployment_checks, File "/usr/local/lib/python2.7/dist-packages/django/core/checks/registry.py", line 75, in run_checks new_errors = check(app_configs=app_configs) File "/usr/local/lib/python2.7/dist-packages/django/core/checks/urls.py", line 13, in check_url_config return check_resolver(resolver) File "/usr/local/lib/python2.7/dist-packages/django/core/checks/urls.py", line 23, in check_resolver for pattern in resolver.url_patterns: File "/usr/local/lib/python2.7/dist-packages/django/utils/functional.py", line 33, in __get__ res = instance.__dict__[self.name] = self.func(instance) File "/usr/local/lib/python2.7/dist-packages/django/core/urlresolvers.py", line 417, in url_patterns patterns = getattr(self.urlconf_module, "urlpatterns", self.urlconf_module) File "/usr/local/lib/python2.7/dist-packages/django/utils/functional.py", line 33, in __get__ res = instance.__dict__[self.name] = self.func(instance) File "/usr/local/lib/python2.7/dist-packages/django/core/urlresolvers.py", line 410, in urlconf_module return import_module(self.urlconf_name) File "/usr/lib/python2.7/importlib/__init__.py", line 37, in import_module __import__(name) ImportError: No module named urls -- EDIT 1 -- My wsgi.py: #!/home/myproject/bin/python import os, sys, site sys.stdout = sys.stderr site.addsitedir('/home/myproject/lib/python2.7/site-packages') sys.path.insert(0, '/home/myproject/lib/python2.7/site-packages') sys.path.append('/home/myproject/src/myproject/') os.environ.setdefault("DJANGO_SETTINGS_MODULE", "myproject.app.settings") from django.core.wsgi import get_wsgi_application application = … -
How to fetch json response from another url in django?
I have created 2 views in django namely def next_qn_url(request): var test_result1; return JsonResponse({'test_result':test_result1}) def last_qn_url(request): var test_result2; return JsonResponse({'test_result':test_result2}) def test(request): var test; return JsonResponse({'test':test}) i have also registered these views in urls.py urlpatterns = [ url(r'^test/$', views.test, name='test'), url(r'^next_qn_url/$', views.test, name='next_qn_url'), url(r'^last_qn_url/$', views.test, name='last_qn_url'), url(r'.*', views.home, name='home'), ] I send data from my test page to the other 2 views and try to fetch their json response and update my test page with the help of jquery getJSON function. $.getJSON('/next_qn_url/', selected_qn_ans, function(data) { console.log(data); }); $.getJSON('/last_qn_url/', selected_qn_ans, function(data) { console.log(data); }); I am just giving a rough draft here. But in the jsonresponse, i get the whole test page again and again with all html but not json. Is it not correct way to do it or guide me through this process. Thanks -
Store password in non-user model
I am creating a contact form for a client, but don't want to have to worry about collecting his/her email and password for sending/receiving emails. I would prefer to have them submit their information, and be able to update it. I was thinking of doing something along the lines of this: class AdminContactInfo(models.Model): email = models.EmailField() password = models.CharField() How can I store the password for Django to use, but not be visible for privacy reasons. I would like it to work the exact same way as the User model, but am unsure how to store it. -
Django having issues with django-registration-redux
I've been following an online tutorial on django registration. They are using django-registration-redux==1.1, and I have to use django-registration-redux==1.4. I start my local server and go to this: http://127.0.0.1:8000/accounts/register/ I then see this error: TemplateDoesNotExist at /accounts/register/ Request Method: GET Request URL: http://127.0.0.1:8000/accounts/register/ Django Version: 1.9 Python Version: 2.7.10 Installed Applications: ['django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'registration', 'store'] Installed 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.auth.middleware.SessionAuthenticationMiddleware', 'django.contrib.messages.middleware.MessageMiddleware', 'django.middleware.clickjacking.XFrameOptionsMiddleware'] Template loader postmortem Django tried loading these templates, in this order: Using engine django: * django.template.loaders.app_directories.Loader: /Library/Python/2.7/site-packages/django/contrib/admin/templates/base.html (Source does not exist) * django.template.loaders.app_directories.Loader: /Library/Python/2.7/site-packages/django/contrib/auth/templates/base.html (Source does not exist) * django.template.loaders.app_directories.Loader: /Library/Python/2.7/site-packages/registration/templates/base.html (Source does not exist) * django.template.loaders.app_directories.Loader: /Users/xx/Desktop/stoneriverelearning/bookstore/store/templates/base.html (Source does not exist) Template error: In template /Library/Python/2.7/site-packages/registration/templates/registration/registration_form.html, error at line 1 base.html 1 : {% extends "registration/ registration_base.html" %} 2 : {% load i18n %} 3 : 4 : {% block title %}{% trans "Register for an account" %}{% endblock %} 5 : 6 : {% block content %} 7 : <form method="post" action=""> 8 : {% csrf_token %} 9 : {{ form.as_p }} 10 : <input type="submit" value="{% trans 'Submit' %}" /> 11 : </form> Traceback: File "/Library/Python/2.7/site-packages/django/core/handlers/base.py" in get_response 174. response = self.process_exception_by_middleware(e, request) File "/Library/Python/2.7/site-packages/django/core/handlers/base.py" in get_response 172. … -
wget cookies login script: same site, HTTP script works, HTTPS doesn't
I have the same website deployed, but one with SSL and a snakeoil cert the other HTTP. I'm trying to script login using wget. The following script works with the HTTP site but not with the HTTPS. Note its a Django site. Login requires 2 requests. The first request gets the CSRF token in the login form, the second posts the login cred back: rm ${COOKIE_FILE} TOKEN=`wget ${LOGIN_URL} -O- --save-cookies ${COOKIE_FILE} --keep-session-cookies \ --server-response --no-check-certificate \ | grep csrfmiddlewaretoken | sed -r 's/.*value="(.*)".*/\1/'` POST="csrfmiddlewaretoken=${TOKEN}&username=${USERNAME}&password=${PASSWORD}" wget ${LOGIN_URL} -O- --load-cookies ${COOKIE_FILE} --save-cookies ${COOKIE_FILE} \ --keep-session-cookies --no-check-certificate --server-response \ --post-data "$POST" >/dev/null On the SSL site I get this output: --2016-09-13 01:20:38-- https://nowhere.com/accounts/login/ Resolving nowhere.com (nowhere.com)... 10.1.1.123 Connecting to nowhere.com (nowhere.com)|10.1.1.123|:443... connected. WARNING: The certificate of ‘nowhere.com’ is not trusted. WARNING: The certificate of ‘nowhere.com’ hasn't got a known issuer. The certificate's owner does not match hostname ‘nowhere.com’ HTTP request sent, awaiting response... HTTP/1.1 403 FORBIDDEN Date: Mon, 12 Sep 2016 15:20:58 GMT X-Frame-Options: SAMEORIGIN Keep-Alive: timeout=5, max=100 Connection: Keep-Alive Transfer-Encoding: chunked Content-Type: text/html 2016-09-13 01:20:41 ERROR 403: FORBIDDEN. I have verified I can login to the HTTPS site with the same credentials via a browser. I suspect its something to do with … -
postgis and geodjango *and* in filter
I have a filter, that is working but I want to add more brains to it by looking for anything that is +- 12 days So I came up with this: last_date = firstPointCheck.acquisition_date - timedelta(days=12) next_date = firstPointCheck.acquisition_date + timedelta(days=12) object_list2 = object_list.filter(center__distance_lte=(firstPointCheck.center, D(m=deltaCenter)), acquisition_date__lte=firstPointCheck.acquisition_date, acquisition_date__gte=last_date) I am not sure how to and the dates so I can find everything greater than and equal to last date and less than or equal next date? Now -
Django Grappelli Autocomplete M2M
I followed the docs down to the letter and can't get the M2M autocomplete lookup to work in Grappelli. #models.py #main model class Entry(models.Model): title = models.CharField(max_length=60) content = models.TextField() keywords = models.ManyToManyField(Keyword, blank=True) #model I want to be searched through while typing in the autocomplete field class Keyword(models.Model): name = models.CharField(max_length=30) @staticmethod def autocomplete_search_field(): return ('id__iexact', 'name__icontains',) def __str__(self): return '%s' % (self.name) then in admin.py: class EntryAdmin(admin.ModelAdmin): raw_id_fields = ('keywords',) autocomplete_lookup_fields = { 'm2m': ['keywords'], } class KeywordAdmin(admin.ModelAdmin): pass admin.site.register(Entry, EntryAdmin) admin.site.register(Keyword, KeywordAdmin) Image showing that it isn't returning any results even though there's definitely a keyword entry titled 'Finances'. -
Label for input field isn't rendered when ends with non ASCII character
I encountered a strange behavior while using Django forms. In my forms.py I have a user register form, and for each field I have set a label. Then in view I am passing the form into the context. In html file I'm using the form as follows: {% for field in UserForm %} <div class="form-group"> {{field.label_tag}} {{field}} </div> {% endfor %} The problem is that for one field a label is not shown, the <label> tag is not even generated in output html file. The problematic label is: label = 'Imię',. I noticed that when a label ends with non ASCII character, the label is not generated. I tested that for other field labels. I have included # -*- coding: utf-8 -*- at the beginning of the forms.py (otherwise python throws an error about non ASCII characters in file), so that's not the source of this problem. Also I checked in Notepad++ that this file really uses UTF-8 encoding. I'm using Django 1.9 and python version is 2.7.6. Any help is appreciated. -
Django + Ajax + FormData: uploaded file is unicode array
I can't upload images to the server. All attributes there are until images. In request.FILES they are, but only as unicode array of file name. And this error: AttributeError: 'unicode' object has no attribute 'read' It's my view: for _f in request.FILES: print(_f) for _fi in _f: print(_fi) photo = PostPhoto.objects.create(photo = _f, name = str(_f)) photo.save() destination = open('media/photos/'+str(photo.pk)+'.jpeg', 'w') for chunk in _f.read(): destination.write(chunk) destination.close() print(photo) post.photos = photo and it's js: if (file.length <= 10) { if (hasExtension(file, ['jpeg','jpg'])) { console.log('files are correct'); var message = document.getElementById('search_textarea').value; console.log('text'); var body_data = new FormData(); body_data.append('text', message); body_data.append('loc_lat', elements[i].latitude); body_data.append('loc_lon', elements[i].longitude); body_data.append('loc_name', results[i].name); body_data.append('loc_addr', results[i].formatted_address); body_data.append('types', results[i].types); body_data.append('action', null); for(var k = 0; k <= (file.length - 1); k++) { console.log(file[k]); body_data.append(k, file[k], file[k].name); } this.$.ajaxNewPost.body = body_data; this.$.ajaxNewPost.contentType = false; this.$.ajaxNewPost.generateRequest(); console.log('ajax sended'); } else { console.log('incorrect files'); } } else { alert('too match files'); } How i can resolve it? I've tried post it via tastypie, but there i couldn't save image too, because of tastypie returned for me byte-file of this request -
The view blog.views.post_share didn't return an HttpResponse object. It returned None instead
This is views.py from django.shortcuts import render, get_object_or_404 from .models import Post from django.views.generic import ListView from django.core.paginator import Paginator, EmptyPage, PageNotAnInteger from .forms import EmailPostForm from django.core.mail import send_mai def post_share(request, post_id): post = get_object_or_404(Post, id=post_id, status='published') sent = False if request.method == 'POST': form = EmailPostForm(request.POST) if form.is_valid(): cd = form.cleaned_data post_url = request.build_absolute_uri( post.get_absolute_url()) subject = '{} ({}) zachecam do przeczytania "{}"'.format(cd['name'], cd['email'], post.title) message = 'Przeczytaj post "{}" na stronie {}\n\n Komentarz dodany przez {}: {}'.format(post.title, post_url, cd['name'], cd['comments']) send_mail(subject, message, 'admin@myblog.com',[cd['to']]) sent = True else: form = EmailPostForm() return render(request, 'blog/post/share.html', {'post': post, 'form': form, 'sent': sent}) When I click on share post i get this error The view blog.views.post_share didn't return an HttpResponse object. It returned None instead. -
Getting an N-N relation in a template
I have these models (an owner can have multiple cars, and a car can have multiple owners): class Car(models.Model): name = models.CharField(max_length=20) class Owner(models.Model): name = models.CharField(max_length=20) class CarOwner(models.Model): car = models.ForeignKey(Car, default = 0, on_delete=Models.CASCADE) owner = models.ForeignKey(Owner, default = 0, on_delete=Models.CASCADE) and I want to create a template that shows a list of cars with their owners, so I did this: def cars(request): cars = models.Cars.objects.all() return render(request, 'template.html', { "cars": cars }) My template.html is as simple as {% for car in cars %} {{ car.name }} <br> {% endfor %} How can I now refer to all users per car in the template.html file? -
How to Transform document id to document url (through a network call) in a Django Rest framework project?
I have a Django Rest framework project and I have a separate document service running which takes document id and returns signed/unsigned cloudfront url depending on the document. Now, A response may have many image_id's, which can be in its property or in a property's property (nested), or if a property is a list of objects, it can be in all of them. { ... image_id: blah property: [ { image_id: blah2 } ... ] Now i have an idea of iterating object once, collect all ids once and make a batch call, get url's and iterate again and set the image_url field Any better ideas? -
django ORM - prevent direct setting of model fields
I have a Django class class Chat(models.Model): primary_node = models.ForeignKey('nodes.Node', blank=True, null=True, related_name='chats_at_this_pri_node', on_delete=models.SET_NULL) secondary_node = models.ForeignKey('nodes.Node', blank=True, null=True, related_name='chats_at_this_sec_node', on_delete=models.SET_NULL) I want to forbid direct assigning of fields, such as chat.primary_node = some_node and instead create a method chat.assign_node(primary, secondary) that updates nodes via Django Chat.update() model method. The reason is that I want to log all changes to these nodes (count changes and update other model fields with the new count), but dont want myself and other developers to forget that we cannot assign fields directly, as this wouldn't trigger custom assign_node logic. How сan I do that? -
Is django saving objects into database during tests?
I'm trying to write a test - from django.test import TestCase from django.test.client import Client class MyTests(TestCase): def _create_person_object(self): person = Person(email='test@example.com', password='test') person.save() return def _login(): self.client.post('/login/', {'email': 'test@example.com', 'password' : 'test'}) return def setUp(self): self.client = Client() def test_login(self): self._create_person_object() self._login() input('wait and enter') # person = Person.object.get(email ='test@example.com') # self.assertEqual(person.password, 'test') # response = self.client.get('/denied_area/') self.assertEqual(response.status_code, 200) And if I run test, it fails - because password mismatch - so I tried to check what is in database : for this i put input. So when test run,it stops - I check database, but table is empty... But the object (commented part) shows, that it is created....??? -
How does Django handle cancelled or interrupted requests?
Let's say for my django application, I submit a request via the browser. In the middle of the processing, it creates a local resource (e.g., a file), which will be deleted at the end of the request. Now to throw a wrench into things. After my request has created the resource, but before deletion, I cancel the request in my browser. Does django still complete the request and delete the resource? Is there any way within the django code to know when the client connection has been closed, perhaps with some kind of signal? -
Query param decode in python
I'm sending a query param which is "ara%C3%B1a" but, in fact, it should be "araña". How could I decode the string and transform %C3%B1 into Ñ ? I'm using django. Thanks in advance -
Setting up sockets with Django on gninx
I have a Django application running on nginx. This application use sockets, wich (as far as I know) should be proxyied. So I have troubles configuring nginx and other stuff. Same application works fine on Apache/2.4.7, so I assume that it is not a programming mistake. Sockets using is based on Django-Channels and backend is very similar to code from Channels getting started. For server configuration I used this manual. In the beginning I had just one problem: I got 200 request answer instead of 101 on socket creation. After many manipulations (configuring and newer versions installing) and information collecting I came to current situation: I start uwsgi separately for sockets: uwsgi --virtualenv /home/appname/env/ --http-socket /var/run/redis/redis.sock --http-websock --wsgi-file /home/appname/appname/appname/wsgi.py On this step on socket creation var socket = new WebSocket("ws://appname.ch/ws/64"); I get WebSocket connection to 'ws://appname.ch/ws/64' failed: Error during WebSocket handshake: Unexpected response code: 502 and sure 2016/09/12 12:00:26 [crit] 30070#0: *2141 connect() to unix:/var/run/redis/redis.sock failed (13: Permission denied) while connecting to upstream, client: 140.70.82.220, server: appname.ch,, request: "GET /ws/64 HTTP/1.1", upstream: "http://unix:/var/run/redis/redis.sock:/ws/64", host: "appname.ch" in nginx error log. After chmod 777 /var/run/redis/redis.sock I get responce WebSocket connection to 'ws://appname.ch/ws/64' failed: Error during WebSocket handshake: Unexpected response code: 404 and … -
Passing Django Model to Template
I have a little problem which I can't seem to get my head around. It seems like a very trivial thing but I just can't figure it out. Essentially what I'm trying to do is to create a Project model which holds information on a certain project and then have another model called Link which holds the name of the link such as 'Get Program' or 'Download Release' and have a URLField which holds the URL for those links and is child of Project. So far my models.py is as below: from django.db import models class Project(models.Model): name = models.CharField(max_length=255) description = models.TextField() def get_name(self): return self.name def get_description(self): return self.description def __str__(self): return self.name class Link(models.Model): project = models.ForeignKey(Project) name = models.CharField(max_length=255) url = models.URLField() def get_name(self): return self.name def __str__(self): return self.name Problem is in my views.py I want to be able to pass Projects object so I can iterate over them and display all links for each project including the project objects fields such as name and description. So far I've done: projects = Project.objects.all() links = Link.objects.all() context = { 'projects': projects, } -
Same Form different results?
I have a create form and update form both using the same form with custom widgets some jquery date/time pickers. from widgets import SelectDateTimeWidget, SplitDateTime class CreateEvent(forms.ModelForm): class Meta: model = Event fields = ['title', 'start', 'end', 'description', 'category'] widgets = { 'start': SplitDateTime(date_format= '%d/%m/%Y'), 'end': SplitDateTime(date_format= '%d/%m/%Y') } The create form works fine when i am actually creating an event, but if i use the update view i get the correct details pre-filled but it seems to change date format. for example if i put 13/8/2016 in the create view its fine but if i put it within the update view i get a validation error, if i then change the date to 12/08/2016 it works, it's like one date format is dd/mm/yyyy and the other mm/dd/yyyy Plus the jquery does not work? I don't get it? class EventUpdateView(UpdateView): form_class = CreateEvent model = Event def get_success_url(self): return reverse('calendar_current_month') class EventCreateView(CreateView): form_class = CreateEvent model = Event def form_valid(self, form): Event = form.save(commit=False) Event.created_by = self.request.user Event.save() return HttpResponseRedirect('/calendar/') def calctime(start, end): start_end = start - end return start_end -
django non model form - use of meta to order fields of inherited form
I'm trying to reorder the rendering of the fields of a standard django form. The form inherits from a base form and builds on that. In a similar way to using Meta and fields to order and specify fields for a model form can this be used to reorder fields for an inherited form or what is the best way to achieve this? (eg something like:) class SignupForm(allauthforms.SignupForm): def __init__(self, *args, **kwargs): super().__init__(*args, **kwargs) class Meta: fields = ['email', 'password2'] -
whats the proper way to automate a website
At the risk of being down voted and being told off, please hear me out and at least offer me some advice should you so choose to do so. what I'm trying to accomplish is a site that obtains data from other sites via scraping or using a sites rss feed to store things like the image path, title of the story and text in my database so That I can display it in a techmeme or drudge report like fashion. I want this to happen every 5 or so hours and I want to delete very old things, and I want it all to happen without me having to do it manually. I am completely self taught and have been advised on using rabbitmq with celery. now i'm being advised to use redis. I just watched a video last night on youtube by new circle training and the speaker said twice on rabbitmq and not using it as a backend and he said if you get anything from what I'm saying please get that. But I also know people have biases sometimes for stacks and languages. I have none, I just want my project to work. In essence or … -
Django URL behavior dev vs deploy
I'm having a interesting issue with a login modal - everything works fine in development, but not in production. The basic idea is that, when the name of a school is appended to the login url, that school name is taken by the view and an image is returned; the view immediately redirects back to the same login template, which now displays the image. urls.py segment #authentication url(r'^login/(?P<school_name>\w+)',view=views.LoginView,name='loginschool'), #url(r'^',view=views.LoginView), url(r'^login/',view=views.LoginView,name='login'), loginindex.html modal <!-- Login Modal --> <div class="modal fade" id="LoginModal" role="dialog" > <div class="modal-dialog" style="width:380px;"> <!-- Modal content--> <div class="modal-content"> <div class="modal-header" style="padding:5px 10px;"> <button type="button" class="close" data-dismiss="modal">&times;</button> <h4>Log in to SBGBook</h4> </div> <div class="modal-body" style="padding:10px 10px;"> <div style=" overflow: hidden; margin:auto;"> {% if school_image %} <div style=" float: left;"> <img src="{{ school_image.url }}" width="100" height="100" /> </div> {% endif %} <div> <form data-parsley-validate method="post" id="loginform" action="" enctype="multipart/form-data" data-parsley-trigger="focusout"> {% csrf_token %} {{ userform.as_p }} <input type="submit" class="btn submit" id="lgnbtn" name="LogIn" value="Log In" /> </form> </div> </div> </div> </div> </div> views.py snippet def LoginView(request,school_name=None): template_name = 'gbook/login/loginindex.html' if request.method == "GET": userform = UserForm(prefix='LogIn') if school_name != None: school = School.objects.get(Urlname=school_name) school_image = school.BigLogo else: school_image = None context = {'userform':userform,'school_image':school_image} return render(request,'./gbook/login/loginindex.html', context) elif request.method == "POST": f = …