I was trying out ImageField in the models, But Image upload do not work when I try to upload from the forms. But it works when I upload it from the admin page.
Any way to debug is also helpful
My model-
class Inventory(models.Model):
"""docstring for Inventory"""
name = models.CharField(max_length=100,default='Something')
image = models.ImageField(null=True, blank=True)
description = models.CharField(max_length=100, default='Describe Something')
price = models.IntegerField( default=0)
My Form-
class InventoryForm(forms.ModelForm):
class Meta:
model = Inventory
fields = ['name','description','price','image']
widgets = {
'name' : forms.TextInput(attrs={"placeholder":"Name", "onfocus":"this.value = '';","onblur":"if (this.value=='') this.value = this.defaultValue","required":""}),
'description' : forms.TextInput(attrs={"placeholder":"Email", "onfocus":"this.value = '';","onblur":"if (this.value=='') this.value = this.defaultValue","required":""}),
'price' : forms.NumberInput(attrs={"placeholder":"Price","onfocus":"this.value = '';","onblur":"if (this.value=='') this.value = this.defaultValue","required":""}),
}
Settings -
MEDIA_URL = '/media/'
MEDIA_ROOT = os.path.join(BASE_DIR, "media/")
template -
<form action="" method="post" enctype="multipart/form-data"> {% csrf_token %}
{{form}}
<input type="submit" value="Send">
</form>
url -
from django.contrib import admin
from django.urls import path, include, re_path
from django.conf import settings
from django.conf.urls.static import static
urlpatterns = [
path('',include('inventory.urls')),
path('<int:id>',include('inventory.urls')),
path('admin/', admin.site.urls),
]+ static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT)
My Views-
def index(request):
form = InventoryForm(request.POST or None)
if form.is_valid():
form.save()
form = InventoryForm()
else:
form = InventoryForm()
inventory = Inventory.objects.all()
context = {'form' : form, 'all_inventory' : inventory}
return render(request, 'inventory/index.html',context)
Regards,
Deepak Dash
In your views.py. Change:
form = InventoryForm(request.POST or None)
to
form = InventoryForm(request.POST, request.FILES or None)
Because, Files in django post request are in request.FILES dictionary. You have to send that to forms as well.
How about adding upload_to in models in image field and add default image also this will come in handy later on or not your choice:
models.py
class Inventory(models.Model):
"""docstring for Inventory"""
name = models.CharField(max_length=100,default='Something')
image = models.ImageField(upload_to='/your_file_name/',default='default.png')
description = models.CharField(max_length=100, default='Describe Something')
price = models.IntegerField(default=0)
Related
I am trying to make a simple mail service with very simple architecture project. At this moment my backend part of development is almost done, but i have stoped already fro two days because of i have no idea why does images saving not working.
Obviously, i expect that user upload his profile avatar and it's saving to path i've set in upload_to. Path to image must looks like profiles/UserName/his_profile_img.jpeg
For last two days i have spent more than 12 hours by trying to solve it.
This is my model where is my trouble ImageField:
from django.db import models
from datetime import datetime, timedelta
from django.contrib.auth.models import User
def username(user, file):
string_username = str(user).split()[0]
return f"profiles/{string_username}/{file}"
class Profile(models.Model):
user = models.OneToOneField(User, on_delete=models.CASCADE, related_name="Profile")
##### This is here
avatar = models.ImageField(default="/profiles/profile.png", upload_to=username)
name = models.CharField(max_length=30, blank=True)
surname = models.CharField(max_length=30, blank=True)
email = models.EmailField(max_length=64, blank=True)
bio = models.CharField(max_length=1024, blank=True)
def username(self):
return self.user.username
#property
def joined(self):
joined = self.user.date_joined.strftime("%d %B %Y")
is_today = joined == datetime.today().strftime("%d %B %Y")
if is_today:
return "today"
is_yesterday = joined == datetime.date(datetime.today() - timedelta(days=1)).strftime("%d %B %Y")
if is_yesterday:
return "yesterday"
return f"{joined}"
def __str__(self):
return f"{self.user} profile"
This is a view function, which doesn't save image:
def my_profile(request):
if not request.user.is_authenticated:
return redirect('login')
user_profile = Profile.objects.get(user=request.user)
sent_messages = Mail.objects.filter(from_user_inf=request.user).count()
received_messages = Mail.objects.filter(to_user_inf=request.user).count()
context = {
"profile": user_profile,
"sent": sent_messages,
"received": received_messages
}
if request.method == 'POST':
user_profile.name = request.POST.get("name")
user_profile.surname = request.POST.get("surname")
user_profile.email = request.POST.get("email")
user_profile.bio = request.POST.get("bio")
avatar = request.FILES.get("avatar")
# I've also tried get image by:
##### request.POST.get("avatar")
##### saving image by "with open" command(this is too weird)
if avatar:
user_profile.avatar = avatar
user_profile.save()
messages.info(request, "Saved successfully !")
return render(request, 'my_profile.html', context=context)
return render(request, 'my_profile.html', context=context)
And my_profile.html file and a piece of code where i set image uploading:
<div>
<img class="img" src="{{ profile.avatar.url }}" width="150" height="150">
<label for="file" cursor="pointer" class="btn">Change Photo</label>
<input id="file" style="visibility:hidden;" name="avatar" type="file" accept="image/*">
</div>
Yes, i did correct settings and added it to urls.
settings.py ---> ROOT and URL media, static settings :
STATIC_URL = '/static/'
STATIC_ROOT = BASE_DIR / 'static'
MEDIA_ROOT = BASE_DIR / 'media'
MEDIA_URL = '/media/'
urls.py:
urlpatterns = [
### There are my urls
]
if settings.DEBUG:
urlpatterns += static(settings.STATIC_URL, document_root=settings.STATIC_ROOT)
urlpatterns += static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT)
Thanks for attention, hope we can solve it !
It's easy with ModelForms:
# forms.py
from django import forms
# import your model here
class ProfileForm(forms.ModelForm):
class Meta:
model = Profile
fields = ('name', 'surname', 'email', 'bio', 'avatar')
# views.py
# imports...
def my_profile(request):
if not request.user.is_authenticated:
return redirect('login')
user_profile = Profile.objects.get(user=request.user)
sent_messages = Mail.objects.filter(from_user_inf=request.user).count()
received_messages = Mail.objects.filter(to_user_inf=request.user).count()
context = {
"profile": user_profile,
"sent": sent_messages,
"received": received_messages
}
if request.method == 'POST':
form = ProfileForm(
instance=user_profile, data=request.POST, files=request.FILES
)
if form.is_valid():
form.save()
messages.info(request, "Saved successfully !")
# Best use a redirect to a success page here.
# Otherwise, if the user clicks reload, the form will be resent.
return render(request, 'my_profile.html', context=context)
else:
form = ProfileForm(instance=user_profile)
# Use the form in the template! #see: https://docs.djangoproject.com/en/3.2/topics/forms/#the-template
# If you need personalize for bootstrap, etc #see: https://github.com/django-crispy-forms/django-crispy-forms
context['form'] = form
return render(request, 'my_profile.html', context=context)
If you need upload the file without the ModelForm, manually save the file to a server path and then set this path (relative to MEDIA_ROOT) in the model. See the handle_uploaded_file in this link https://docs.djangoproject.com/en/3.2/topics/http/file-uploads/#basic-file-uploads.
I stack. I try many thinks. I want to put 2 forms in my mainpage. Models, forms in index.html, ModelForm, save(), urls.. I think everything ok. But submit button do nothing.
#models.py
from django.db import models
class Iletisim(models.Model):
DURUM = [
('KT', 'Keşif Talebi'),
('AB', 'Arıza Bildirimi'),
('IL', 'İletişimden'),
]
SINIF = [
('Konut', (
('SI', 'Site '),
('DA', 'Apartman Dairesi'),
('VI', 'Yazlık/Bağ/Villa'),
)
),
('İşyeri', (
('OF', 'Ofis/Büro/Dükkan'),
('FA', 'Fabrika/Şantiye/Otel/Okul'),
)
),
('DG', 'Diğer'),
]
name = models.CharField(max_length=100, verbose_name="Ad/Soyad")
phone = models.CharField(max_length=100, verbose_name="Telefon")
address = models.CharField(max_length=250, verbose_name="Adresi")
message = models.CharField(max_length=1000, verbose_name="Mesaj")
email = models.EmailField(max_length=40, verbose_name="E-Posta")
province= models.CharField(max_length=40,verbose_name="Şehir")
tarih = models.DateTimeField(default=None)
basvuru = models.CharField(max_length=2, choices=DURUM)
sinif = models.CharField(max_length=2, choices=SINIF)
class Meta:
ordering = ["tarih", "email"]
verbose_name = "Mesaj"
verbose_name_plural = "Mesajlar"
def __str__(self):
return self.basvuru
My forms folder
from django.shortcuts import redirect, render
from django.forms import ModelForm
from apps.giris.models import Iletisim
class Kesif_Form(ModelForm):
class Meta:
model = Iletisim
fields = '__all__'
def kesif_kayit(request):
if request.method=='POST':
form = Kesif_Form(request.POST)
if form.is_valid():
yeni_kesif = Iletisim()
yeni_kesif.name = request.POST.get("name")
yeni_kesif.phone = request.POST.get("phone")
yeni_kesif.address = request.POST.get("address")
yeni_kesif.message = request.POST.get("message")
yeni_kesif.email = request.POST.get("email")
yeni_kesif.province = request.POST.get("province")
yeni_kesif.tarih = request.POST.get("tarih")
yeni_kesif.basvuru = request.POST.get("basvuru")
yeni_kesif.sinif = request.POST.get("sinif")
yeni_kesif.save()
return redirect('index')
else:
form = Kesif_Form()
context={'form' : form}
return render(request,'index.html',context)
Main class
...
from forms.formlar import Kesif_Form
class Anasayfa_View(TemplateView, Kesif_Form):
template_name = 'index.html'
def get_context_data(self, **kwargs):
...
context['kform'] = Kesif_Form
...
return context
index.html
...
{{ kform.errors }}
<form action="{% url 'kesif' %}" method="POST" class="php-email-form php-email-form animate__animated animate__fadeInRight">
{{ kform.errors }}
{{ kform }}
<input type="submit" value="gir">
</form>
...
urls.py
...
from forms.formlar import kesif_kayit
urlpatterns = [
path('admin/', admin.site.urls),
path('', Anasayfa_View.as_view(), name='grsndx'),
path('kesif/', kesif_kayit, name='kesif'),
path('<str:ktgr>/', Detaylar_View.as_view(), name='dtyndx'),
path('<str:ktgr>/<str:bslk>/', Detay_View.as_view(), name='dtydty'),
]
and submit not work, every fields in form, I want 2 forms but I have not work anyone.
help..
structure
-project
-apps
-giris
-models.py
+detay
...
+env
-fls
-settings
-urls
-forms
-formlar.py
...
-templates
-index.html
...
-manage.py
...
If you are using Django model form than you have to do something like this first create form class
class Kesif_Form(ModelForm):
class Meta:
model = Iletisim
fields = '__all__'#here you to defined specific you field or all the field
than you have to submit it like this
def kesif_kayit(request):
if request.method=='POST':
form = Kesif_Form(request.POST)
if form.is_valid():
form.save()
return redirect('index')
else:
form = Kesif_Form()
context={'form' : form}
return render(request,'index.html',context)
you don't have save it manually Django Model Form will save it for you.
I am trying to do multiple file uploads in Django but am encountering some errors: form.is_valid() returning false. <br>
I have tried printing form.erorrs and it gives me the following:
<ul class="errorlist"><li>uploaded_images<ul class="errorlist"><li>“b'\xbd\x06D\xcd3\x91\x85,\xdf\xa5K\n'” is not a valid value.</li></ul></li></ul>
I am not sure how to interpret this general error. Been searching for quite some time but couldn't find an answer.
Edit:
Im also encountering a "This field is required." error
Perhaps this screenshot may help with debugging:
I must be missing something simple but I just can't find it!!
Another pair of eyes to help me sieve through would be very appreciated!
views.py
from django.shortcuts import render,redirect
from django.views.generic.edit import FormView
from .forms import BRForm
from .models import *
class BRHomeView(FormView):
form_class = BRForm
model = TargetImage
template_name = 'br/br-home.html'
context_object_name = 'bankrecon'
def get(self, request):
form = BRForm(request.POST, request.FILES)
return render(request, self.template_name, {'form': form, 'title': 'Bank Reconcilation'})
def post(self, request, *args, **kwargs):
form_class = self.get_form_class()
form = self.get_form(form_class)
files = request.FILES.getlist('uploaded_images')
print("POST")
print(request.POST)
print("FILES")
print(request.FILES)
print(form.errors)
if form.is_valid():
form.save()
return redirect('br-home')
models.py
from django.db import models
# Create your models here.
class UploadedImages(models.Model):
image_files = models.ImageField(null=True, blank=True, upload_to='images/')
class TargetImage(models.Model):
invoice_date = models.DateTimeField()
recon_date = models.DateTimeField()
uploaded_images = models.ManyToManyField(UploadedImages)
def __str__(self):
return self.invoice_date
forms.py
from django import forms
from django.core.validators import FileExtensionValidator
from .models import *
class BRForm(forms.ModelForm):
class Meta:
model = TargetImage
fields = ('invoice_date', 'recon_date', 'uploaded_images')
widgets = {
'invoice_date': forms.DateInput(attrs={'type': 'date'}),
'recon_date': forms.DateInput(attrs={'type': 'date'}),
'uploaded_images': forms.ClearableFileInput(attrs={'multiple': True, 'accept':'.jpeg, .png, .jpg'}),
}
relevant template code:
<div class="mt-5 d-flex justify-content-center">
<form action="" enctype="multipart/form-data" method="POST">
{% csrf_token %}
{{ form.as_p }}
<div class="d-flex justify-content-center">
<button class="btn btn-success mt-3" type="submit">Submit</button>
</div>
</form>
</div>
Extra info: My request.POST and request.FILES seems to be working fine:
POST
<QueryDict: {'csrfmiddlewaretoken': ['hiding this'], 'invoice_date': ['2021-02-01'], 'recon_date': ['2021-02-01']}>
FILES
<MultiValueDict: {'uploaded_images': [<InMemoryUploadedFile: first_slide (1).jpg (image/jpeg)>, <InMemoryUploadedFile: fourth_slide (1).jpg (image/jpeg)>]}>
Thank you all!!
Some errors that I see in your code:
You're trying to render a POST request in your get method.
You're not passing any data from POST request to your form instance. That's why is_valid() is returning False.
Change your code to something like this and see if it works:
...
def get(self, request):
form = BRForm()
return render(request, self.template_name, {'form': form, 'title': 'Bank Reconcilation'})
def post(self, request, *args, **kwargs):
form = BRForm(request.POST)
if form.is_valid():
form.save()
return redirect('br-home')
I have managed to solve this issue! <br>
Link: https://stackoverflow.com/a/60961015/10732211 <br>
I overhauled the entire thing and followed the above link. Probably the models relations have some issues that does not work. <br>
views.py
class BRHomeView(FormView):
# model = TargetImage
template_name = 'br/br-home.html'
context_object_name = 'bankrecon'
def get(self, request):
form = BRFormExtended()
return render(request, self.template_name, {'form': form, 'title': 'Bank Reconcilation'})
def post(self, request, *args, **kwargs):
form = BRFormExtended(request.POST,request.FILES)
files = request.FILES.getlist('image_files')
if form.is_valid():
print("Form Valid")
print(form.cleaned_data['invoice_date'])
print(form.cleaned_data['recon_date'])
user = request.user
invoice_date = form.cleaned_data['invoice_date']
recon_date = form.cleaned_data['recon_date']
target_image_obj = TargetImage.objects.create(user=user,invoice_date=invoice_date, recon_date=recon_date)
for file in files:
UploadedImage.objects.create(target_image=target_image_obj,image_files=file)
else:
print("Form Invalid")
return redirect('br-home')
forms.py
class BRForm(forms.ModelForm):
class Meta:
model = TargetImage
fields = ['invoice_date', 'recon_date']
widgets = {
'invoice_date': forms.DateInput(attrs={'type': 'date'}),
'recon_date': forms.DateInput(attrs={'type': 'date'}),
}
class BRFormExtended(BRForm):
image_files = forms.FileField(widget=forms.ClearableFileInput(attrs={'multiple': True}))
class Meta(BRForm.Meta):
fields = BRForm.Meta.fields + ['image_files',]
models.py
from django.contrib.auth.models import User
from django.utils import timezone
class TargetImage(models.Model):
user = models.OneToOneField(User,on_delete=models.CASCADE)
uploaded_date = models.DateTimeField(default=timezone.now)
invoice_date = models.DateTimeField()
recon_date = models.DateTimeField()
def __str__(self):
return self.user.__str__()
class UploadedImage(models.Model):
target_image = models.ForeignKey(TargetImage, on_delete=models.CASCADE)
image_files = models.ImageField(null=True, blank=True, upload_to='images/')
Also, it would be helpful to have a media root folder and edits to urls.py is also required.
urls.py
from django.urls import path
from .views import BRHomeView
from django.conf import settings
from django.conf.urls.static import static
urlpatterns = [
path('', BRHomeView.as_view(), name='br-home'),
] + static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT)
settings.py
MEDIA_URL = '/media/'
MEDIA_ROOT = os.path.join(BASE_DIR, 'media')
STATIC_URL = '/static/'
STATICFILES_DIRS = (os.path.join(BASE_DIR, "static"),)
Hopefully this will help someone!
I am adding a search field in my blog so people can put the name of the blog they want to read and a list of items come up and after clicking on any of the list items, it will redirect to the detail view. However, in my case,If I put anything in search, it is not redirecting to a detail view but going to http://127.0.0.1:8000/home/search/2 instead of http://127.0.0.1:8000/home/list/2/.
I have posted my models, views, URLs and template files below.
Is there any reverse method I need to use here to redirect and what changes I need in my template file?
models.py
from django.db import models
class Category(models.Model):
cat_name = models.CharField(max_length = 256, blank = True)
def __str__(self):
return self.cat_name
class Blog(models.Model):
name = models.CharField(max_length = 256, blank = True)
pub_date = models.DateTimeField('date published')
text = models.TextField(blank = True)
category = models.ForeignKey(Category, on_delete=models.CASCADE,
related_name='categories', verbose_name = 'blog_categories')
def __str__(self):
return self.name
views.py
from django.shortcuts import render
from homepage.models import Blog
from django.views.generic import TemplateView, ListView, DetailView
from homepage import models
from django.db.models import Q
class Home(TemplateView):
template_name = 'homepage/index.html'
class BlogListView(ListView):
context_object_name = 'blogs'
model = models.Blog
template_name = 'homepage/blog_list.html'
class BlogDetailView(DetailView):
context_object_name = 'blogs_detail'
model = models.Blog
template_name = 'homepage/blog_detail.html'
def get_queryset(self):
query = self.request.GET.get('q')
return Blog.objects.filter(
Q(name__icontains = query) | Q(name__icontains = query) )
class SearchResultsListView(ListView):
model = Blog
context_object_name = 'blog_list'
template_name = 'homepage/search_result_list.html'
def get_queryset(self):
query = self.request.GET.get('q')
return Blog.objects.filter(
Q(name__icontains = query) | Q(name__icontains = query) )
urls.py
from django.urls import path
from homepage import views
from homepage.views import SearchResultsListView
app_name = 'homepage'
urlpatterns = [
path('', views.Home.as_view(), name = 'index'),
path('list/', views.BlogListView.as_view(), name = 'blog-list'),
path('list/<int:pk>/', views.BlogDetailView.as_view(), name = 'blog-list'),
path('search/', SearchResultsListView.as_view(), name = 'search_result'),
]
index.html
<div class="grid-item-1">
<h1>G</h1>
<input type="button" name="" value="Back to Home" placeholder="">
<form action="{% url 'home:search_result' %}" method = 'get'>
<input type="text" name="q" placeholder="search">
</form>
</div>
search_result_list.html
{% for blog in blog_list %}
<ul>
<li>
{{blog.name}}
{{blog.address}}
here
</li>
</ul>
{% endfor %}
the URL redirects to http://127.0.0.1:8000/home/search/2 and its a 404 page.
how can I redirect it to the detail view page http://127.0.0.1:8000/home/list/1/ and see the detail of the list pulled by search result.
The reason this happens is because {{ blog.id }} just contains a number, for example 2. It will be appended to the URL. You can fix this by prepending the URL with a slash (/) and write list with:
{{blog.name}}
{{blog.address}}
here
But it is likely better to make use of the {% url … %} template tag [Django-doc]:
{{blog.name}}
{{blog.address}}
here
In your BlogDetailView, there is no q parameter, so you can remove the get_queryset:
class BlogDetailView(DetailView):
context_object_name = 'blogs_detail'
model = models.Blog
template_name = 'homepage/blog_detail.html'
# no get_queryset
Furthermore perhaps you should consider renaming the DetailView from blog-list, to blog-detail, or something similar.
I have built a crispy form from a tutorial (https://godjango.com/29-crispy-forms/) and am getting an error that I believe means I need to define a URL in the urls.py. I also get the sense that there may be more than one issue going on - I am still trying to make this work and will continue to research it but I am quite new to Django and Python so struggling on this. Any guidance gratefully received.
Here's the error:
Failed lookup for key [form] in "[{'True': True, 'False': False, 'None': None}, {}, {}, {'view': <django.views.generic.base.TemplateView object at 0x10faa03c8>, 'home_url': '/'}]"
For reference here are the files:
forms.py
from django import forms
from crispy_forms.helper import FormHelper
from crispy_forms.layout import Submit, Layout, Field
from crispy_forms.bootstrap import (
PrependedText, PrependedAppendedText, FormActions)
class SimpleForm(forms.Form):
username = forms.CharField(label="Username", required=True)
password = forms.CharField(
label="Password", required=True, widget=forms.PasswordInput)
remember = forms.BooleanField(label="Remember Me?")
helper = FormHelper()
helper.form_method = 'POST'
helper.add_input(Submit('login', 'login', css_class='btn-primary'))
class CartForm(forms.Form):
item = forms.CharField()
quantity = forms.IntegerField(label="Qty")
price = forms.DecimalField()
helper = FormHelper()
helper.form_method = 'POST'
helper.layout = Layout(
'item',
PrependedText('quantity', '#'),
PrependedAppendedText('price', '$', '.00'),
FormActions(Submit('login', 'login', css_class='btn-primary'))
)
class CreditCardForm(forms.Form):
fullname = forms.CharField(label="Full Name", required=True)
card_number = forms.CharField(label="Card", required=True, max_length=16)
expire = forms.DateField(label="Expire Date", input_formats=['%m/%y'])
ccv = forms.IntegerField(label="ccv")
notes = forms.CharField(label="Order Notes", widget=forms.Textarea())
helper = FormHelper()
helper.form_method = 'POST'
helper.form_class = 'form-horizontal'
helper.label_class = 'col-sm-2'
helper.field_class = 'col-sm-4'
helper.layout = Layout(
Field('fullname', css_class='input-sm'),
Field('card_number', css_class='input-sm'),
Field('expire', css_class='input-sm'),
Field('ccv', css_class='input-sm'),
Field('notes', rows=3),
FormActions(Submit('purchase', 'purchase', css_class='btn-primary'))
)
views.py
from django.views.generic import FormView
from forms import SimpleForm, CreditCardForm, CartForm
class MainView(FormView):
template_name = "pages/home.html"
form_class = SimpleForm
urls.py
from django.conf import settings
from django.conf.urls import include, url
from django.conf.urls.static import static
from django.contrib import admin
from django.views.generic import TemplateView
from django.views import defaults as default_views
urlpatterns = [
url(r'^$', TemplateView.as_view(template_name='pages/home.html'), name='home'),
url(r'^page/$', TemplateView.as_view(template_name='pages/page.html'), name='page'),
# Django Admin, use {% url 'admin:index' %}
url(settings.ADMIN_URL, admin.site.urls),
# User management
url(r'^users/', include('base_django_template.users.urls', namespace='users')),
url(r'^accounts/', include('allauth.urls')),
# Your stuff: custom urls includes go here
] + static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT)
if settings.DEBUG:
# This allows the error pages to be debugged during development, just visit
# these url in browser to see how these error pages look like.
urlpatterns += [
url(r'^400/$', default_views.bad_request, kwargs={'exception': Exception('Bad Request!')}),
url(r'^403/$', default_views.permission_denied, kwargs={'exception': Exception('Permission Denied')}),
url(r'^404/$', default_views.page_not_found, kwargs={'exception': Exception('Page not Found')}),
url(r'^500/$', default_views.server_error),
]
if 'debug_toolbar' in settings.INSTALLED_APPS:
import debug_toolbar
urlpatterns = [
url(r'^__debug__/', include(debug_toolbar.urls)),
] + urlpatterns
and the section on home.html
<section id="contact" class="contact">
<div class="container">
<div class="row">
{% crispy form %}
</div>
</div>
</section>
I have {% load crispy_forms_tags %} at the top of the home.html.
It seems that your route '/' couldn't find any form.You can try by changing TemplateView class and put your MainView class.
urlpatterns = [
url(r'^$', MainView.as_view(), name='home'),
]
Then no need to define template name because it is defined on your MainView class.
Hope it will help.