Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
How can I add a facebook user login functionality
My python version is 3.4.3 and my django version is 1.9.6 . I tried many django facebook registrations apps but almost all the versions are outdated. What I want is to allow users to login via facebook and check if their friends are registered to my website. Your help would be very much appreciated! -
Django on Apache 2.2.15 on centos 6.5
i install django(1.11) and python 3.5 and virtualenv in my centos production server (centos 6.5) when i start django locally using python manage.py runserver i can use the django but i can't serve my django on apache with mod WSGI i test very difference configuration on /conf.s/django.conf but i faced with this error: mod_wsgi (pid=5713): Target WSGI script '/var/www/path/to/site/myapp/wsgi.py' cannot be loaded as Python module. how can i handle this issue ? -
Django: Don't repeat yourself with class based views
Writing django apps, i realize i often repeat myself when creating class based views. The code for a new CreateView or UpdateView almost always looks the same. Also the URLs are very similar. How would one write "generic generic views", or "model agnostic views"? Ideas: I thought about using a constant dictionary "my_models" in my views.py where i define the proper variables for model, form_class, template_name, succeess_message, etc and pick the proper values from the dictionary based on a value provided by the URL. But even this seems to be rather redundant. The admin uses the admin.site.register method, is this a good way to tackle the problem? -
Django recognizing incorrect form in POST
I have the following issue. I am creating a simple web app where you can add some recipes with ingredients. When I GET my RecipeCreateView I am sending it 3 forms - a RecipeForm, IngredientFormset and a ProductForm. The RecipeForm and IngredientFormset are standard forms which are necessary to add a recipe. Lately I've added a ProductForm to give the user an opportunity to quickly add new Products to the database using a modal window and AJAX/POST request. So my main form is the RecipeForm and the ProductForm is only used to add new products using the modal window. My issue is that in my post method my form is recognized as the ProductForm instead of a RecipeForm as you can see . Here are some code snippets: views.py class RecipeCreateView(CreateView): model = Recipe form_class = RecipeForm template_name = "recipes/create.html" def get(self, request, *args, **kwargs): self.object = None form_class = self.get_form_class() form = RecipeForm ingredient_formset = IngredientCreateFormSet() product_form = ProductForm() return self.render_to_response( self.get_context_data(form=form, ingredient_formset=ingredient_formset, product_form=product_form)) def post(self, request, *args, **kwargs): self.object = None form_class = self.get_form_class() form = self.get_form(form_class) ingredient_formset = IngredientCreateFormSet(self.request.POST) if form.is_valid() and ingredient_formset.is_valid(): return self.form_valid(form, ingredient_formset) else: return self.form_invalid(form, ingredient_formset) def form_valid(self, form, ingredient_formset=None): form.instance.author = self.request.user … -
Saving audio from the browser to the backend (Django)
I went through a lot of answers which have already been given but did not understand. Task : I have to get the audio from the user which should be less than one minute and then save it in the backend and send it to Google's Speech Recognition API to get the text. I tried recording in the browser using the MediaRecorder API by using this demo over here https://mido22.github.io/MediaRecorder-sample/. I want to get the recorded audio saved in my Django backend so we can do some post processing on it. -
Do you I need to call 'django-admin.py startproject PROJECT' commant to start a new django project?
I'm starting a new django project using google cloud and bitnami django distribution. I copied working project from my local machine to cloud instance to a projects folder, restarted apache, but unfortunately cannot see my site from outside. According to a documentaion to start a new project I need to run a command django-admin.py startproject PROJECT Do I need to start this command for copied project? -
how to make another class object appear if the one predefined above is True in Django model
I have the following class in mysite/portfolio/models.py class Certification(models.Model): publish_date = models.DateTimeField(auto_now_add=True, blank=True) receive_date = models.DateField(default=datetime.datetime.now(), blank=True) is_expired = models.BooleanField(default=True, name='Has expiration?') expire_date = models.DateField(default=None, blank=True) This is how it looks like in the admin panel: http://prntscr.com/ewscbc How can I make Expire date to be shown only if Will expire? is chosen? -
Django beginner - how to separate the view and template?
I am new to django. How can turn this default from django into separate view and template? <!DOCTYPE html> <html lang="en"><head> <meta http-equiv="content-type" content="text/html; charset=utf-8"> <meta name="robots" content="NONE,NOARCHIVE"><title>Welcome to Django</title> <style type="text/css"> html * { padding:0; margin:0; } body * { padding:10px 20px; } body * * { padding:0; } body { font:small sans-serif; } body>div { border-bottom:1px solid #ddd; } h1 { font-weight:normal; } h2 { margin-bottom:.8em; } h2 span { font-size:80%; color:#666; font-weight:normal; } h3 { margin:1em 0 .5em 0; } h4 { margin:0 0 .5em 0; font-weight: normal; } table { border:1px solid #ccc; border-collapse: collapse; width:100%; background:white; } tbody td, tbody th { vertical-align:top; padding:2px 3px; } thead th { padding:1px 6px 1px 3px; background:#fefefe; text-align:left; font-weight:normal; font-size:11px; border:1px solid #ddd; } tbody th { width:12em; text-align:right; color:#666; padding-right:.5em; } #summary { background: #e0ebff; } #summary h2 { font-weight: normal; color: #666; } #explanation { background:#eee; } #instructions { background:#f6f6f6; } #summary table { border:none; background:transparent; } </style> </head> <body> <div id="summary"> <h1>It worked!</h1> <h2>Congratulations on your first Django-powered page.</h2> </div> <div id="instructions"> <p> Next, start your first app by running <code>python manage.py startapp [app_label]</code>. </p> </div> <div id="explanation"> <p> You're seeing this message because you … -
Django forms doesn`t validate, when i trying to update Image
I use this form for adding and updating posts. When I want to edit post and update image Django adds ['image-clear'] checkbox if post has image. But it doesn`t work. Form is not valid, if I tick checkbox and choose new image.But if I only choose new image (without tick checkbox) it works. I was looking for a long time in what the problem, but I did not find. Can you help me? And sorry for my English forms.py class AddIdeaFrom(forms.ModelForm): class Meta: model = Idea fields = ['title', 'description', 'image'] title = forms.CharField(max_length=500, widget=forms.TextInput(attrs={'class': 'form-control'})) description = forms.CharField(max_length=500, widget=forms.Textarea(attrs={'class': 'form-control'})) image = forms.FileField(required=False) views.py def idea_edit(request,idea_id): if request.method == "GET": idea = Idea.objects.get(id=idea_id) edit_idea = AddIdeaFrom(initial={'title':idea.title,'description':idea.description,'image':idea.image}) return render(request, 'myidea/my/idea_edit.html', {'form':edit_idea, 'comment':idea.comment}) if request.method == "POST": idea = Idea.objects.get(id=idea_id) edit_idea = AddIdeaFrom(request.POST,request.FILES) if edit_idea.is_valid(): edit_idea = AddIdeaFrom(request.POST, request.FILES, instance=idea) if edit_idea.has_changed(): new_idea = edit_idea.save() new_status = Status.objects.get(name = STATUS_REVIEW) new_idea.status = new_status new_idea.save() return redirect('/') else: return HttpResponse('Need some changes') else: form = AddIdeaFrom(instance= idea) return render(request, 'myidea/my/idea_edit.html', {'form': form}) html <form method="post" class="post-form" enctype="multipart/form-data"> {% csrf_token %} <label for="description.for_label" class="col-sm-9">Text</label> {{ form.description }} <label for="description.for_image" class="col-sm-9">Choose Image</label> {{ form.image }} <button type="submit" class="btn btn-space mb-">Add</button> </div> </form> </div> -
Django + AJAX query model without refreshing the page
I'm trying to create an app in Django. I'm struggling to query my model without refreshing the page. What I want is: a form in HTML, text box and a Submit button, and after the button is clicked I want to be able to see the details of the airport. Here's my model: from __future__ import unicode_literals from django.db import models class Airportslist(models.Model): icao = models.TextField(db_column='ICAO', blank=True, null=False, primary_key=True) # Field name made lowercase. type = models.TextField(db_column='Type', blank=True, null=True) # Field name made lowercase. name = models.TextField(db_column='Name', blank=True, null=True) # Field name made lowercase. lat = models.FloatField(db_column='LAT', blank=True, null=True) # Field name made lowercase. lon = models.FloatField(db_column='LON', blank=True, null=True) # Field name made lowercase. elevation = models.IntegerField(db_column='Elevation', blank=True, null=True) # Field name made lowercase. country = models.TextField(db_column='Country', blank=True, null=True) # Field name made lowercase. region = models.TextField(db_column='Region', blank=True, null=True) # Field name made lowercase. def __str__(self): return self.icao Here is my view: def detail(request, icao): first_50_airports = Airportslist.objects.filter(name=icao) template = loader.get_template('nearestAirportApp/index.html') print(first_50_airports[0].lat - 10) context = { 'first_50_airports': first_50_airports, } return HttpResponse(template.render(context, request)) The view is modified, I wanted to make it show first 50 airports from the list and that has worked (without any button press event). I'm trying … -
(django) order queryset like a linked list
My model object is that: class MyModel(models.Model): next = models.OneToOneField(MyModel, blank=True) #note, that the last not have a following object prev = models.OneToOneField(MyModel, blank=True) #note, the first have no previous object ordered = MyModelManager() Is blank=True the right thing? Or should it be null=True? Now I want to have a Manager that orders MyModels like a linked list(That means: the object not having a previous one being the first, and then next objects next): class MyModelManager(models.Manager): def get_queryset(self): return self.order(super(MyModelManager, self).get_queryset()) def order(self, mymodels): #And what to do here? How do I order the queryset correctly? (I can't just create my own list because I need a queryset, don't I?) -
django Use to process and return json from other RESTful services
I have some experience with Python, and started to make a Rest API for my front end apps. In one of those, a photography portfolio hosted as static site, I want to get JSON from 500px, and use it for showing my photos. I can get JSON from 500px, but the problem is hiding its consumer key in the front end JS Code. So, I was thinking of using django for that. Is it possible that my JS code requests the django code, and the django code will get the JSON, process it mayber, and return a JSON for the website? -
Error with url reverse NoReverseMatch at at "post_of_serial" not registered tag in namespace"
Error with url reverse NoReverseMatch at at "post_of_serial" not registered tag in namespace" and this one Reverse for 'post_of_serial' with arguments '()' and keyword arguments '{'slug': ''}' not found. 1 pattern(s) tried: ['series/(?P[\w-]+)/$'] and I want to get this kind of URL "http: //www.mysite.tv / series / Prison_Break / season_5 / episode_2 /" this is my main urls.py from django.conf.urls import include, url from django.contrib import admin urlpatterns = [ url(r'^series/', include("serials.urls", namespace='series')), url(r'^', include("serials.urls", namespace='homeview')), url(r'^admin/', admin.site.urls), ] This is my app urls.py from django.conf.urls import include, url from .views import homeview, post_of_serial, post_of_season, post_of_serie urlpatterns = [ url(r'^$', homeview, name='homeview'), url(r'^(?P<slug>[\w-]+)/$', post_of_serial, name='post_of_serial'), url(r'^(?P<slug>[\w-]+)/$', post_of_season, name='post_of_season'), url(r'^(?P<slug>[\w-]+)/$', post_of_serie, name='post_of_serie'), ] This is my piece of models.py from django.core.urlresolvers import reverse class Series(models.Model): id = models.AutoField(primary_key=True) slug = models.SlugField(unique=False, blank=True) rus_name = models.CharField(max_length=60) eng_name = models.CharField(max_length=60) is_active = models.BooleanField(default=True) season_of_this_series = models.ForeignKey(Season, default=True) serial_of_this_series = models.ForeignKey(Serial, default=True) number_of_series = models.IntegerField(default=0, blank=True, null=True) slug = models.SlugField(unique=False, blank=True) description = models.TextField(max_length=700, blank=True, default=None) timestamp_rus= models.DateTimeField(auto_now_add=True, auto_now=False) updated = models.DateTimeField(auto_now_add=False, auto_now=True) timestamp_eng= models.CharField(max_length=60) time_of_series = models.DecimalField(max_digits=10, decimal_places=2, default=0) def get_absolute_url(self): return reverse("series:post_of_serial:post_of_season:post_of_serie", kwargs={"slug": self.slug}) #return "/posts/%s/" %(self.id) def __str__(self): return "%s | %s" % (self.rus_name, self.number_of_series) class Meta: ordering = ["-timestamp_rus"] verbose_name … -
Django: don't add file field multiple times when adding object programmatically
Let's assume I have a model like following: class SomeModel(models.Model): name = models.CharField(max_length=255, blank=False, null=False) audio_file = models.FileField(upload_to='audio_files') I need to populate a lot of audio files programmatically to the database. Normally I would use Django's get_or_create to make sure that same object isn't inserted multiple times. But I'm having problems to populate objects with file fields. So my question is, how I could ensure that 'SomeModel' with same name and file is inserted only once? The idea should be something like this: name = 'Unique name' audio_file = File(open('audio.mp3', 'rb')) ... ??? SomeModel.objects.get_or_create(name=name, audio_file=audio_file) But this doesn't work, it will give me SuspiciousFileOperation exception. -
Django & Heroku - ImportError: No module named gettingstarted.wsgi
I'm trying to deploy a Django1.10 app to Heoroku, and I followed this guide to add the required configurations. After deploy, application crash and I get a No module named gettingstarted.wsgi ImportError - full traceback as follow: 2017-04-15T12:22:03.430119+00:00 heroku[web.1]: Starting process with command `gunicorn gettingstarted.wsgi --log-file -` 2017-04-15T12:22:05.349515+00:00 app[web.1]: [2017-04-15 12:22:05 +0000] [4] [INFO] Listening at: http://0.0.0.0:40627 (4) 2017-04-15T12:22:05.349596+00:00 app[web.1]: [2017-04-15 12:22:05 +0000] [4] [INFO] Using worker: sync 2017-04-15T12:22:05.352984+00:00 app[web.1]: [2017-04-15 12:22:05 +0000] [9] [INFO] Booting worker with pid: 9 2017-04-15T12:22:05.355385+00:00 app[web.1]: Traceback (most recent call last): 2017-04-15T12:22:05.349135+00:00 app[web.1]: [2017-04-15 12:22:05 +0000] [4] [INFO] Starting gunicorn 19.7.1 2017-04-15T12:22:05.355386+00:00 app[web.1]: File "/app/.heroku/python/lib/python2.7/site-packages/gunicorn/arbiter.py", line 578, in spawn_worker 2017-04-15T12:22:05.355384+00:00 app[web.1]: [2017-04-15 12:22:05 +0000] [9] [ERROR] Exception in worker process 2017-04-15T12:22:05.355387+00:00 app[web.1]: File "/app/.heroku/python/lib/python2.7/site-packages/gunicorn/workers/base.py", line 126, in init_process 2017-04-15T12:22:05.355387+00:00 app[web.1]: self.load_wsgi() 2017-04-15T12:22:05.355386+00:00 app[web.1]: worker.init_process() 2017-04-15T12:22:05.355388+00:00 app[web.1]: self.wsgi = self.app.wsgi() 2017-04-15T12:22:05.355389+00:00 app[web.1]: File "/app/.heroku/python/lib/python2.7/site-packages/gunicorn/app/base.py", line 67, in wsgi 2017-04-15T12:22:05.355389+00:00 app[web.1]: self.callable = self.load() 2017-04-15T12:22:05.355388+00:00 app[web.1]: File "/app/.heroku/python/lib/python2.7/site-packages/gunicorn/workers/base.py", line 135, in load_wsgi 2017-04-15T12:22:05.355390+00:00 app[web.1]: return self.load_wsgiapp() 2017-04-15T12:22:05.355390+00:00 app[web.1]: File "/app/.heroku/python/lib/python2.7/site-packages/gunicorn/app/wsgiapp.py", line 52, in load_wsgiapp 2017-04-15T12:22:05.355390+00:00 app[web.1]: File "/app/.heroku/python/lib/python2.7/site-packages/gunicorn/app/wsgiapp.py", line 65, in load 2017-04-15T12:22:05.355391+00:00 app[web.1]: File "/app/.heroku/python/lib/python2.7/site-packages/gunicorn/util.py", line 352, in import_app 2017-04-15T12:22:05.355391+00:00 app[web.1]: return util.import_app(self.app_uri) 2017-04-15T12:22:05.355392+00:00 app[web.1]: __import__(module) 2017-04-15T12:22:05.355467+00:00 app[web.1]: [2017-04-15 12:22:05 +0000] [9] [INFO] Worker exiting … -
Python/Django - LDAP backend, remove certificate requirement?
I've been using the code from this site for my backend https://djangosnippets.org/snippets/2899/ however I've just started to come into an issue.. I'n my settings.py i have the below: AD_CERT_FILE = '/certs/certfile' # this is the certificate of the Certificate Authority issuing your DCs certificate The path to the file has never existed, however it continued to work. now i have set up an environment on my mac it looks as if this line is now causing problems, because that file doesn't exist. Thus is it possible to change the below to not need a certificate? I'm not using TLS anyway so I'm not sure why its needed? I've tried just hashing out the line and testing again but then the script fails later down the line... def authenticate(self,username=None,password=None): try: if len(password) == 0: return None #dap.set_option(ldap.OPT_X_TLS_CACERTFILE,settings.AD_CERT_FILE) l = ldap.initialize(settings.AD_LDAP_URL) l.set_option(ldap.OPT_PROTOCOL_VERSION, 3) binddn = "%s@%s" % (username,settings.AD_NT4_DOMAIN) l.simple_bind_s(binddn,password) l.unbind_s() return self.get_or_create_user(username,password) except ImportError: self.debug_write('import error in authenticate') except ldap.INVALID_CREDENTIALS: self.debug_write('%s: Invalid Credentials' % username) -
Render image from byte stream stored in mako template in mako template
I am working in Django framework. I have stored image in mysql table. When I access my mysql table from views.py file this image appears as byte stream text whose tyep is string, I want to know how can I pass this byte stream to my img tag in html so that it will appear on my screen. P.S. I do not want to store this image and then pass its source. -
how to track on which page people close the browser. session or log
I created a web that helps people to understand how to make a certain food. And I am trying to gather the data which recipe most of people want to get. What I am asking is "Is there any way that I can get the information when people search a certain information and also on which page they close the browser??? should I look at session or log or else? I really need to track on which page people close the browser. -
Clear all Form Fields on Validation Error in Django
I have a simple user registration form (in forms.py): from django.contrib.auth.models import User class UserForm(forms.ModelForm): password = forms.CharField(widget=forms.PasswordInput validators=[MinLengthValidator(6)]) password_repeat = forms.CharField(widget=forms.PasswordInput) class Meta: model = User fields = ['username', 'password','password_repeat'] If someone tries to enter something and the validation fails I want the same form to be rendered again but all fields should be cleared. At the moment my view looks like this (in views.py): def signup(request): form = UserForm(request.POST or None) if form.is_valid(): user = form.save(commit=False) username = form.cleaned_data['username'] password = form.cleaned_data['password'] password_repeat = form.cleaned_data['password-repeat'] user.set_password(password) user.save() user = auth.authenticate(username=username, password=password) if user is not None and user.is_active: auth.login(request, user) return redirect('/') return render(request, 'signup.html', {'form': form}) The problem is that the form.fields['username'] field still contains the username that was entered and is thus passed to render. I've been searching for a solution a while now but can't find it. My guess is that the solution has something to do with the clean() method that I don't seem to get. -
How To Pagination Angular2 with Django Rest Framework API
I am trying to create a simple blog application using Angular2 with Django Rest Framework. I am implementing pagination in Django, but I do not know how to rendering it in Angular. API has the following structure. Entries are paginated every 5 entries. ng2app/src/app/models/entries.model.ts export interface IEntries { count: any, next: any, previous: any, results: IResults[] } export interface IResults { title: string, body: string, created_at: any, updated_at: any } ng2app/src/app/services/entries.service.ts import { Injectable } from "@angular/core"; import { Http } from "@angular/http"; import 'rxjs/add/operator/toPromise'; import { IEntries } from '../models/entries.model'; @Injectable() export class EntriesService { constructor( private http: Http ){ } getEntries(page: number){ return this.http .get(`http://127.0.0.1:8000/api/entries/?limit=5&offset=` +((page * 5)-5)) .toPromise() .then(response => response.json()) .catch(this.handleError); } private handleError(error: any) { console.error('An error occurred', error); return Promise.reject(error.message || error); } } ng2app/src/app/services/entries.component.ts import { Component, OnInit } from '@angular/core'; import { EntriesService } from '../services/entries.service'; import { IEntries } from '../models/entries.model'; @Component({ selector: 'my-entries', templateUrl: '../templates/entries.component.html', styleUrls: ['../static/entries.component.css'] }) export class EntriesComponent implements OnInit{ title = 'entries'; entries: IEntries[] = []; error: any; public constructor( private entriesService: EntriesService, ){} getEntires(page :number) { this.entriesService .getEntries(page) .then(entries => this.entries = entries) .catch(error => this.error = error); } ngOnInit() { this.getEntires(1); } } ng2app/src/app/templates/entries.component.html … -
Check if user has voted on a certain poll
I've got a list of polls (questions), and would like to check if a certain User has voted on that certain poll. Here's my models: class Question(models.Model): has_answered = models.ManyToManyField(User) question_text = models.CharField(max_length=80) def __str__(self): return self.question_text class Choice(models.Model): question = models.ForeignKey(Question, on_delete=models.CASCADE) choice_text = models.CharField(max_length=100) votes = models.IntegerField(default=0) def __str__(self): return self.choice_text Here's my view when a user votes on a poll: def poll_answer(request): if request.method == 'POST': answer = request.POST.get('answer') question = request.POST.get('question') q = Question.objects.get(question_text=question) choice = Choice.objects.get(id=answer) choice.votes += 1 choice.save() ... I've added a ManyToMany field in my Question model, which after reading the docs I believe is the right way to link the list of Users who have voted on a certain Question, but i'm not sure to be honest. The end goal is to put in my template something like: if request.user in question.has_answered: don't display the poll How exactly would I go about this? -
Compute distance between fields on the same model in GeoDjango
I want to compute the distance between two fields on the same model in GeoDjango. Here is the way I'm trying to do it: posts = Post.objects.filter(location__distance_lte=(ref_location,D(km=F('i_move')) Where location is a PointField and i_move is a float. However, this does not work, with django throwing : float() argument must be a string or a number, not 'F' I also tried to get first the distance with a large number, than annotate, and after that compare the distance to the field: Post.objects.filter(location__distance_lte=(ref_location, D(km=100)) ).annotate(distance=Distance('location', ref_location) ).filter(distance=F('i_move')) This simply does not work, no error are thrown. I could'nt find anyone doing something similar, though I think the issue is not recent. -
wkhtmltopdf not displaying svg content
<script src="https://cdn.rawgit.com/knsv/mermaid/master/dist/mermaid.min.js"> </script> <link rel="stylesheet" href="/static/css/mermaid.css"> <script>mermaid.initialize({startOnLoad:true});</script> <div class="mermaid container center">graph LR 1["1. DbFileInput"]-->3["3. Join"] 2["2. DbFileInput"]-->3["3. Join"] 3["3. Join"]-->4["4. Formula"] 4["4. Formula"]-->5["5. Filter"] 5["5. Filter"]-->6["6. BrowseV2"] 5["5. Filter"]-->8["8. Sort"] 8["8. Sort"]-->7["7. DbFileOutput"]</div> I am trying to generate pdf - wkhtmltopdf from a html page which has flowchart using mermaid js.PDF shows me other contents in html except the svg. What could be the problem. Can anyone suggest what to do ? -
Get the value of input text element after pressing submit button in django
I'm a newbie to Django and started learning it last week. My question is I have a web page which has an input text box and a submit button. I want to capture the input string entered in the next web page (redirecting page) which has been entered in the text box after pressing the submit button in Django. This is how the initial web page looks like I have tried the following: views.py #View for the initial page def index(request): return render( request, 'index.html') #View for the Redirecting page -- This is where I want to catch the text box input def results(request): inp_value = request.GET.get('text_search', 'This is a default value') context = {'inp_value': inp_value} return render( request, 'results.html', context) forms.py from django import forms class TextForm(forms.Form): text_search = forms.CharField(label='Text Search', max_length=100) index.html <form action="/searcher/results/" method="get"> <label for="results">Enter a string: </label> <input id="results" type="text" name="results" value="{{ search_results }}"> <input type="submit" value="submit"> </form> Can anyone point out why I'm not able to get the value of the textbox? Thanks in Advance -
Django change base template based on user authenticaton
I have two base templates: base.html and base_visitor.html. I want base.html to be extended if user is authenticated and base_vistior.html if user is not authenticated. I have already tried this: {% if user.is_authenticated %} {% extends 'base.html' %} {% else %} {% extends 'base_visitor.html' %} {% endif %} {% block title %}{{ title }}{% endblock %} {% block body %} <h1>Title</h1> {% if models %} {% for model in models %} <h2>{{ model.model_number }}<h2> {% endfor %} {% else %} <h3>NO models</h3> {% endif %} {% endblock %} But for some reason this gives me an error: "Invalid block tag on line 3: 'else'. Did you forget to register or load this tag?" Help is appreciated!