I would like to use some custom CSS and images on my custom 404/500 pages that I made. Django doesn't include the STATIC_URL variable in those pages though.
What would be the best way to accomplish this? I also tried making a custom 404/500 view and rendering an arbitrary HTML file but it didn't work out so great.
Here's how I would do it:
# urls or settings
handler500 = 'mysite.views.server_error'
# views
from django.shortcuts import render
def server_error(request):
# one of the things ‘render’ does is add ‘STATIC_URL’ to
# the context, making it available from within the template.
response = render(request, '500.html')
response.status_code = 500
return response
It's worth mentioning the reason Django doesn't do this by default:
“The default 500 view passes no variables to the 500.html template and is rendered with an empty Context to lessen the chance of additional errors.”
-- Adrian Holovaty, Django documentation
I run into the same problem and found a solution which doesn't need custom templates or handlers. From Django 1.4 on you can use the tags get_media_prefix and get_static_prefix to access MEDIA_URL and STATIC_URL when they are not in the context.
In my particular case (Django 1.5), I wanted to access some static images in my page 500.html. I just added at the beginning of the template
{% load static %}
and then obtained the media and static urls with these tags
<img src="{% get_media_prefix %}logo.png">
<img src="{% get_static_prefix %}img/error_pages/error.png" style="height:235px;">
You can find the official documentation here: https://docs.djangoproject.com/en/1.5/ref/templates/builtins/#get-static-prefix
I believe you're just going to have to override the default 404/500 error handling. This should get you started:
http://docs.djangoproject.com/en/dev/topics/http/views/#customizing-error-views
Related
In case I'm:
at a very early stage of developing;
using Chrome, which doesn't allow images from local resource, and
storing my images in a local /static folder,
what could be the best workaround for displaying images, other than through the {% static %} tag?
I have been using {% load static %}...{% static variable/path %} in my templates, but now I'm trying to display images in the admin page, which requires a good deal of overriding, and admin templates aren't easy to find where exactly to override.
Lately I tried format_html, as in:
from django.contrib import admin
(...)
#admin.display(description='Foto')
def show_foto(self):
return format_html(
'<img src=https://media.(...)>'
)
Which works fine as long as the image resource isn't local.
Also, Django tags don't seem to work inside format_html().
So I set up profile pic upload as guided by http://www.tangowithdjango.com/book/chapters/login.html.
Then I found the second answer(by user Raisins) to useful for my purpose and implemented it Extending the User model with custom fields in Django. As I've been that this answer is outdated, I've also tried the solution offered here for migration Get rid of get_profile() in a migration to Django 1.6 which hasn't improved my situation
Then in my views, I add required details including the image to a dictionary, and render i to the HTML page. It looks as though the UserProfile isn't returning the right object.
u=User.object.get(username__exact=request.user)
profile=UserProfile.objects.get(user=u)
global client
client['login']=True
client['name']=u.username
client['password']=u.password
client['email']=u.email
client['picture']=profile.picture
return render(request,'index.html',{'client':client})
And when I try to display the details on HTML page, everything except image is loaded.
I tried
<img src="profile_images/{{client.picture}}">
where profile_images is in the root directory. I inspected the element and I find this
<img src="/static/profile_images/%7B%7B%20client.picture%20%7D%7D">
where I was expecting "1.jpg" instead of "%7B%7B%20client.picture%20%7D%7D".
Any help is appreciated. Thanks
Raisin's answer is outdated. Please don't use AUTH_PROFILE_MODULE in Django 1.6 anymore. In fact, you don't even need to handle the post_save signal.
Based on the same tutorial, you will find the code for your view:
u = User.objects.get(username=request.user)
try:
p = UserProfile.objects.get(user=u)
except:
p = None
return render(request,'index.html',{'client':client, 'userprofile':p})
In your template use:
{% if userprofile.picture %}
<img src="{{ userprofile.picture.url }}" />
{% endif %}
I solved my problem by using
{% load staticfiles %}
<img src="{% static client.picture %}" />
I'm doing a website in html and base (where all pages extend) I want
to put a session of social network icons. As this session is base on
html it should be displayed on all pages of the website.
I do not want
to put this session in a static html, I want to do in django using
models. This is already done.
Question: Do I have to put the session of social network icons on each view, or can I make a separate view and all others extend this view?
How can I do this?
Try using an inclusion tag. You can create a function for doing all of the work to create the sessions and then associate that with a particular block of HTML.
templatetags/session.py
#register.inclusion_tag('includes/session_box.html')
def output_session_box(...):
...
return { .. }
The associated template file, includes/session_box.html, would have the HTML like any template.
And then your base.html would have:
{% load session %}
{% output_session_box ... %}
Use RequestContext and a context_processor to inject template variables into every view using RequestContext.
It's as simple as a python function accepting request as an arg, and returning a dictionary to be passed into your template.
https://docs.djangoproject.com/en/dev/ref/templates/api/#django.template.RequestContext
def my_processor(request):
return {'foo': 'bar'}
TEMPLATE_CONTEXT_PROCESSORS = (
# add path to your context processor here.
)
I generally have a per-project processor for the basics... It's exactly how django adds {{ user }} or {{ STATIC_URL }} to every template.
Django newbie here. Following the documentation, I am trying the following to get a link to the admin site from the homepage of the public site I'm building:
{% load admin_urls %}
<p>Go to the admin.</p>
I am getting the error:
NoReverseMatch at /
u'opts|admin_urlname' is not a registered namespace
I am including the URLs properly:
url(r'^admin/', include(admin.site.urls)),
My template loaders are in the right order.
I've tried a few different variations on this, and they all throw namespace errors.
Any ideas? Thanks!
After 30 minutes with Daniel Roseman / Django docs in one screen and my code in the other, I come up with this simple solution:
In your views.py, add the opts context with the _meta of the model (that includes the required app_label and model_name):
class YourModelDetailView(DetailView):
def get_context_data(self, **kwargs):
context = super(YourModelDetailView, self).get_context_data(**kwargs)
context["opts"] = YourModel._meta
return context
In your templates:
{% url opts|admin_urlname:'change' object.pk %}
Where change can be any action in the reverse admin urls documentation page.
While the above answers were helpful about the code I was calling, there is a much easier way. I'm using this instead:
{% url 'admin:index' %}
This works for custom admin views as well, like:
{% url 'admin:myapp_mymodel_<keyword>' object.id %}
Where keyword is from the named parameters listed here (i.e. add, change, delete).
You are almost certainly using the released 1.4 version, rather than the development version. As the documentation for that version shows, you need to use {% load url from future %} before you can use that syntax.
I used this social registration/signup library django allauth for a project of mine. How do i customize the default templates and forms to give a better look and feel?
Assuming you have set a project level templates directory using the TEMPLATE_DIRS setting like:
TEMPLATE_DIRS = [
os.path.join(PROJECT_DIR, 'templates'),
]
You should be able to copy all of the folders shown here into that directory and edit them as you need. Most of the templates seem to be filling a {% block content %} block, so it's probably easiest if your site_base.html template defines that block somewhere.
If you haven't set TEMPLATE_DIRS, you can do the same thing, but copy the template folders into the templates directory of one of your apps. I prefer to set TEMPLATE_DIRS and keep the main site templates like base.html there, since they don't really belong to a particular app, but that's really just a preference; the template loader should find them either way.
In your views:
from allauth.account.views import SignupView, LoginView
class MySignupView(SignupView):
template_name = 'my_signup.html'
class MyLoginView(LoginView):
template_name = 'my_login.html'
Do pay attention to the examples and docs for structuring your own templates.
Watch this piece in the example templates though:
<form id="signup_form" method="post" action="{% url 'account_signup' %}">
I had to remove the URL link to make it work properly in my own template:
<form id="signup_form" method="post" action="">'
the latest version of all-auth on github has its templates outside, however the one on Pypi is not, all you need to do is clone the repo in your project directory and override the templates. As simple as that.
Use the same logic as overriding admin templates.
Have a look at the example application; it has a templates folder that indicates the layout of the necessary templates
All of these are good suggestions.
Most of these ought to work.
The only thing that worked for me, though, was to include my own templates in "project/app/templates/account/" and make sure that "django-allauth" gets listed in INSTALLED_APPS after my own app.
I discovered this here.
To customize django-allauth after installing it, copy it from site-packages and paste it in your project apps directory. In this way the default allauth app and its templates being used will be those in your project's allauth app. Then if you want to modify signup.html of socialaccount then go to apps\allauth\templates\socialaccount\signup.html and modify it by editting inside 'block content' tag:
{% block content %}
// your customized html for signup form
{% endblock %}
Hope this will help you.