I need to create a UpdateForm with a TemplateView. Why with TemplateView? Because, I has a attribute what is geo_location, and I'm using LeafLet maps, and LeafLet maps doesn't work with generic.UpdateView or others the same type.
Here my views from Update:
class UpdateStore(LoginRequiredMixin, TemplateView):
template_name = 'store_form'
success_url = reverse_lazy('register:store_list')
def post(self, request, *args, **kwargs):
store_id = kwargs['store']
store = get_object_or_404(Store, pk=store_id)
form = StoreForm(request.POST, on_edit=True)
if form.is_valid():
form.save()
return redirect(reverse('register:store_list'))
else:
context = self.get_context_data()
context['data_form'] = form
return render(request, self.template_name, context)
return self.get(request)
def get_context_data(self, **kwargs):
context = super().get_context_data(**kwargs)
store_id = self.kwargs['store']
store = get_object_or_404(Store, pk=store_id)
data = {
'name': store.name,
'description': store.description,
'address': store.address,
'geo_loc': store.geo_loc,
'opened': store.opened
}
context['editing'] = True
context['data_form'] = StoreForm(initial=data, on_edit=True)
context['store'] = store
return context
Here is my template code:
{% extends 'base.html' %}
{% load bootstrap3 %}
{% load leaflet_tags %}
{% block extra_css %}
{% leaflet_css plugins="forms" %}
{% endblock %}
{% block body %}
<h1> Update Store </h1>
<form method="POST">
{% csrf_token %}
{{ form }}
{% buttons %}
<button type="submit">
{% bootstrap_icon "star" %} Save
</button>
{% endbuttons %}
</form>
{% endblock %}
{% block extra_js %}
{% leaflet_js plugins="forms" %}
{% endblock %}
I trying this, but in my template, the Forms doesn't load, and my template are blanked :(. Someone knows why? I need another method for get anything else?
Thanks.
The problem with your code is that you place the form in the data_form key of the context:
context['data_form'] = StoreForm(initial=data, on_edit=True)
and then on the template you try to use it with {{form}} instead of {{data_form}}. After that the form should be rendered.
Related
I'm trying to include a link on a webpage to download a tables2 table to csv. I got the commented out piece below from the documentation, and I think it might just need a simple tweak to get it to work with my code. Any thoughts?
views.py
class PlatListView(SingleTableMixin, FilterView):
model = Plat
template_name = 'blog/filtertable.html'
filter_class = PlatFilter
def get_context_data(self, **kwargs):
context = super(PlatListView, self).get_context_data(**kwargs)
query = Phase.objects.all().select_related('plat','plat__community')
f = PlatFilter(self.request.GET, queryset=query)
t = PlatTable(data = f.qs)
RequestConfig(self.request, paginate=False).configure(t)
context['filter'] = f
context['table'] = t
'''
export_format = self.request.GET.get("_export", None)
if TableExport.is_valid_format(export_format):
exporter = TableExport(export_format, query)
return exporter.response("query.{}".format(export_format))
'''
return context
filtertable.html
{% extends "blog/base.html" %}
{% block content %}
{% load querystring from django_tables2 %}
<div style = 'padding-top: 24px'>
Download CSV
</div>
{% load render_table from django_tables2 %}
{% load bootstrap4 %}
{% if filter %}
<form action="" method="get" class="form form-inline">
{% bootstrap_form filter.form layout='inline' %}
{% bootstrap_button 'filter' %}
</form>
{% endif %}
{% render_table table 'django_tables2/bootstrap4.html' %}
{% endblock content %}
The commented-out snippet in your code is for function-based views as mentioned in the docs. In your case you should just add the ExportMixin :
from django_tables2.export.views import ExportMixin
class PlatListView(SingleTableMixin, ExportMixin, FilterView):
# other stuff your view is doing
I've been doing some django these past weeks and I'm having a problem.
I have a page where Articles are shown. No problem while reovering all articles from db. But now I'd like to get all categories (an Article has a category) that I have in my database.
So I can display like this in my page:
List of categories
-cat1
-cat2
-cat3
List of articles
-art1
-art2
-art3
But I don't know how to do with both queries.
Here's what I've tried.
class IndexView(generic.ListView):
template_name = 'eduardoApp/index.html'
context_object_name = 'article_list'
def get_queryset(self):
return Article.objects.order_by('article_name')
def get_categories(request):
category_list=Category.objects.all()
context = {'category_list':category_list}
return render(request,'eduardoApp/index.html',context)
And in my view:
<h2>List of categories</h2>
{% if category_list %}
{% for category in category_list %}
<p>{{ category.name }}</p>
{% endfor %}
{% else %}
<p>no categorys</p>
{% endif %}
<h2>List of articles</h2>
{% if article_list %}
<div class="flex-container">
{% for article in article_list %}
<div>{{ article.article_name }}</div>
{% endfor %}
</div>
{% else %}
<p>No articles...</p>
{% endif %}
{% endblock %}
In my view I keep seeing no categorys displayed (since category_list does not exist but don't know why and how to fix)
ListView is creating context with 'objects' as queryset get_queryset returns.
I suppose your custom method get_categories hasn't been used anywhere?
Best practice here is to override get_context_data method like...
class IndexView(generic.ListView):
...
def get_context_data(self, **kwargs):
context = super(IndexView, self).get_context_data(**kwargs)
context['category_list'] = ...
return context
I'm trying to make Todo app. I want to make checkbox next to task, so when you select it, the task is set to done. The problem is, I can't really know how to change value of my BooleanField in Task Model. There are plenty of posts like this, but they are usually using functions inside views.py or use forms, but I can't relate do my form in ListView.
views.py
class TodolistView(LoginRequiredMixin, ListView):
model = Todolist
template_name = 'todolist.html'
def get_queryset(self):
return Todolist.objects.all().filter(user=self.request.user)
def get(self, request, *args, **kwargs):
todolist_objects = Todolist.objects.all()
return render(request, 'todolist.html', {'todolist_objects': todolist_objects})
todolist.html
{% extends 'base.html' %}
{% load crispy_forms_tags %}
{% block content %}
<p>Add new task</p>
{% for todo in todolist_objects %}
<div>
<form action="" method="post">
<li> {{ todo }} see details</l>
</form>
</div>
{% endfor %}
{% endblock %}
I use Django Endless Paginator plugin.
I try to change the value of ENDLESS_PAGINATION_PER_PAGE from template side.
As default is 10.
I want to realize some dropbox where the user can change between (Example: 10,20,50,100 Objects).
Thanks for answer, but something not work property.
1. I have view.py
def adv_search(request):
objects = None
if request.GET.get('key'):
form = AdvancedSearchForm(request.GET)
if form.is_valid():
repo = Repository()
objects = list(repo.find_objects('*'+form.cleaned_data['key'] +'*', type=FileObject, chunksize=20))
return render(request, 'templates/adv_search.html', {'form': form, 'objects': objects })
return render(request, 'templates/adv_search.html', {'form': AdvancedSearchForm(), 'objects': objects})
2. Then forms.py
class AdvancedSearchForm(forms.Form):
key = forms.CharField(max_length=500, label="", widget= forms.TextInput(attrs={'class': 'label'}))
show_props = forms.MultipleChoiceField(choices = (("pid", "pid"),("title", "title"),("type","type"),("source","source"),("date","date"),("publisher","publisher"),("subject","subject"),("label","label"),("cDate","cDate"),("mDate","mDate")),required=False, widget=forms.CheckboxSelectMultiple(attrs={'class': 'my-class'}))
paginator = forms.ChoiceField(choices =(('10', '10'),('20','20'), ('50','50'), ('100','100')) ,required=False, )
3. adv_search.html
{% paginate paginator objects %}
{% for obj in objects %}
...
<div class="paginator">
{% get_pages %}
{{ pages.first_as_arrow }}
{% show_pages %}
{{ pages.last_as_arrow }}
<form method="get">
{{ form.paginator }}
<input type="submit" Value="Go">
</form>
{{ pages.total_count }} total objects
</div>
Everything works except select
Thanks Andrey
You can have a form which will set pagination per page and then use that submitted value in template. Here is an example:
View
from django.shortcuts import render
from .models import Entry
def endless_view(request):
pagination_per_page = request.GET.get('per_page', 10)
entries = Entry.objects.all()
return render(request, 'some_template.html', {'pagination_per_page':
pagination_per_page, 'entries': entries})
Template
{% extends 'base.html' %}
{% load endless %}
{% block content %}
{# #}
<form action="" method="get">
<select name="per_page">
<option value="10">10 per page</option>
<option value="20">20 per page</option>
<option value="50">50 per page</option>
<option value="100">100 per page</option>
</select>
<input type="submit" Value="Go">
</form>
{% paginate pagination_per_page entries %}
{% for entry in entries %}
{# your code to show the entry #}
{% endfor %}
{% show_pages %}
{% endblock content %}
Reference
http://django-endless-pagination.readthedocs.org/en/latest/templatetags_reference.html
I want to use {% include %} to include a second form on a page, but the form is empty..
views.py:
def year_form(request):
thing_list = Thing.objects.all()
if request.method == 'POST':
form = YearBrowseForm(request.POST)
if form.is_valid():
year = form.cleaned_data['year']
return HttpResponseRedirect(reverse('browse_years', kwargs={'year':year}))
else:
form = YearBrowseForm()
return render(request, 'browse-year.html', {'form':form, 'thing_list':thing_list})
forms.py:
class YearBrowseForm(forms.Form):
year = forms.ChoiceField(choices=YEARS_EMPTY, widget=forms.Select(attrs={'onchange': 'this.form.submit();'}))
url:
url(r'^browse/years/(?P<year>\d+)/$', 'my_app.views.browse.year_form', name='browse_years'),
html:
{% extends 'base.html' %}
{% block content %}
{% include 'browse-year.html' %}
{% endblock %}
browse-year.html:
<form action='' method='post' enctype='multipart/form-data'>
{{ form.as_p }}
{% csrf_token %}
</form>
This renders an empty form (i.e. the source shows that a form is being included, but it is empty of content). What am I missing here? This is a continuation of this question that I am trying to solve in a different method by using {% include %}. Thanks for your ideas!
This happens because you are rendering browse-year.html:
return render(request, 'browse-year.html', {'form':form, 'thing_list':thing_list})
You should be rendering the other html, the one you didn't gave a name, but starts with
{% extends 'base.html' %}
only by rendering that one you extend the base, and the other content appears.