views.py
def search_author(request):
if 'q' in request.GET and request.GET['q']:
q = request.GET['q']
authors =User.objects.filter(username=q)
return render_to_response('search_results.html',
{'authors': author, 'query': q})
else:
return HttpResponse('Please submit a search term.')
def search_form(request):
return render_to_response('search_form.html')
urls.py
url(r'^search_author$',app.views.search_author),
url(r'^search_form$', app.views.search_form)
search_form.html
{% extends "app/layout.html" %}
{% block content %}
<form action="/search_author/" method="get">
<input type="text" name="q">
<input type="submit" value="Search">
</form>
search_results.html
{% extends "app/layout.html" %}
{% block content %}
<p>You searched for: <strong>{{ query }}</strong></p>
{% if authors%}
<p>Found {{ authors|length }} author{{ authors|pluralize }}.</p>
<ul>
{% for author in authors %}
<li>{{ author.username }}</li>
{% endfor %}
</ul>
{% else %}
<p>No authors matched your search criteria.</p>
{% endif %}
loginparitial.html
{% if user.is_authenticated %}
<form id="logoutForm" action="/logout" method="post" class="navbar-right">
{% csrf_token %}
<ul class="nav navbar-nav navbar-right">
<li><span class="navbar-brand">您好 {{ user.username }}!</span></li>
<li>查询作者</li>
<li> 发布旧书</li>
<li><a href="user_book_detail" >查看我的书籍</a></li>
<li> 登出</li>
</ul>
when l click the '查询作者' in the home page,the error says
Page not found (404)
Request Method: GET
Request URL: http://127.0.0.1:8000/search_form/
Can anyone help me with my problem ? Thanks in advance
It's because of your regex pattern.
/search_form/ is different from your specified ^search_form$. That maps to /search_form (No trailing slash). To make it /search_form/, just use ^search_form/$.
I think you giving wrong routing to templates.
In settings.py you giving templates directory route like this
TEMPLATES = [
{
'BACKEND': 'django.template.backends.django.DjangoTemplates',
'DIRS': [os.path.join(BASE_DIR, 'templates')],
'APP_DIRS': True,
'OPTIONS': {
'context_processors': [
'django.template.context_processors.debug',
'django.template.context_processors.request',
'django.contrib.auth.context_processors.auth',
'django.contrib.messages.context_processors.messages',
],
},
},
]
then your templates loaded from main app folder --> templates folder.
You can call templates directly in views.
If you save your templates in another folder in templates folder,then you need to give the template route upto that folder.
For example:
you saved your templates in main app folder -->templates --> app folder.
then you have to give the route upto to app folder.
like this:
def search_form(request):
return render_to_response('app/search_form.html').
Try once..!
Related
I just want to display profile picture.Img upload successfully but not showing the img.But if i try in admin panel then show me img. Here is my index.html code
{% extends 'Login_app/base.html' %}
{% block body_block %}
{% if user.is_authenticated %}
<p>Hi {{ user_basic_info.username }},</p>
<p>Your Email {{ user_basic_info.email }}</p>
<p> Facebook Profile </p>
<img src="/media/{{ user_more_info.profile_pic }}" width="200px">
{% else %}
<div class="alert alert-primary"></div>You are not logged in!!</div>
{% endif %}
{% endblock %}
Here is my setting.py media setting
import os
MEDIA_ROOT = os.path.join(BASE_DIR, 'media') # This is a tuple
MEDIA_URL = '/media/'
Here the ss of website
You have to add .url after the profile picture.
Try This:
<img src="/media/{{ user_more_info.profile_pic.url }}" width="200px">
OR
In Models.py define a get_absolute_url() method to join the media directory:
def get_absolute_image(self):
return os.path.join('/media', self.image.name)
And in templates do this:
{% for post in posts %}
<img src="{{ post.get_absolute_image }}" width="200px">
{% endfor %}
p.s.- here post is model name
django setting
BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
STATIC_URL = '/static/'
STATIC_ROOT = os.path.join(BASE_DIR, 'staticfiles')
STATICFILES_DIRS = (
os.path.join(BASE_DIR, "static"),
)
MEDIA_URL = '/media/'
MEDIA_ROOT = os.path.join(BASE_DIR, 'media')
django views
def single_article(request, page, slug):
article = get_object_or_404(Article, slug=slug)
return render(request, "article/single_article.html", locals())
django template
<`enter code here`img class="d-block w-100 img-responsive" style="height: 100%" src="{{ article.picture.url }}" alt="{{ article.title }}"
> Blockquote
you don't have to pass /media/ or use .url to fetch it from db
{% extends 'Login_app/base.html' %}
{% block body_block %}
{% if user.is_authenticated %}
<p>Hi {{ user_basic_info.username }},</p>
<p>Your Email {{ user_basic_info.email }}</p>
<p> Facebook Profile </p>
<img src="{{ user_more_info.profile_pic.url }}" width="200px">
{% else %}
<div class="alert alert-primary"></div>You are not logged in!!</div>
{% endif %}
{% endblock %}
this will work if still image is not loadin add you views
Try to add this code to the project's urls.py:
urlpatterns = [
...
] + static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT)
I have this app in which I need to display an image on the html template which is not happening.
models.py
class cateledetails(models.Model):
cdid=models.IntegerField(unique=True,default=0)
cid=models.ForeignKey(category,to_field='cid',on_delete=models.CASCADE)
elename=models.CharField(max_length=20)
imgsrc=models.ImageField(upload_to='elements/',blank=True)
def __unicode__(self):
return u"{} {}".format(self.cdid,self.elename)
class Meta:
db_table="cateledetails"
views.py
def mainpage(request):
pic_details=get_object_or_404(cateledetails,pk=1)
template=loader.get_template('student/mainpage.html')
context={'pic_details': pic_details,}
return HttpResponse(template.render(context,request))
urls.py
urlpatterns= [
url(r'^mainpage/$',views.mainpage ,name='mainpage'),
] + static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT)
settings.py
MEDIA_ROOT = os.path.join(BASE_DIR, 'media')
MEDIA_URL = '/media/'
mainpage.html
{% block body %}
<form action="" method="post" enctype="multipart/form-data">
{% csrf_token %}
<h4>What sound does it make?</h4>
{% for image in pic_details.imgsrc_set.all %}
<img src="{{ image.imgsrc.url }}" alt="image">
{% endfor %}
</form>
{% endblock %}
what do I do?
pic_details is a cateledetails object.
This class has a single ImageField called imgsrc. Since imgsrc isn't a ForeignKey you can't use the ForeignKey <field>_set syntax with it. Instead, simply refer to the field directly:
{% block body %}
<form action="" method="post" enctype="multipart/form-data">
{% csrf_token %}
<h4>What sound does it make?</h4>
<img src="{{ pic_details.imgsrc.url }}" alt="image">
</form>
{% endblock %}
I have generated a django-admin for my app and I can access the dashboard. But it contains a logo that says "django admin". I want to change it to my own custom logo. How can I do that?
I have tried adding a base.html file to admin directory and tried to override but for some reason it's not working. It's code is as follows:
{% extends "admin/base.html" %}
{% load theming_tags %}
{% load staticfiles %}
{% block blockbots %}
{{ block.super }}
{# Using blockbots ensures theming css comes after any form media and other css #}
{% render_theming_css %}
<style type="text/css">
#header #branding h1 {
background-image: url("bootstrap_admin/img/logo-140x60.png");
}
</style>
{% endblock %}
{% block branding %}
<a href="{% url 'admin:index' %}" class="django-admin-logo">
<!-- Django Administration -->
<img src="{% static "bootstrap_admin/img/logo-140x60.png" %}" alt="{{ site_header|default:_('Django Admin') }}">
</a>
{% endblock branding %}
I want to change the logo in the top-left corner. How can I achieve what I'm trying to?
your question is answered here
"{% static "bootstrap_admin/img/logo-140x60.png" %}"
this comes from here
django-admin-bootstrap/bootstrap_admin/static/bootstrap_admin/img/logo-140x60.png
after replacing you need to run command python manage.py collectstaticthen this will work
The official way to achieve that is:
You need to override the default templates provided by Django. In your Django settings, your code:: TEMPLATES setting looks like this.
TEMPLATES = [
{
'BACKEND': 'django.template.backends.django.DjangoTemplates',
'DIRS': [],
'APP_DIRS': True,
'OPTIONS': {
'context_processors': [
'django.template.context_processors.debug',
'django.template.context_processors.request',
'django.contrib.auth.context_processors.auth',
'django.contrib.messages.context_processors.messages',
],
},
},
]
This means that Django will look for templates in a directory called templates inside each app, but you can override that by setting a value for TEMPLATES.DIRS.
We change the 'DIRS': [], to 'DIRS': [os.path.join(BASE_DIR, 'templates/')], and create the templates folder. If your STATICFILES_DIRS is empty set it to:
STATICFILES_DIRS = [
os.path.join(BASE_DIR, "static"),
]
Now create a file called base_site.html from the admin app to templates\admin folder you just created. Add the code in it:
{% extends "admin/base.html" %}
{% load staticfiles %}
{% block title %}{{ title }} | {{ site_title|default:_('Django site admin') }}{%
endblock %}
{% block branding %}
<h1 id="site-name">
<a href="{% url 'admin:index' %}">
<img src="{% static 'Your image.png' %}" height="40px" />
</a>
</h1>
{% endblock %}
{% block nav-global %}{% endblock %}
I'm planning to add change language dropdown in my admin page.
according to this code and How to extend admin page.
I copy base_site.html and copy it to myapp/templates/admin, the i create a html file named change_language.html and write this code in it:
{% load i18n %}
/ {% trans 'Change language' %}
<form action="/i18n/setlang/" method="post" style="display: inline;">
<div style="display: inline;">
<select name="language" onchange="javascript:form.submit()">
{% for lang in LANGUAGES %}
<option value="{{ lang.0 }}"{% ifequal LANGUAGE_CODE lang.0 %} selected="selected"{% endifequal %}>{{ lang.1 }}</option>
{% endfor %}
</select>
</div>
</form>
I add {% extends 'admin/base_site.html' %} at the top of this file, noting happens.
I add {% extends 'admin/base.html' %} , again noting happens.
All hints and answers says that we should change something name <div id="user-tools"> at line 25 of base.html, But in Django 1.10 it goes to line 31 with a different staff. im kinnda lost because i read many different staff every where and non of them works for me. Dose any know where im doing wrong ?
here is my middlewares :
MIDDLEWARE = [
'django.middleware.security.SecurityMiddleware',
'django.contrib.sessions.middleware.SessionMiddleware',
'django.middleware.locale.LocaleMiddleware',
'django.middleware.common.CommonMiddleware',
'django.middleware.csrf.CsrfViewMiddleware',
'django.contrib.auth.middleware.AuthenticationMiddleware',
'django.contrib.messages.middleware.MessageMiddleware',
'django.middleware.clickjacking.XFrameOptionsMiddleware',
]
And template settings :
TEMPLATES = [
{
'BACKEND': 'django.template.backends.django.DjangoTemplates',
'DIRS': [
os.path.join(BASE_DIR,'templates'),
],
'APP_DIRS': True,
'OPTIONS': {
'context_processors': [
'django.template.context_processors.debug',
'django.template.context_processors.request',
'django.contrib.auth.context_processors.auth',
'django.contrib.messages.context_processors.messages',
],
},
},
]
In your templates/admin folder, make sure the file is named base_site.html (otherwise the default base_site will not be overwritten).
Make sure to copy the latest version of the file from the django-repo.
Most important: verify you extend the admins base.html (your base_site.html should start with {% extends "admin/base.html" %})
You may now add your form (for example to the footer):
{% extends "admin/base.html" %}
{% load i18n %}
{% block title %}{{ title }} | {{ site_title|default:_('Django site admin') }}{% endblock %}
{% block branding %}
<h1 id="site-name">{{ site_header|default:_('Django administration') }}</h1>
{% endblock %}
{% block nav-global %}{% endblock %}
{% block footer %}
<div id="footer">
<form action="/i18n/setlang/" method="post">
{% csrf_token %}
<select name="language">
{% for lang in LANGUAGES %}
<option value="{{ lang.0 }}"
{% ifequal lang.0 request.LANGUAGE_CODE %}
selected="yes"
{% endifequal %}
>{{ lang.1 }}</option>
{% endfor %}
</select>
<input type="submit" value="{% trans 'Change language' %}" />
</form>
</div>
{% endblock %}
Refer to the base.html to find a block that seems suitable for your form.
You will also need to add the i18n urls to your url-settings
url(r'^i18n/', include('django.conf.urls.i18n')),
And if you really want to submit your form using javascript you will also need to get and submit the csrf token for the form. The django docs cover this topic quite comprehensive.
In addition to Kim's answer, you should add i18n context processor in your django settings django.template.context_processors.i18n to be able to access LANGUAGES variable in the template.
I guess you are mixing both answers that you've found on the internet. One of them copies and changes a couple of files from the admin template, effectively overriding them in your program's references. The second one extends admin's templates. You should completely implement just one of them.
I have a model with a ImageField and created an simple Upload Form via CreateForm. I have a simple ListView to show the images (logos).
Upload works fine, Iterating the logos works. Property logo.url is missing but instead it is logo.media. Unfortunately media does not contain the whole path, MEDIA_ROOT is missing. What am I doing wrong here?
models.py:
class Logo(models.Model):
media = models.ImageField(upload_to='uploads')
views.py:
class LogoManager(CreateView):
model = Logo
template_name = 'polls/upload.html'
success_url = '/logos/'
class LogoIndex(ListView):
model = Logo
template_name = 'polls/logos.html'
upload.html:
{% block title %} Upload Form {% endblock %}
{% block content %}
<form id="my_form" action="" method="post" enctype="multipart/form-data">{% csrf_token %}
{{ form.as_p }}
<input type="submit" value="Save Changes" />
</form>
<br />
Back
{% endblock %}
logos.html:
{% block content %}
{% if object_list %}
<ul>
{% for image in object_list %}
<li><img src="{{ image.media }}" width="320" height="200"/></li>
{% endfor %}
</ul>
{% else %}
<p>No Logos are available.</p>
{% endif %}
<br />
{% endblock %}
Output is:
<li><img src="uploads/IMG_5106.JPG" width="320" height="200"/></li>
You'll want to use {{ image.media.url }}, I think.
OK, it was my wrong. I was editing the url in the apps url file. When adding this stanza in root urls.py it works fine:
if settings.DEBUG:
urlpatterns += patterns('django.views.static',
(r'%s(?P<path>.*)' % settings.MEDIA_URL, 'serve', {'document_root': settings.MEDIA_ROOT}),
)
using settings.py:
MEDIA_URL = '/media/'