I am currently using Django version 1.11.2 and would like to use the FilteredSelectMultiple widget outside of the admin page.
This is my forms.py:
class TBDAuthGroupManageForm(forms.Form):
permissions = forms.ModelMultipleChoiceField(queryset=Permission.objects.all(),
required=True,
widget=FilteredSelectMultiple("Permissions", is_stacked=False))
class Media:
css = {'all': ('/static/admin/css/widgets.css',), }
js = ('/admin/jsi18n/',)
def __init__(self, parents=None, *args, **kwargs):
super(TBDAuthGroupManageForm, self).__init__(*args, **kwargs)
This is my views.py:
class TBDAuthGroupManageView(DetailView):
model = TBDAuthGroup
template_name = 'perms/tbdauthgroup_manage.html'
def get_context_data(self, **kwargs):
context = super(TBDAuthGroupManageView, self).get_context_data(**kwargs)
context['form'] = TBDAuthGroupManageForm()
return context
And this is my template:
{% extends "base.html" %}
{% load static %}
{% block css %}
{{ form.media }}
<script type="text/javascript" src="{% static 'js/jquery-3.1.1.min.js' %}"></script>
<script type="text/javascript" src="/static/admin/js/jquery.min.js"></script>
<script type="text/javascript" src="/static/admin/js/jquery.init.js"></script>
{% endblock %}
{% block content %}
{{ form }}
{% endblock %}
However when I render it in the page, I only get this:
and not this:
I would love to know what I'm doing wrong and how I could fix this so my form looks like the admin form.
{% block content %}
{{ form.media }}
<form>
{{ form.permissions }}
</form>
{% endblock %}
try this in your template
Related
When I create a new post with an image, everything is fine, but if I edit it, I want to delete the image using the "clear" button, then this error appears, and if I change, then nothing changes, but there are no errors
here is models.py
`
from django.db import models
from django.urls import reverse
class Post(models.Model):
title = models.CharField(max_length=200)
author = models.ForeignKey(
'auth.User',
on_delete=models.CASCADE,
)
body = models.TextField()
header_image = models.ImageField(blank=True, null=True, upload_to="images/", default='#') #new
def __str__(self):
return self.title
def get_absolute_url(self):
return reverse('post_detail', args=[str(self.id)])`
here is views.py
`
from django.shortcuts import render
from django.views.generic import ListView, DetailView
from django.views.generic.edit import CreateView, UpdateView, DeleteView
from django.urls import reverse_lazy
from .models import Post
class BlogListView(ListView):
model = Post
template_name = 'home.html'
class BlogDetailView(DetailView):
model = Post
template_name = 'post_detail.html'
class BlogCreateView(CreateView):
model = Post
template_name = 'post_new.html'
fields = ['title', 'author', 'body', 'header_image']
class BlogUpdateView(UpdateView):
model = Post
template_name = 'post_edit.html'
fields = ['title', 'body', 'header_image']
class BlogDeleteView(DeleteView):
model = Post
template_name = 'post_delete.html'
success_url = reverse_lazy('home')
#property
def image_url(self):
"""
Return self.photo.url if self.photo is not None,
'url' exist and has a value, else, return None.
"""
if self.image:
return getattr(self.photo, 'url', None)
return None`
post_base.html
`{% load static %}
<html>
<head>
<title>Django blog</title>
<link href="https://fonts.googleapis.com/css?family=Source+Sans+Pro:400"
rel="stylesheet">
<link href="{% static 'css/base.css' %}" rel="stylesheet">
</head>
<body>
<div>
<header>
<div class="nav-left">
<h1>Django blog</h1>
<h2>Admin</h2>
</div>
<div class="nav-right">
+ New Blog Post
</div>
</header>
{% if user.is_authenticated %}
<p>Hi {{ user.username }}!</p>
{% else %}
<p>You are not logged in.</p>
Log In<br>
<p>Sign up</p>
{% endif %}
{% block content %}
{% endblock content %}
</div>
</body>
</html>`
post_detail.html
`
{% extends 'base.html' %}
{% block content %}
<div class="post-entry">
<h2>{{ post.title }}</h2>
<p>{{ post.body }}</p>
</div>
<p>+ Edit Blog Post</p>
<p>+ Delete Blog Post</p>
<img src="{{ post.header_image.url|default_if_none:'#' }}">
{{ post.body|safe }}
{% endblock content %}`
post_new.html
`
{% extends 'base.html' %}
{% block content %}
<h1>New post</h1>
<form action="" method="post" enctype="multipart/form-data">{% csrf_token %}
{{ form.as_p }}
<input type="submit" value="Save" />
</form>
{% endblock content %}`
post_edit.html
`
{% extends 'base.html' %}
{% block content %}
<h1>Edit post</h1>
<form action="" method="post">{% csrf_token %}
{{ form.as_p }}
<input type="submit" value="Update" />
</form>
{% endblock content %}`
enctype='multipart/form-data' means that no characters will be encoded. that is why this type is used while uploading files to server. So multipart/form-data is used when a form requires binary data, like the contents of a file, to be uploaded.
You forgot to add enctype='multipart/form-data' in your post_edit.html form and that's the reason your files aren't sent to Django. Following code should work.
post_edit.html
{% extends 'base.html' %}
{% block content %}
<h1>Edit post</h1>
<form action="" method="post" enctype='multipart/form-data'>
{% csrf_token %}
{{ form.as_p }}
<input type="submit" value="Update" />
</form>
{% endblock content %}
I am learning django, I added a new app,
the link can be displayed in friendly_link.html,
the code is as follows:
admin.py
from django.contrib import admin
from .models import FriendlyLink
admin.site.register(FriendlyLink)
models.py
from django.db import models
class FriendlyLink(models.Model):
title = models.CharField(max_length=100, default='', verbose_name='title')
url = models.CharField(max_length=100, default='', verbose_name='url')
class Meta:
verbose_name_plural = 'links'
def __str__(self):
return self.title
views.py
from django.shortcuts import render
from .models import FriendlyLink
def friendly_link(request):
friendly_link = FriendlyLink.objects.order_by('title')
context = {'friendly_link': friendly_link}
return render(request, 'friendly_link.html', context)
urls.py
from django.urls import re_path
from . import views
urlpatterns = [
re_path(r'^links$', views.friendly_link, name='friendly_link'),
]
friendly_link.html
{% extends "base.html" %}
{% block title %}Links{% endblock %}
{% block content %}
<ul>
{% for link in friendly_link %}
<li>{{ link.title }}</li>
{% empty %}
{% endfor %}
</ul>
{% endblock %}
base.html
{% load i18n static %}<!DOCTYPE html>
<html>
<head>
...
</head>
<body>
...
{% block content %}{% endblock %}
<footer>
<ul>
<!--This code doesn't work-->
{% for link in friendly_link %}
<li>{{ link.title }}</li>
{% empty %}
{% endfor %}
</ul>
</footer>
...
</body>
I want to put the link inside the <footer> element in base.html. How do I change the code? Thank you.
You should really read this documentation page:
https://django-adminlte2.readthedocs.io/en/latest/templates_and_blocks.html
Each block is clickable there and there's a detailed description on how to overwrite each one.
For your problem, you will probably nav_footer
{% block nav_footer %}
{{ block.super }}
...
{% endblock %}
{{ block.super }} is optional and will append your content to the block instead of overwriting it.
The Django docs aren't clear on using ModelForm. First, how do I set up my urls.py?
I simply do this:
from . import views as music_views
url(r'album/add/$', music_views.AlbumCreate(), name='album-add'),
In my views I'm trying to use the AdminDateWidget:
from . import models as music_models
from django import forms
from django.contrib.admin.widgets import AdminDateWidget
class AlbumCreate(forms.ModelForm):
class Meta:
releasedate = forms.DateField(widget=AdminDateWidget())
model = music_models.Album
fields = ['artist', 'album_title', 'genre', releasedate, 'notes', 'album_logo', 'rating']
My template is:
{% for field in form %}
<div class="form-group">
<div class="col-sm-offset-2 col-sm-10">
<span class="text-danger small">{{ field.errors }}</span>
</div>
<label class="control-label col-sm-2">
{{ field.label_tag }}
</label>
<div class="col-sm-10">
{{ field }}
</div>
</div>
{% endfor %}
My struggle here is that I am getting this error when rendering the page:
Exception Value:
sequence item 0: expected str instance, DateField found
But according to the https://docs.djangoproject.com/en/1.10/topics/forms/modelforms/ docs, DateField is one of the allowable datatypes. So I am obviously doing it wrong somehow, but don't know how to do it right. Can someone help me out on this? I tend to prefer ground up examples to study from, if possible.
At a glance, it seems there are many problems (no form tags in template, fields can only accept strings, etc.) But most importantly for those wanting to use AdminDateWidget: there are a number of extra scripts you need to load which are NOT included in the usual {{ form.media }}.
project/urls.py
from django.conf.urls import include, url
from album.views import album_add
urlpatterns = [
url(r'album/add/$', album_add, name='album-add'),
]
album/models.py
from django import forms
from django.db import models
from django.contrib.admin.widgets import AdminDateWidget
class Album(models.Model):
artist = models.CharField(max_length=30)
releasedate = models.DateField()
class AlbumForm(forms.ModelForm):
releasedate = forms.DateField(widget=AdminDateWidget)
class Meta:
model = Album
fields = ['artist', 'releasedate']
album/views.py
from .models import AlbumForm
from django.shortcuts import render, HttpResponse
def album_add(request):
if request.method == "GET":
form = AlbumForm()
return render(request, 'album/create_album.html', {'form': form})
elif request.method == "POST":
form = AlbumForm(request.POST)
if form.is_valid():
form.save()
return HttpResponse("Saved.")
return render(request, 'album/create_album.html', {'form': form})
album/templates/album/create_album.html
{% load static %}
<script type="text/javascript" src="/admin/jsi18n/"></script>
<script type="text/javascript" src="{% static 'admin/js/core.js' %}"></script>
<script type="text/javascript" src="{% static 'admin/js/vendor/jquery/jquery.js' %}"></script>
<script type="text/javascript" src="{% static 'admin/js/jquery.init.js' %}"></script>
{{ form.media }}
<link rel="stylesheet" type="text/css" href="{% static 'admin/css/base.css' %}" />
<link rel="stylesheet" type="text/css" href="{% static 'admin/css/widgets.css' %}" />
<form>
{% csrf_token %}
<table>
{{ form }}
</table>
<input type="submit" value="Go!">
</form>
I hope this helps someone!
I found a solution:
admin_forms.py
First add widgets of type AdminDateWidget to your date fields. You will need to assign a custom name as css class attribute (autocomplete=off is optional, disables autofill)
class MyForm(forms.ModelForm):
class Meta:
model = MyModel
fields = ('date_start', 'date_end',)
widgets = {
'date_start': AdminDateWidget(
attrs={'class': 'picker', 'autocomplete': 'off'}),
'date_end': AdminDateWidget(
attrs={'class': 'picker', 'autocomplete': 'off'}),
}
template.html
Secondly, load necessary resources (datepicker.css)and customise the action of your date fields with class 'picker' or any name you assigned to your css class. Check the code in the script tag. IMPORTANT: For some reason the script tags need to be after the styles to work.
{% extends "admin/base_site.html" %}
{% load i18n %}
{% block content %}
<style rel="stylesheet" type="text/css" href="https://cdnjs.cloudflare.com/ajax/libs/datepicker/0.6.5/datepicker.min.css" />
<style>
... Other CSS ...
</style>
<script>
grp.jQuery(function () {
grp.jQuery(".picker").datepicker({dateFormat: 'yy-m-d'});
});
</script>
<form action="{{ action_url }}" method="post" id="my_form">
{% csrf_token %}
<section>
<fieldset class="module grp-module">
{% for field in form %}
<label>{{ field.label }}</label>
{{ field }}
{% endfor %}
</fieldset>
</section>
</form>
{% endblock %}
Access to /admin/jsi18n/ requires superuser authentication in Django v.2.0.7. The following line will not work for non-superusers:
<script type="text/javascript" src="/admin/jsi18n/"></script>
The workaround is to copy script from this URL to jsi18n.js (being authenticated as a superuser). Please, note that under each LOCAL_LANGUAGE jsi18n.js has different version, so if you have more then one target LOCAL_LANGUAGE you will need to save different versions of jsi18n.js.
I am using template inheritance in my django project. I used form in my base html page and submit button, When i inherit base template to another template form get disappeared but submit button is still there. I have below templates.
base.html
<head>
{% load static from staticfiles %}
<link rel="stylesheet" href="{% static "bootstrap.css" %}">
</script>
</head>
<body>
{% block option %}
<div class="row">
<div class="col-lg-3">
<form method = "post" action="">
{% csrf_token %}
{{form}}
<input type="submit" value="Submit" />
</form>
</div>
</div>
{% endblock %}
<div class="row">
{% block content %}{% endblock %}
</div>
</body>
chart.html
{% extends 'base.html' %}
{% block content %}
<head>
{% load static from staticfiles %}
<link rel="stylesheet" href="{% static "bootstrap.css" %}">
<script type="text/javascript" src="https://www.google.com/jsapi"></script>
<script type="text/javascript">
google.load("visualization", "1", {packages:["corechart"]});
</script>
</head>
<div id="container" align="center">
{{ column_chart.as_html }}
{% endblock %}
How can i make form visible there in chart html??
EDIT: Added Views
views.py
def select_chart_form(request):
form = SelectChart(request.POST)
if form.is_valid():
if (str(form.cleaned_data['status']) == '1'):
#print "Hello Naresh reverse('chart1')"
return HttpResponseRedirect('/chart1/')
if (str(form.cleaned_data['status']) == '2'):
return HttpResponseRedirect('/chart2/')
context = {
'form' : form
}
return render(request, 'base.html', context)
def video_by_user(request):
analysis = VideoData.objects.annotate(watches_count = Count('user')).order_by('-watches_count')[:10]
data_source = ModelDataSource(analysis,fields=['video_name', 'watches_count'])
column_chart = gchart.ColumnChart(data_source,options={'title': "Top 10 Videos watched by No. Of Users"})
context = {
"data_source": data_source,
"column_chart": column_chart,
}
return render_to_response('chart.html', context)
I am calling video_by_user method..after click on submit button.
The select_chart_form and video_by_user views are completely separate. The first one renders just base.html, and supplies the form variable when it does so. The second one renders chart.html, which inherits from base.html, but it only supplies the variables needed for chart.html itself: it doesn't provide the form needed for base.html. You will need to supply that in video_by_user.
I am trying to implement end less pagination in Django App but stuck at how to implement twitter like end less scrolling :
My models.py
from django.db import models
from django.contrib import admin
#------------------------------------------------------------------------------
class Book(models.Model):
name = models.CharField(max_length=50)
pub_date = models.DateField(auto_now_add=True)
class bookAdmin(admin.ModelAdmin):
"""Book admin class"""
list_display = ('name','pub_date')
ordering = ('name',)
admin.site.register(Book,bookAdmin)
My views.py :
from models import Book
from django.template import RequestContext
from django.shortcuts import render_to_response
#------------------------------------------------------------------------------
def latest_books(request,template = 'latest_books.html',
page_template = 'latest_books_page.html' ):
context = {}
book_list = Book.objects.order_by('-pub_date')
context.update( {'book_list': book_list, 'page_template': page_template,} )
# override the template and use the 'page' style instead.
if request.is_ajax():
template = page_template
return render_to_response(
template, context, context_instance=RequestContext(request) )
My 'latest_books.html' template :
<html><head><title>Books</title></head>
<body>
<h1>Books</h1>
{% block js %}
{{ block.super }}
<script src="http://ajax.aspnetcdn.com/ajax/jQuery/jquery-1.5.2.min.js" type="text/javascript" charset="utf-8"></script>
<script type="text/javascript" src="http://yourjavascript.com/337923491/endless.js" charset="utf-8"></script>
<script type="text/javascript" src="http://yourjavascript.com/151379951/endless-pagination.js"></script>
<script>$.endlessPaginate();</script>
{% endblock %}
{% block content %}
<div class="endless_page_template">
{% include page_template %}
</div>
{% endblock %}
</body></html>
My latest_books_page.html :
<h2>Viewing All Entries</h2>
{% load endless %}
<div>
<ul>
{% paginate book_list %}
{% for book in book_list %}
<li>{{ book.name }}</li> {{ book.pub_date }}
{% endfor %}
{% show_pages %}
</ul>
</div>
I am facing two issues first if i use {{ block.super }} as given in tutorial .Django gives this error 'BlockNode' object has no attribute 'context' and if i remove {{ block.super }}. I get simple pagination with next and previous functionality .
Can someone help me please. I want to implement on scroll load pagination...
Please try out my code:
views.py :
from models import Book
from django.template import RequestContext
from django.shortcuts import render_to_response
#------------------------------------------------------------------------------
def latest_books(request,template = 'latest_books.html',
page_template = 'latest_books_page.html' ):
context = {}
book_list = Book.objects.order_by('-pub_date')
context.update( {'book_list': book_list, 'page_template': page_template,} )
# override the template and use the 'page' style instead.
if request.is_ajax():
template = page_template
return render_to_response(
template, context, context_instance=RequestContext(request) )
latest_books.html :
<html><head><title>Books</title></head>
<body>
<h1>Books</h1>
<h2>Viewing All Entries</h2>
<div class="endless_page_template">
{% include page_template %}
</div>
{% block js %}
<script src="http://code.jquery.com/jquery-latest.js"></script>
<script src="{{ STATIC_URL }}js/endless_on_scroll.js"></script>
<script src="{{ STATIC_URL }}js/endless-pagination.js"></script>
<script>
$.endlessPaginate({paginateOnScroll: true,
endless_on_scroll_margin : 10,
paginateOnScrollChunkSize: 5
});</script>
{% endblock %}
</body></html>
latest_books_page.html :
{% load endless %}
{% paginate 10 book_list %}
{% for book in book_list %}
{{ book.name }}<br> {{ book.pub_date }}<br><br><br>
{% endfor %}
{% show_more "even more" "working" %}
Try out and let me know ... and enter 20-30 entries into your DB to check it out properly ...
You have to include page_template before call the {{block.super}}
<h2>Entries:</h2>
{% include page_template %}
{% block js %}
{{ block.super }}
<script src="http://code.jquery.com/jquery-latest.js"></script>
<script src="{{ STATIC_URL }}endless_pagination/js/endless-pagination.js"></script>
<script>$.endlessPaginate();</script>
{% endblock %}