So i am building a personal website and am using Materialize for web designing. At first it was good and my pages look good, but then I added some new pages and i found that the css is not applied in these new pages, can anybody help me in solving this.
Actually both are same pages(categories.html) but the path are different.
header.html (main html file, have not changed the name yet)
<<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<!--Import Google Icon Font-->
<link href="https://fonts.googleapis.com/icon?family=Material+Icons" rel="stylesheet">
<!--Import materialize.css-->
<link type="text/css" rel="stylesheet" href="static/main/materialize.css" media="screen,projection"/>
</head>
<body>
{% load static %}
{% include "main/includes/navbar.html" %}
{% include "main/includes/messages.html" %}
<main>
<div style="background-image: url('https://www.google.com/url?sa=i&url=https%3A%2F%2Fwallpapersafari.com%2Fw%2FcU6JWo&psig=AOvVaw1eBAulQvnXOrIK1yQueVX5&ust=1623841457736000&source=images&cd=vfe&ved=0CAIQjRxqFwoTCPje9_--mfECFQAAAAAdAAAAABAD')">
<div class = "container">
<br>
{% block content %}
{% endblock %}
</div>
</div>
</main>
{% include "main/includes/footer.html" %}
<script type="text/javascript" src="static/main/materialize.js"></script>
</body>
</html>
views.py
from django.shortcuts import render, redirect
from django.http import HttpResponse
from .models import Item, ItemSeries, ItemCategory
from django.contrib.auth.forms import AuthenticationForm
from django.contrib.auth import login, logout, authenticate
from django.contrib import messages
from .forms import NewUserForm
def single_slug(request, single_slug):
categories = [c.category_slug for c in ItemCategory.objects.all()]
if single_slug in categories:
matching_series = ItemSeries.objects.filter(item_category__category_slug=single_slug)
series_urls = {}
for m in matching_series.all():
part_one = Item.objects.filter(item_series__item_series=m.item_series).earliest("item_update")
series_urls[m] = part_one.item_slug
return render(request,
"main/category.html",
{"part_ones": series_urls})
items = [c.item_slug for c in Item.objects.all()]
if single_slug in items:
this_item = Item.objects.get(item_slug=single_slug)
return render(request,
"main/item.html",
{"item":this_item})
return HttpResponse(f"{single_slug} does not correspond to anything.")
def product(request):
return render(request = request,
template_name = "main/categories.html",
context ={"categories": ItemCategory.objects.all})
def homepage(request):
return render(request = request,
template_name = "main/categories.html",
context ={"categories": ItemCategory.objects.all})
def about(request):
return render(request = request,
template_name = "main/about.html",
context ={"categories": ItemCategory.objects.all})
def contact(request):
return render(request = request,
template_name = "main/contact.html",
context ={"categories": ItemCategory.objects.all})
def register(request):
if request.method == "POST":
form = NewUserForm(request.POST)
if form.is_valid():
user = form.save()
username = form.cleaned_data.get('username')
messages.success(request, f"New Account Created: {username}")
login(request, user)
messages.info(request, f"You are now logged in as: {username}")
return redirect("main:homepage")
else:
for msg in form.error_messages:
messages.error(request, f"{msg}: {form.error_messages[msg]}")
form = NewUserForm
return render(request,
"main/register.html",
context = {"form": form})
def logout_request(request):
logout(request)
messages.info(request, "Logged out successfully!")
return redirect("main:homepage")
def login_request(request):
if request.method == "POST":
form = AuthenticationForm(request, data = request.POST)
if form.is_valid():
username = form.cleaned_data.get('username')
password = form.cleaned_data.get('password')
user = authenticate(username = username, password = password)
if user is not None:
login(request, user)
messages.info(request, f"You are now logged in as: {username}")
return redirect("main:homepage")
else:
messages.error(request, "Invalid username or password")
else:
messages.error(request, "Invalid username or password")
form = AuthenticationForm()
return render(request,
"main/login.html",
{"form": form})
navbar.html
{% load static %}
<!-- Dropdown Structure -->
<ul id='dropdown1' class='dropdown-content'>
<li>one</li>
<li>two</li>
<li class="divider" tabindex="-1"></li>
<li>three</li>
<li><i class="material-icons">view_module</i>four</li>
<li><i class="material-icons">cloud</i>five</li>
</ul>
<nav>
<div id="nav-wrapper">
<div>
<ul class="center hide-on-med-and-down">
<li>
Home
</li>
<li>
About Us
</li>
<li>
Products
</li>
<li>
Services
</li>
<li>
Contact
</li>
<li>
<a class='dropdown-trigger btn' href='#' data-target='dropdown1'>Drop Me!</a>
</li>
</ul>
</div>
</div>
</nav>
categories.html
{% extends "main/header.html" %}
{% block content %}
<div class="row">
{% for cat in categories %}
<div class="col s12 m6 l4">
<a href="{{cat.category_slug}}", style="color:#000">
<div class="card hoverable">
<div class="card-content">
<div class="card-title">{{cat.item_category}}</div>
<p>{{cat.category_summary}}</p>
</div>
</div>
</a>
</div>
{% endfor %}
</div>
{% endblock %}
When CSS worked This is home page
When CSS did not work This is the same homepage after clicking 'about us' link form navbar
I am stuck and don't know what to do next, any help would be appretiated.
According to the comment above, i changed my header.html,
<<!DOCTYPE html> <html> <head> <meta charset="utf-8">
<!--Import Google Icon Font-->
<link href="https://fonts.googleapis.com/icon?family=Material+Icons" rel="stylesheet">
<!--Import materialize.css-->
<link type="text/css" rel="stylesheet" href="/static/main/materialize.css" media="screen,projection"/>
</head>
<body>
{% load static %}
{% include "main/includes/navbar.html" %}
{% include "main/includes/messages.html" %}
<main>
<div style="background-image: url('https://www.google.com/url?sa=i&url=https%3A%2F%2Fwallpapersafari.com%2Fw%2FcU6JWo&psig=AOvVaw1eBAulQvnXOrIK1yQueVX5&ust=1623841457736000&source=images&cd=vfe&ved=0CAIQjRxqFwoTCPje9_--mfECFQAAAAAdAAAAABAD')">
<div class = "container">
<br>
{% block content %}
{% endblock %}
</div>
</div>
</main>
{% include "main/includes/footer.html" %}
<script type="text/javascript" src="/static/main/materialize.js"></script> </body> </html>
notice the href of css and js link tag.
There are a few things that I have seen here that don't look correct. Number 1, Are you inheriting your template from your base?
{% extends 'base.html' %}
This is where you should call your materialize.css (in the base template)
Load static is in the wrong place, you are calling static after the link to the css, load static should be at the very top of the template:
{% extends 'base.html' %} {% load static %}
You have an extra opening chevron in your DOCTYPE.
Put materialize js in you base template before closing body tag. Django by default inherits the default base template so this is what you could be missing.
In case I have misunderstood, and you are only wanting to call materialize.css for that header template you can use tags after the call for load static
{% block extra_css %}<link rel="stylesheet" href="{% static 'main/materialize.css' %}"> {% endblock extra_css %}
This might help:
{% load static %} above doctype tag!
{% load static %}
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<!--Import Google Icon Font-->
<link href="https://fonts.googleapis.com/icon?family=Material+Icons" rel="stylesheet">
<!--Import materialize.css-->
<link type="text/css" rel="stylesheet" href="{% static 'main/materialize.css' %}" media="screen,projection"/>
</head>
<body>
{% include "main/includes/navbar.html" %}
{% include "main/includes/messages.html" %}
<main>
<div style="background-image: url('https://www.google.com/url?sa=i&url=https%3A%2F%2Fwallpapersafari.com%2Fw%2FcU6JWo&psig=AOvVaw1eBAulQvnXOrIK1yQueVX5&ust=1623841457736000&source=images&cd=vfe&ved=0CAIQjRxqFwoTCPje9_--mfECFQAAAAAdAAAAABAD')">
<div class = "container">
<br>
{% block content %}
{% endblock %}
</div>
</div>
</main>
{% include "main/includes/footer.html" %}
<script type="text/javascript" src="{% static 'main/materialize.js' %}"></script>
</body>
</html>
In every html page {% load static %} below {% block content %} and above the html of the page!
Static files path:
{% static 'app name/filefoldername' %}
Hope you understood! Look for some tutorials on youtube also!
Related
Im having a problem with project for school that im working on. when i run the code and go to "random page" link that i created, nothing happens. After trying for a bit, i think the problem is that whatever is in {{}} doesnt seem to be found. views.py:
from django.shortcuts import render
from django.http import HttpResponse
from . import util
import random
def index(request):
return render(request, "encyclopedia/index.html", {
"entries": util.list_entries()
})
random_page = random.choice(entries)
def CSS(request):
return render(request, "encyclopedia/css_tem.html", {
"article_css": "css is slug and cat"
})
def Python(request):
return render(request, "encyclopedia/python_tem.html", {
"article_python": "python says repost if scav"
})
def HTML(request):
return render(request, "encyclopedia/HTML_tem.html", {
"article_HTML": "game theory: scavs are future humans"
})
def Git(request):
return render(request, "encyclopedia/Git_tem.html", {
"article_Git": "github is git"
})
def Django(request):
return render(request, "encyclopedia/Django_tem.html", {
"article_Django": "this is a framework"
})
layout.html:
<!DOCTYPE html>
<html lang="en">
<head>
<title>{% block title %}{% endblock %}</title>
<link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.4.1/css/bootstrap.min.css" integrity="sha384-Vkoo8x4CGsO3+Hhxv8T/Q5PaXtkKtu6ug5TOeNV6gBiFeWPGFN9MuhOf23Q9Ifjh" crossorigin="anonymous">
<link href="{% static 'encyclopedia/styles.css' %}" rel="stylesheet">
</head>
<body>
<div class="row">
<div class="sidebar col-lg-2 col-md-3">
<h2>Wiki</h2>
<form>
<input class="search" type="text" name="q" placeholder="Search Encyclopedia">
</form>
<div>
Home
</div>
<div>
Create New Page
</div>
<div>
Random Page
</div>
{% block nav %}
{% endblock %}
</div>
<div class="main col-lg-10 col-md-9">
{% block body %}
{% endblock %}
</div>
</div>
</body>
</html>
Your index() method returns before selecting the random_page, so that code never gets run. Your filenames don't match your code, but in essence you need to pass the random page name into the context of the index page.
View:
def index(request):
random_page = random.choice(entries)
return render(request, "encyclopedia/index.html", {
"entries": util.list_entries(),
"random_page": random_page,
})
"encyclopedia/index.html"
[...]
<div>
Random Page
</div>
[...]
Here is my html file of landing page.
{% load static %}
<!DOCTYPE html>
<html lang="en" dir="ltr">
<head>
<meta charset="utf-8">
<title></title>
<link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.3.1/css/bootstrap.min.css" integrity="sha384-ggOyR0iXCbMQv3Xipma34MD+dH/1fQ784/j6cY/iJTQUOhcWr7x9JvoRxT2MZw1T" crossorigin="anonymous">
<link rel="stylesheet" href="{% static 'css/base.css' %}">
</head>
<body>
<div class="center-column">
<form method="POST" action="/">
{% csrf_token %}
{{form.title}}
<input class="btn btn-info" type="submit" name="Create Task">
</form>
<div class="todo-list">
{% for task in tasks %}
<div class="item-row">
<a class="btn btn-sm btn-info" href="{% url 'update_task' task.id %}">Update</a>
<a class="btn btn-sm btn-danger" href="{% url 'delete' task.id %}">Delete</a>
{% if task.complete == True %}
<strike>{{task}}</strike>
{% else %}
<span>{{task}}</span>
{% endif %}
</div>
{% endfor %}
</div>
</div>
</body>
</html>
Here is Models.py file where a table is created
class Task(models.Model):
title = models.CharField(max_length=200)
complete = models.BooleanField(default=False)
created = models.DateTimeField(auto_now_add=True)
def __str__(self):
return self.title
Error i am getting
OperationalError at /
no such table: tasks_task
C:\Users\91870\Desktop\Django\todo\tasks\templates\tasks\list.html, error at line 15
line 15 is
{% for task in tasks %}
here is views.py file
def index(request):
tasks = Task.objects.all()
form = TaskForm()
if request.method =='POST':
form = TaskForm(request.POST)
if form.is_valid():
form.save()
return redirect('/')
return render(request, 'tasks/list.html', {'tasks':tasks, 'form':form})
It was working when i haven't applied the css but now it isn't.
Can someone please help me with this
I am making a web site by seeing Django tutorial.But message in results.html is not shown.
results.html is
{% extends "polls/base.html" %}
{% load bootstrap3 %}
{% block contents %}
<h1>{{ question.question_text }}</h1>
<ul>
{% for choice in question.choice_set.all %}
<li>{{ choice.choice_text }} -- {{ choice.votes }} vote{{ choice.votes|pluralize }}</li>
{% endfor %}
</ul>
Vote again?
{% endblock contents %}
results.html inherits base.html.
base.html is
{% load staticfiles %}
{% load bootstrap3 %}
<html lang="en">
<head>
<meta charset="utf-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1">
<meta name="description" content="">
<meta name="author" content="">
<link rel="icon" href="../../favicon.ico">
<title>Starter Template for Bootstrap</title>
<!-- Bootstrap core CSS -->
<link href="{% static 'css/bootstrap.min.css' %}" rel="stylesheet">
<style type="text/css">
body {
padding-top: 50px;
}
</style>
</head>
<body>
<nav class="navbar navbar-inverse navbar-fixed-top">
<div class="container">
<div class="navbar-header">
<button type="button" class="navbar-toggle collapsed" data-toggle="collapse" data-target="#navbar" aria-expanded="false" aria-controls="navbar">
<span class="sr-only">Toggle navigation</span>
<span class="icon-bar"></span>
<span class="icon-bar"></span>
<span class="icon-bar"></span>
</button>
<a class="navbar-brand" href="{% url 'index' %}">Tutorial</a>
</div>
<div id="navbar" class="collapse navbar-collapse">
<ul class="nav navbar-nav">
<li class="{% block nav_polls %}{% endblock %}">polls</li>
<li class="">admin</li>
</ul>
</div><!--/.nav-collapse -->
</div>
</nav>
<div class="container">
{% if messages %}
{% bootstrap_messages messages %}
{% endif %}
{% block contents %}{% endblock %}
</div>
<!-- Bootstrap core JavaScript
================================================== -->
<!-- Placed at the end of the document so the pages load faster -->
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.3/jquery.min.js"></script>
<script>window.jQuery || document.write('<script src="../../assets/js/vendor/jquery.min.js"><\/script>')</script>
<script src="{% static 'js/bootstrap.min.js' %}"></script>
</body>
</html>
I wanna show this part
<div class="container">
{% if messages %}
{% bootstrap_messages messages %}
{% endif %}
{% block contents %}{% endblock %}
</div>
in results.html. Bootstrap in base.html is shown in results.html so I really cannot understand why messages is not shown.views.py is
from django.shortcuts import render
from django.urls import reverse_lazy
from .models import Question
from django.shortcuts import get_object_or_404,redirect
from .models import Choice
from .forms import MyForm
from .forms import VoteForm
from django.views.generic import FormView
from django.views.generic.detail import SingleObjectMixin
from django.shortcuts import resolve_url
from django.contrib import messages
from django.urls import reverse
# Create your views here.
def index(request):
return render(request,'polls/index.html',{
'questions': Question.objects.all(),
})
def vote(request,pk):
question = get_object_or_404(Question,pk=pk)
try:
selected_choice = question.choice_set.get(pk=request.POST['choice'])
except (KeyError,Choice.DoesNotExist):
return render(request,'polls/detail.html',{
'question':question,
'error_message':"You didn't select a choice",
})
else:
selected_choice.votes += 1
selected_choice.save()
# return redirect(reverse('polls:poll_results'), pk=pk)
# return redirect('results_url', pk=pk)
return redirect('polls:polls_results', pk=pk)
def results(request,pk):
obj = get_object_or_404(Question,pk=pk)
return render(request,'polls/results.html',{
'question':obj,
})
class FormTest(FormView):
form_class = MyForm
template_name = 'polls/form.html'
success_url = reverse_lazy('polls:index')
form_test = FormTest.as_view()
class Detail(SingleObjectMixin,FormView):
model = Question
form_class = VoteForm
context_object_name = 'question'
template_name = 'polls/detail.html'
def get(self, request, *args, **kwargs):
self.object = self.get_object()
return super().post(request, *args, **kwargs)
def post(self, request, *args, **kwargs):
self.object = self.get_object()
return super().post(request, *args, **kwargs)
def get_form_kwargs(self):
kwargs = super().get_form_kwargs()
kwargs['question'] = self.object
return kwargs
def form_valid(self, form):
form.vote()
choice = form.cleaned_data['choice']
messages.success(self.request,'"%s"に投票しました' % choice)
return super().form_valid(form)
def get_success_url(self):
return resolve_url('polls:results',self.kwargs['pk'])
detail = Detail.as_view()
I wanna show messages of
def form_valid(self, form):
form.vote()
choice = form.cleaned_data['choice']
messages.success(self.request,'"%s"に投票しました' % choice)
return super().form_valid(form)
How can I fix this?
My app directory is
urls.py in polls is
from django.conf.urls import url
from django.views.generic import TemplateView
from . import views
app_name="polls"
urlpatterns = [
url(r'(?P<pk>\d+)/$', views.detail, name='polls_detail'),
url(r'(?P<pk>\d+)/vote$', views.vote, name='poll_vote'),
url(r'(?P<pk>\d+)/results$', views.results, name='polls_results'),
url(r'^$',views.index,name='index'),
url(r'^form$', views.form_test),
]
I wanna call Detail class when results.html is loaded.
I have 2 html pages in my Django templates. I am trying to insert cats.html in index.html as a block, but nothing happens. No errors, no display. I already looked in django documentation and in the youtube. Just can't understand where is problem
index.html:
{% load static %}
<!DOCTYPE doctype html>
<html class="no-js" lang="en">
<head>
<meta charset="utf-8"/>
<meta content="width=device-width, initial-scale=1.0" name="viewport"/>
<link rel="stylesheet" type="text/css" href="{% static 'items/index-style.css' %}" />
<title>
my site
</title>
</head>
<body>
{% block cats %}
{% endblock cats %}
</body>
</html>
cats.html:
{% extends "index.html" %}
{% block cats %}
<div class="row column">
<p class="lead">
Категории товаров
</p>
</div>
<div class="row small-up-1 medium-up-2 large-up-3">
{% for category in categories %}
<div class="column">
<a href="/{{category.alias}}">
<div class="callout">
<p>
{{category.name}}
</p>
<p>
<img alt="image of a planet called Pegasi B" src="{{category.image}}"/>
</p>
<p class="lead">
<!-- Цена: {{tovar.price}} -->
</p>
<p class="subheader">
<!-- {{tovar.short_description}} -->
</p>
</div>
</a>
</div>
{% endfor %}
</div>
{% endblock cats %}
views.py:
from django.shortcuts import render
from django.http import HttpResponse, Http404
from django.template.loader import render_to_string
from items.models import *
# Create your views here.
def home(request):
try:
categories = Category.objects.all()
except:
raise Http404()
context = {
'categories':categories,
}
return render(request,"index.html",context)
You are confusing the block name with template name. You are not inserting cats.html into index.html as you expect, but you are extending index.html in your cats.html. You should use your child template (cats.html) in your view, ie change the last line to:
return render(request, 'cats.html', context)
actually the problem is you use index.html as a base template
and then inherit in your cats.html
so you have to render cat.html to get the desired result THIS IS HELPFUL FOR YOU
return render(request, 'cats.html', context)
thanks :)
This is what I have at the moment in my models.py
class Document(models.Model):
docfile = models.FileField(upload_to='documents/%Y/%m/%d')
img = models.ImageField(upload_to='documents/%Y/%m/%d', null=True, blank=True)
admin.py#
from django.contrib import admin
from imagine.models import Document
admin.site.register(Document)
views.py#
from django.shortcuts import render_to_response
from django.template import RequestContext
from django.core.urlresolvers import reverse
from imagine.models import Document
from forms import DocumentForm
def list(request):
# Handle file upload
if request.method == 'POST':
form = DocumentForm(request.POST, request.FILES)
if form.is_valid():
newdoc = Document(docfile = request.FILES['docfile'])
newdoc.save()
# Redirect to the document list after POST
return HttpResponseRedirect(reverse('facetut.views.list'))
else:
form = DocumentForm() # A empty, unbound form
# Load documents for the list page
documents = Document.objects.all()
# Render list page with the documents and the form
return render_to_response(
'list.html',
{'documents': documents, 'form': form},
context_instance=RequestContext(request))
list.html#
{% extends "base.html" %}
{% load staticfiles %}
{% block content %}
<head>
<!-- Theme Made By www.w3schools.com - No Copyright -->
<title>facemail</title>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<link rel="stylesheet" href="http://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/css/bootstrap.min.css">
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.12.0/jquery.min.js"></script>
<script src="http://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/js/bootstrap.min.js"></script>
<style>
.jumbotron {
background-color: #f4511e;
color: #fff;
}
</style>
</head>
<body>
<div class="jumbotron text-center">
<h1>FaceMail</h1>
<p>who knew Email could be fun aGain</p>
</div>
{% endblock %}
{% block content2 %}
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>Minimal Django File Upload Example</title>
</head>
<body>
<h2>Current Posts</h2>
<!-- List of uploaded documents -->
{% if documents %}
<ul>
{% for document in documents %}
<li>{{ document.docfile.name }}</li>
<img src="{{ document.img.url }}">
{% endfor %}
</ul>
{% else %}
<p>No documents.</p>
{% endif %}
<br>
<br>
<!-- Upload form. Note enctype attribute! -->
<form action="{% url "list" %}" method="post" enctype="multipart/form-data">
{% csrf_token %}
<p>{{ form.non_field_errors }}</p>
<p>{{ form.docfile.label_tag }} {{ form.docfile.help_text }}</p>
<p>
{{ form.docfile.errors }}
{{ form.docfile }}
</p>
<p><input type="submit" value="Upload" /></p>
</form>
</body>
</html>
{% endblock %}
any feedback would be great when i do it it just shows me a link with no picture?
I want it to be like a post or blog but with a imagefield were there could be a story and then a picture as well but the imagefield with django can be a pain in the butt if you ask me so simple but so hard please help me