I have just started learning the django framework and I am having issues while displaying the images from the database to the frontend of the website. My database is showing the images uploaded but nothing is being displayed on the page itself.
This is my models.py
class Post(models.Model):
title= models.CharField(max_length=255)
author= models.ForeignKey(User,on_delete=models.CASCADE)
body = models.TextField()
def get_absolute_url(self):
return reverse('article-detail', args=(str(self.id)))
def __str__(self):
return self.title + ' | ' + str(self.author)
class Images(models.Model):
post= models.ForeignKey(Post,on_delete=models.CASCADE )
image= models.ImageField(null=True, blank=True)
This is my views.py
class ArticleDetailView(DetailView):
model = Post
template_name= 'article_details.html'
def get_context_data(self, **kwargs):
context = super().get_context_data(**kwargs)
context['imagelist'] = Post.objects.get(id = self.kwargs['pk'])
return context
def AddPostView(request):
model= Images
if request.method == "POST":
form= PostForm(request.POST)
files = request.FILES.getlist("image")
if form.is_valid():
f=form.save(commit=False)
f.user=request.user
f.save()
for i in files:
img = Images.objects.create(post=f, image= i)
img.save()
messages.success(request, "New Blog added")
return HttpResponseRedirect("/")
else:
form= PostForm()
imageform= ImageForm()
return render (request, "add_post.html",{"form":form,"imageform":imageform})
This is my forms.py
from django import forms
from .models import Images, Post
class PostForm(forms.ModelForm):
class Meta:
model= Post
fields = ('title', 'body','author')
widgets = {
'title': forms.TextInput(attrs{'class':'form-control'}),
'body': forms.Textarea(attrs={'class':'form-control'})
}
class ImageForm(forms.ModelForm):
image= forms.ImageField(
label="image",
widget= forms.ClearableFileInput(attrs={"multiple":True}),
)
class Meta:
model= Images
fields= ("image",)
This is my artice-details.html page
{% for pimage in imageslist.image_set.all %}
<img src="{{pimage.image.url}}" alt="default">
{% endfor %}
Related
I have an image gallery app in Django that has an upload image page and sends that photo to a gallery page. Also, there's an edit photo page where I want to display the uploaded image and edit it, then submit the edited photo to the gallery page. How can I have the currently uploaded image show up on both the upload image and edit pages?
views.py #uploads form for add image page(named addartifact)
def addartifact(request):
if request.method == 'GET':
form = EditorForm()
return render(request=request,template_name='addartifact.html', context={'form': form})
if request.method == 'POST':
form = EditorForm(request.POST)
if form.is_valid():
imgtitle = form.cleaned_data['imgtitle']
imgdesc = form.cleaned_data['imgdesc']
image = form.cleaned_data['image']
artifact = Artifact.objects.create(imgtitle=imgtitle, imgdesc=imgdesc, image=image)
return HttpResponseRedirect(reverse('landingpage'))
views.py #uploads image to page
def image_upload_view(request):
"""Process images uploaded by users"""
if request.method == 'POST':
form = ImageForm(request.POST, request.FILES)
if form.is_valid():
form.save()
# Get the current instance object to display in the template
img_obj = form.instance
return render(request, 'addartifact.html', {'form': form, 'img_obj': img_obj})
else:
form = ImageForm()
return render(request, 'addartifact.html', {'form': form})
forms.py
class ImageForm(forms.ModelForm):
"""Form for the image model"""
class Meta:
model = Artifact
fields = ('artifact_id', 'imgtitle', 'imgdesc', 'image')
class EditorForm(forms.Form):
imgtitle = forms.CharField(max_length=13, required=True, label=False, widget=forms.TextInput(attrs={'style': 'text-transform:lowercase;', 'placeholder': 'enter title'}))
imgdesc = forms.CharField(widget=forms.Textarea(attrs={'placeholder': 'add description'}), label=False, required=True)
image = forms.URLField(required=True, label=False, widget=forms.TextInput(attrs={'placeholder': 'add image'}))
models.py
class Artifact(models.Model):
artifact_id = models.AutoField(primary_key=True)
imgtitle = models.CharField(max_length=11)
imgdesc = models.CharField(max_length=24)
image=models.ImageField(upload_to='images/')
created_at = models.DateTimeField(auto_now_add=True)
updated_at = models.DateTimeField(auto_now=True)
class Meta:
ordering = ['-created_at']
Hope you can help me with this one.I am very new to Python/Django so my code might be quite bad.
I am creating a website/blog and on my navigation bar I have a list of the categories which contain dropdown menues with the subcategories. When I click on each subcategory I want it to display just the posts from that subcategory.
Here is part of my code for this:
"Models":
from django.db import models
from django.utils import timezone
from django.utils.text import slugify
from django.urls import reverse
from ckeditor_uploader.fields import RichTextUploadingField
class Post(models.Model):
NO_CATEGORY = 'No Category'
GETTING_STARTED = 'Getting Started'
DIY = "DIY"
GARDENS = 'Gardens'
TERRARIUMS = 'Terrariums'
CATEGORIES = (
(NO_CATEGORY, 'No Category'),
(GETTING_STARTED, 'Getting Started'),
(DIY, 'DIY'),
(GARDENS, 'Gardens'),
(TERRARIUMS, 'Terrariums'),
)
title = models.CharField(max_length=200, unique=True)
slug = models.SlugField(unique=True, default='', blank=True)
image = models.ImageField(upload_to='images/')
content = RichTextUploadingField(null=True, blank=True)
summary = models.CharField(max_length=150, unique=True, null=True)
category = models.CharField(choices=CATEGORIES, max_length=15, default=NO_CATEGORY)
subcategory = models.ForeignKey('Subcategory', on_delete=models.SET_NULL, null=True)
created_date = models.DateTimeField(default=timezone.now)
def __str__(self):
return self.title
def save(self, *args, **kwargs):
self.slug = slugify(self.title)
super(Post, self).save(*args, **kwargs)
def get_absolute_url(self):
return reverse('core:post_detail', args=[str(self.slug)])
class Meta:
ordering = ['-created_date']
class Subcategory(models.Model):
NO_CATEGORY = 'No Category'
TOOLS = 'Tools'
HOW_TO = 'How To'
SUPPLIES = 'Supplies'
FURNITURE = 'Furniture'
ACCESSORIES = 'Accessories'
DECOR = 'Decor'
MINIATURE = 'Miniature'
MICRO = 'Micro'
OPEN = 'Open'
ENCLOSED = 'Enclosed'
SUBCATEGORIES = [
(NO_CATEGORY, 'No Category'),
('Getting Started', ((TOOLS, 'Tools'), (HOW_TO, 'How To'), (SUPPLIES, 'Supplies'),)),
('DIY', ((FURNITURE, 'Furniture'), (ACCESSORIES, 'Accessories'), (DECOR, 'Decor'),)),
('Gardens', ((MINIATURE, 'Miniature'), (MICRO, 'Micro'),)),
('Terrariums', ((OPEN, 'Open'), (ENCLOSED, 'Enclosed'),)),
]
name = models.CharField(choices=SUBCATEGORIES, max_length=15, default=NO_CATEGORY)
slug = models.SlugField(max_length=150, unique=True, null=True)
class Meta:
verbose_name = "Subcategory"
verbose_name_plural = "Subcategories"
def get_posts(self):
return Post.objects.filter(subcategories_name=self.name)
def __str__(self):
return self.name
def get_absolute_url(self):
return reverse('core:post_subcategory', kwargs={'slug': self.slug})
class Picture(models.Model):
title = models.CharField(max_length=100, unique=True)
image = models.ImageField(upload_to='images/gallery/')
created_date = models.DateTimeField(default=timezone.now)
def __str__(self):
return f'{self.title}'
class Meta:
ordering = ['-created_date']
"Views":
from django.shortcuts import render
from .models import Post, Subcategory, Picture
from django.core.paginator import Paginator
from django.views import generic
def base(request):
return render(request, 'core/base.html')
def home(request):
posts = Post.objects.all()
paginator = Paginator(posts, 5)
page = request.GET.get('page')
posts = paginator.get_page(page)
return render(request, 'core/home.html', {'posts': posts})
class PostList(generic.ListView):
model = Post
queryset = Post.objects.all().order_by('-created_date')
template_name = 'home.html'
def post_detail(request, slug=None):
post = Post.objects.get(slug=slug)
return render(request, 'core/post_detail.html', {'post': post})
class PostDetail(generic.DetailView):
model = Post
template_name = 'post_detail.html'
def post_subcategory(request):
subcategories = Subcategory.objects.all()
paginator = Paginator(subcategories, 5)
page = request.GET.get('page')
subcategories = paginator.get_page(page)
return render(request, 'core/post_subcategory.html', {'subcategories': subcategories})
class SubcategoryDetailView(generic.DetailView):
model = Subcategory
context_object_name = 'subcategory'
template_name = 'core/post_subcategory.html'
def get_queryset(self):
return Post.objects.filter(subcategory_id=self.kwargs.get('slug'))
def base_gallery(request):
pictures = Picture.objects.all()
paginator = Paginator(pictures, 16)
page = request.GET.get('page')
pictures = paginator.get_page(page)
return render(request, 'core/base_gallery.html', {'pictures': pictures})
class PictureList(generic.ListView):
queryset = Picture.objects.all().order_by('-created_date')
template_name = 'base_gallery.html'
def contact(request):
return render(request, 'core/contact.html', {'contact': contact})
"config/urls"
from django.shortcuts import render
from .models import Post, Subcategory, Picture
from django.core.paginator import Paginator
from django.views import generic
def base(request):
return render(request, 'core/base.html')
def home(request):
posts = Post.objects.all()
paginator = Paginator(posts, 5)
page = request.GET.get('page')
posts = paginator.get_page(page)
return render(request, 'core/home.html', {'posts': posts})
class PostList(generic.ListView):
model = Post
queryset = Post.objects.all().order_by('-created_date')
template_name = 'home.html'
def post_detail(request, slug=None):
post = Post.objects.get(slug=slug)
return render(request, 'core/post_detail.html', {'post': post})
class PostDetail(generic.DetailView):
model = Post
template_name = 'post_detail.html'
def post_subcategory(request):
subcategories = Subcategory.objects.all()
paginator = Paginator(subcategories, 5)
page = request.GET.get('page')
subcategories = paginator.get_page(page)
return render(request, 'core/post_subcategory.html', {'subcategories': subcategories})
class SubcategoryDetailView(generic.DetailView):
model = Subcategory
context_object_name = 'subcategory'
template_name = 'core/post_subcategory.html'
def get_queryset(self):
return Post.objects.filter(subcategory_id=self.kwargs.get('slug'))
def base_gallery(request):
pictures = Picture.objects.all()
paginator = Paginator(pictures, 16)
page = request.GET.get('page')
pictures = paginator.get_page(page)
return render(request, 'core/base_gallery.html', {'pictures': pictures})
class PictureList(generic.ListView):
queryset = Picture.objects.all().order_by('-created_date')
template_name = 'base_gallery.html'
def contact(request):
return render(request, 'core/contact.html', {'contact': contact})
"app/urls":
from django.contrib import admin
from django.urls import path, include
from django.conf import settings
from django.conf.urls.static import static
import core.views
urlpatterns = [
path('admin/', admin.site.urls),
path('core/', include('core.urls')),
path('ckeditor/', include('ckeditor_uploader.urls')),
path('', core.views.home, name='home'),
path('', core.views.base, name='base'),
path('post_subcategory', core.views.post_subcategory, name='post_subcategory'),
path('post_detail', core.views.post_detail, name='post_detail'),
path('base_gallery', core.views.base_gallery, name='base_gallery'),
path('contact', core.views.contact, name='contact')
] + static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT)
"post_category.html":
{% extends "core/base.html" %}
{% block content %}
{% load static %}
<div class="category-title">
<h1>HOW TO</h1>
</div>
{% for subcategory in subcategories %}
{% for post in subcategory.post_set.all %}
<h1>{{ post.title }}</h1>
<div class="category-content">
<figure class="gallery-picture">
<h1 class="picture-text"></h1>
<img src="{{ post.image.url }}" alt="gallery image">
</figure>
</div>
{% endfor %}
{% endfor %}
{% endblock %}
This is what I've tried so far and I can display all the subcategories on that template but I don't know how to filter them one by one, if that makes any sense.
First, I think the data structure and your model relationships are not properly placed.
I think you should have a category model and a sub_category model too.
class Category(models.Model):
title = models.Charfield(...)
class SubCategory(models.Model):
category = models.ForiegnKey(on_delete=models.CASCADE)
title = models.Charfield(...)
By doing this, you wouldn't need the dictionary and you won't also need the category field on Post model
so all have to query in your views.py is where post.sub_category.category == the requested category or where post.sub_cateogory == the requested sub_category.
Editing to show how to implement in views.py
class DIYCategoryList(generic.ListView):
template_name = 'blog/diy_category.html'
model = Post
context_object_name = 'diy_posts'
paginate_by = 16
def get_queryset(self):
return Post.objects.filter(sub_category.category.title='DIY')
I have a little problem. I want to to display in list only records belongs to user whos add it. In my app when I'am login as 'user' and I want to add new records incude records from list, I see all records in db from ForeignKey. How to make it correctly?
In 'Strona www' when I expand the list I see all records, not only records added by user personally.
My view for it is:
#login_required
def new_keyword(request):
if request.method == "POST":
new_keyword = KeywordForm(request.POST)
if new_keyword.is_valid():
new_keyword=new_keyword.save(commit=False)
new_keyword.user = request.user
new_keyword.save()
messages.success(request, 'Pomyślnie dodano słowo kluczowe')
return render(request, 'konto/new_keyword_ok.html')
else:
new_keyword = WebsiteForm()
return render(request, 'konto/new_keyword.html', {'new_keyword':new_keyword})
in forms.py I have:
class KeywordForm(forms.ModelForm):
class Meta:
model = Keyword
fields = ('www', 'keyword')
models.py
class Keyword(models.Model):
user = models.ForeignKey(User, on_delete=models.CASCADE, verbose_name="Użytkownik")
www = models.ForeignKey(Website, on_delete=models.CASCADE, verbose_name="Strona www")
keyword = models.CharField(max_length=250, verbose_name="Słowo kluczowe", unique=False)
urls.py
path('new-keyword/', new_keyword, name='new_keyword'),
and html for display the form is:
{% if request.user.is_authenticated %}
<form action="." method="post">
{{ new_keyword.as_p }}
{% csrf_token %}
<p><input type="submit" value="Dodaj nowe słowo kluczowe" ></p>
Powrót do monitoringu
</form>
{% endif %}
EDIT:
models.py
from django.db import models
from django.contrib.auth.models import User
class Website(models.Model):
user = models.ForeignKey(User, on_delete=models.CASCADE, verbose_name="Użytkownik")
website = models.CharField(max_length=250,verbose_name='Strona www', unique=False)
class Meta:
verbose_name = 'Strona www'
verbose_name_plural = 'Strony www'
def __str__(self):
return self.website
class Keyword(models.Model):
user = models.ForeignKey(User, on_delete=models.CASCADE, verbose_name="Użytkownik")
www = models.ForeignKey(Website, on_delete=models.CASCADE, verbose_name="Strona www")
keyword = models.CharField(max_length=250, verbose_name="Słowo kluczowe", unique=False)
class Meta:
verbose_name = 'Słowo kluczowe'
verbose_name_plural = 'Słowa kluczowe'
def __str__(self):
return self.keyword
Pass the request.user to your form and use the inverse relation user.website_set :
forms :
class KeywordForm(forms.ModelForm):
class Meta:
model = Keyword
fields = ('www', 'keyword')
def __init__(self, user, *args, **kwargs):
super(KeywordForm, self).__init__(*args, **kwargs)
self.fields['www'].queryset = user.website_set.all()
self.user = user
def save(self, commit=True):
instance = super(KeywordForm, self).save(commit=False)
instance.user = self.user
if commit:
instance.save()
return instance
views:
#login_required
def new_keyword(request):
if request.method == "POST":
new_keyword = KeywordForm(request.user, request.POST)
if new_keyword.is_valid():
new_keyword.save()
messages.success(request, 'Pomyślnie dodano słowo kluczowe')
# DONT DO THIS ! REDIRECT INSTEAD
return render(request, 'konto/new_keyword_ok.html')
else:
new_keyword = KeywordForm(request.user)
return render(request, 'konto/new_keyword.html', {'new_keyword':new_keyword})
As a side note: after a successful POST you want to redirect (even if to the same url). This avoids a lot of troubles (and duplicate submissions) when a user reloads the page
Just pass the user id to your form and then set a queryset for your field
like this:
How to pass the user to your form:
in your view:
#login_required
def new_keyword(request):
if request.method == "POST":
#### Notice this part.
new_keyword = KeywordForm(data=request.POST, u=request.user)
if new_keyword.is_valid():
new_keyword=new_keyword.save(commit=False)
new_keyword.user = request.user
new_keyword.save()
messages.success(request, 'Pomyślnie dodano słowo kluczowe')
return render(request, 'konto/new_keyword_ok.html')
else:
# Notice this part.
new_keyword = WebsiteForm(data=None, u=request.user)
return render(request, 'konto/new_keyword.html', {'new_keyword':new_keyword})
How to retrieve the user in form and set the queryset:
forms.py:
class KeywordForm(forms.ModelForm):
class Meta:
model = Keyword
fields = ('www', 'keyword')
def __init__(self, current_user, *args, **kwargs):
self.u = kwargs.pop("u") ## The user you just passed.
super(KeywordForm, self).__init__(*args, **kwargs)
self.fields['www'].queryset = Website.objects.filter(user=self.u) ## Setting the queryset.
I am building a post editor for my website. One of the fields I can edit is for tags. However when I save the post everything updates correctly and no errors are thrown but any changes I made to the tags field are not saved.
# Views.py
class EditPostView(UpdateView):
form_class = EditPostForm
model = Post
template_name = 'myapp/editpost.html'
def get(self, request, pk):
if (not request.user.is_superuser):
return HttpResponseForbidden()
post = Post.objects.get(id=pk)
if (post is None):
return HttpResponseNotFound()
form = self.form_class(instance=post)
return render(request, self.template_name, {'form': form, 'post': post})
def post(self, request, pk):
if (not request.user.is_superuser):
return HttpResponseForbidden()
post = Post.objects.get(id=pk)
if (post is None):
return HttpResponseNotFound()
form = self.form_class(request.POST, instance=post)
if (form.is_valid()):
post.title = form.cleaned_data['title']
post.content_type = form.cleaned_data['content_type']
post.screenshot = form.cleaned_data['screenshot']
post.tags = form.cleaned_data['tags']
post.body = form.cleaned_data['body']
post.nsfw = form.cleaned_data['nsfw']
post.allow_comments = form.cleaned_data['allow_comments']
post.display_edited = form.cleaned_data['display_edited']
post.files = form.cleaned_data['files']
post.date_edited = datetime.now()
post.save()
return redirect('/posts/' + str(post.id))
else:
return HttpResponseNotFound()
return HttpResponseNotFound()
#Forms.py
class PostForm(forms.ModelForm):
class Meta:
model = Post
fields = ['title', 'content_type', 'screenshot', 'body', 'tags', 'nsfw', 'allow_comments', 'files']
widgets = {
'screenshot': forms.TextInput(attrs={'placeholder': 'URL...'}),
'tags': TagWidget(),
}
labels = {
'files': 'Attachments',
}
# Models.py
class Post(models.Model):
title = models.CharField(max_length=256)
disclaimer = models.CharField(max_length=256, blank=True)
BLOGS = 'blogs'
APPLICATIONS = 'applications'
GAMES = 'games'
WEBSITES = 'websites'
GALLERY = 'gallery'
PRIMARY_CHOICES = (
(BLOGS, 'Blogs'),
(APPLICATIONS, 'Applications'),
(GAMES, 'Games'),
(WEBSITES, 'Websites'),
)
content_type = models.CharField(max_length=256, choices=PRIMARY_CHOICES, default=BLOGS)
screenshot = models.CharField(max_length=256, blank=True)
tags = TaggableManager()
body = RichTextField()
date_posted = models.DateTimeField(default=datetime.now)
date_edited = models.DateTimeField(blank=True, null=True)
visible = models.BooleanField(default=True)
nsfw = models.BooleanField()
display_edited = models.BooleanField(default=False)
allow_comments = models.BooleanField(default=True)
files = models.ManyToManyField(File, blank=True)
def __str__(self):
if (self.visible == False):
return '(Hidden) ' + self.title + ' in ' + self.content_type
return self.title + ' in ' + self.content_type
You're doing a lot of unnecessary work here. You're not leveraging the power of the UpdateView. This is all you should need. It will call form.save() and everything for you
from django.http import HttpResponseForbidden
from django.shortcuts import get_object_or_404
from django.views.generic.edit import UpdateView
class EditPostView(UpdateView):
form_class = EditPostForm
model = Post
template_name = 'myapp/editpost.html'
def dispatch(self, *args, **kwargs):
if not self.request.user.is_superuser:
return HttpResponseForbidden()
return super(EditPostView, self).dispatch(*args, **kwargs)
def get_object(self, queryset=None):
return get_object_or_404(Post, id=self.kwargs['id'])
def get_success_url(self):
return '/posts/{0}'.format(self.object.id)
Edit: bonus points if you get rid of get_success_url and add a get_absolute_url method to the Post model.
class Post(models.Model):
...
def save(self, *args, **kwargs):
self.date_edited = datetime.now()
super(Post, self).save(*args, **kwargs)
def get_absolute_url(self):
return '/posts/{0}'.format(self.id)
I'm trying to user Django model formset factory to render a template where a user can add images and change the images they have uploaded(very similar to what can be done in the admin). I currently can render the template and its correct fields to the template. What I cannot do is have the user preselected(want currently logged in) and when I refresh the page the image will be posted again(not sure if this is preventable). Below is my code. Thanks!
Model:
class Image(models.Model):
user = models.ForeignKey(User)
image = models.ImageField(upload_to=content_file_name, null=True, blank=True)
link = models.CharField(max_length=256, blank=True)
Form:
class ImageForm(forms.ModelForm):
image = forms.ImageField(label='Image')
class Meta:
model = Image
fields = ('image',
'link',
)
View:
#login_required
def register(request):
user_data = User.objects.get(id=request.user.id)
ImageFormSet = modelformset_factory(Image,
fields=('user', 'image', 'link'), extra=3)
if request.method == 'POST':
print '1'
formset = ImageFormSet(request.POST, request.FILES, queryset=Image.objects.all())
if formset.is_valid():
formset.user = request.user
formset.save()
return render(request, 'portal/register.html', {'formset': formset, 'user_data': user_data})
else:
print '2'
formset = ImageFormSet(queryset=Image.objects.all())
return render(request, 'portal/register.html', {'formset': formset, 'user_data': user_data})
Template:
<form id="" method="post" action=""
enctype="multipart/form-data">
{% csrf_token %}
{{ formset.management_form }}
{% for form in formset %}
{{ form }}
{% endfor %}
<input type="submit" name="submit" value="Submit" />
let me explain the way you can do it.
MODELS
from django.utils.text import slugify
from django.db import models
from custom_user.models import AbstractEmailUser
# User model
class UserModel(AbstractEmailUser):
full_name = models.CharField(max_length=255)
def __str__(self):
return str(self.id)
# Function for getting images from instance of user
def get_image_filename(instance, filename):
title = instance.id
slug = slugify(title)
return "user_images/%s-%s" % (slug, filename)
# Save images with user instance
class UserImages(models.Model):
user = models.ForeignKey('UserModel', db_index=True, default=None)
image = models.ImageField(upload_to=get_image_filename, verbose_name='Image', db_index=True, blank=True, null=True)
In forms it's a just a two form, one for model User, other for UserImages model.
# Images forms
class ImageForm(forms.ModelForm):
image = forms.ImageField(label='Image', required=False)
class Meta:
model = UserImages
fields = ('image',)
# User form
class UserForm(forms.ModelForm):
full_name = forms.CharField(required=True)
class Meta:
model = UserModel
fields = ('full_name','email','password',)
And in Views for post you can do something like this
# View
from models import *
from forms import *
#csrf_protect
def post_view(request):
template = 'some_template.html'
ImageFormSet = modelformset_factory(UserImages, form=ImageForm, extra=15)
if request.method == 'POST':
user_form = UserForm(request.POST, prefix='form1')
formset = ImageFormSet(request.POST, request.FILES, queryset=UserImages.objects.none(), prefix='form2')
if user_form.is_valid() and formset.is_valid():
# Save User form, and get user ID
a = user_form.save(commit=False)
a.save()
images = formset.save(commit=False)
for image in images:
image.user = a
image.save()
return HttpResponseRedirect('/success/')
else:
user_form = UserForm(prefix='form1')
formset = ImageFormSet(queryset=UserImages.objects.none(), prefix='form2')
return render(request, template, {'form_user':user_form,'formset':formset})
In template you are doing the right thing.