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.
Related
I am new to Django and am trying to make an online journal, and the server runs fine, but when I press the create button, it does not redirect to the form even though a POST request is being sent. screenshot of the create page. I'm not sure why.
This is the code:
views.py:
from django.shortcuts import render, redirect, get_object_or_404
from ejournal.models import Journal
from ejournal.forms import JournalForm
def make_entry(request):
if request.method == "POST":
entry = JournalForm(request.POST, request.FILES)
if entry.is_valid():
entry.save()
return redirect('list_journals')
else:
entry = JournalForm()
context = {
'entry':entry
}
return render(request, 'ejournal/create.html', context)
def delete_entry(request, id):
entry = get_object_or_404(Journal, id=id)
if request.method == "POST":
entry.delete()
return redirect('list_journals')
context = {
'object':object
}
return render(request, 'journal/delete.html',context)
def list_journals(request):
entries = Journal.objects.all()
context = {
'entries': entries
}
return render(request, 'ejournal/list_journals.html',context)
def journal_detail(request, id):
journal = Journal.objects.get(id=id)
context = {
'journal':journal
}
return render(request, 'journal/journal_detail.html', context)
forms.py
from ejournal.models import Journal
from django.forms import ModelForm
class JournalForm(ModelForm):
class Meta:
model = Journal
fields = ['name','title','text','image']
models.py
from django.db import models
class Journal(models.Model):
name = models.CharField(max_length=20)
title = models.CharField(max_length=50)
text = models.TextField(max_length=1000)
date = models.DateField(auto_now_add=True)
image = models.FileField(upload_to='')
archived = models.BooleanField(default=False)
def __str__(self):
return self.name
base.html
{% load static %}<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no">
<title>My Online Journal</title>
<!-- Bootstrap core CSS -->
<link href="{% static 'css/bootstrap.min.css' %}" rel="stylesheet">
<link href="{% static 'css/style.css' %}" rel="stylesheet">
</head>
<body>
<!-- Navigation -->
<nav class="navbar navbar-expand-lg navbar-dark bg-dark">
<div class="container">
<a class="navbar-brand" href="{% url 'list_journals' %}">Smart Journal</a>
<button class="navbar-toggler" type="button" data-toggle="collapse" data-target="#navbarResponsive" aria-controls="navbarResponsive" aria-expanded="false" aria-label="Toggle navigation">
<span class="navbar-toggler-icon"></span>
</button>
<div class="collapse navbar-collapse" id="navbarResponsive">
<ul class="navbar-nav ml-auto">
<li class="nav-item">
<a class="btn btn-outline-info btn-md" href="{% url 'list_journals' %}">LIST ALL</a>
</li>
</ul>
</div>
<div class="collapse navbar-collapse" id="navbarResponsive">
<ul class="navbar-nav ml-auto">
<li class="nav-item">
<a class="btn btn-outline-info btn-md" href="{% url 'make_entry' %}">+ New Journal Entry </a>
</li>
</ul>
</div>
</div>
</nav>
<!-- Page Content -->
<div class="container" id="app">
{% block content %}
{% endblock %}
</div>
<!-- /.container -->
<!-- Bootstrap core JavaScript -->
<script src="{% static 'js/jquery.min.js' %}"></script>
<script src="{% static 'js/bootstrap.min.js' %}"></script>
</body>
</html>
create.html
{% extends 'ejournal/base.html' %}
{% block content %}
<div class="center_journal">
<h1> Create Journal Entry </h1>
</div>
<div class="center_journal">
<form method="POST" enctype="multipart/form-data">
{% csrf_token %}
<p>{{ form.as_p }}</p>
<button class="btn btn-primary" type="submit">CREATE</button>
</form>
</div>
{% endblock content %}
urls.py
from django.urls import path
from ejournal.views import make_entry, delete_entry, list_journals, journal_detail
urlpatterns = [
path('create', make_entry, name="make_entry"),
path('list_journals', list_journals, name="list_journals"),
path('delete/<int:id>/', delete_entry, name="delete_entry"),
path('journal_detail/<int:id>',journal_detail, name="journal_detail"),
]
You pass the form as the variable entry to your template ejournal/create.html.
Inside this template you use {{ form.as_p }}, but form is undefined. You need to use the variable entry because thats where the form is assigned to.
So your create.html becomes this:
{% extends 'ejournal/base.html' %}
{% block content %}
<div class="center_journal">
<h1> Create Journal Entry </h1>
</div>
<div class="center_journal">
<form method="POST" enctype="multipart/form-data">
{% csrf_token %}
<p>{{ entry.as_p }}</p>
<button class="btn btn-primary" type="submit">CREATE</button>
</form>
</div>
{% endblock content %}
You're checking if your form is valid by using entry.is_valid(), but your form will always be invalid because you didn't pass the correct form in your template, as described above.
Check with form's action='' attribute like this...
<form method="POST" action="{% url 'make_entry' %}" enctype="multipart/form-data">
{% csrf_token %}
<p>{{ form.as_p }}</p>
<button class="btn btn-primary" type="submit">CREATE</button>
</form>
I create program stock management system by using Django. Page of Update_items that create for saving and updating. Program can running but when I will update new data it can't save and update data. It will redirect with same data. I'm not sure whatit's wrong. I am very new so please introduce me.
This is from views.py
from email import header
from multiprocessing import context
from urllib import request
from django.shortcuts import render,redirect
import stockmgmt
from .models import Stock
from .forms import StocksearchForm,StockCreateForm,StockUpdateForm
def home(request):
title = 'ยินดีต้อนรับเข้าสู่ระบบสต็อคสินค้าเซียงกง'
form = 'Welcome: This is the Home Page'
context = {
"title": title,
"test": form,
}
return render(request, "home.html",context)
def list_items(request):
title = 'รายการสินค้า'
form = StocksearchForm(request.POST or None)
queryset = Stock.objects.all()
context = {
"title": title,
"queryset": queryset,
"form":form
}
if request.method == 'POST':
queryset = Stock.objects.filter(category__icontains=form['category'].value(),item_name__icontains=form['item_name'].value(),id_product__icontains=form['id_product'].value(),shop_name__icontains=form['shop_name'].value())
context ={
"form":form,
"header": header,
"queryset": queryset,
}
return render(request, "list_items.html",context)
def add_items(request):
form=StockCreateForm(request.POST or None)
if form.is_valid():
form.save()
return redirect('/list_items')
context={
"form":form,
"title":"Add Item",
}
return render(request,"add_items.html",context)
def update_items(request, pk):
queryset = Stock.objects.get(id=pk)
form = StockUpdateForm(instance=queryset)
if request.method == ' POST':
form = StockUpdateForm (request.POST, instance=queryset)
if form.is_valid():
form.save()
return redirect('/list_items')
context = {
'form':form
}
return render(request, 'add_items.html', context)
This is list_items.html
{% load static %}
{% load crispy_forms_tags %}
<!DOCTYPE html>
<body>
</body>
</html>
<!doctype html>
<html lang="en">
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no">
<meta name="description" content="">
<meta name="author" content="">
<link rel="icon" href="/docs/4.0/assets/img/favicons/favicon.ico">
<title>รายการสินค้า</title>
<link rel="canonical" href="https://getbootstrap.com/docs/4.0/examples/navbar-top-fixed/">
<!-- Bootstrap core CSS -->
<link href ="../../dist/css/bootstrap.min.css" rel ="stylesheet">
<link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.1.3/css/bootstrap.min.css" integrity="sha384-MCw98/SFnGE8fJT3GXwEOngsV7Zt27NXFoaoApmYm81iuXoPkFOJwJ8ERdknLPMO" crossorigin="anonymous">
<!-- Custom styles for this template -->
<link href="navbar-top-fixed.css" rel="stylesheet">
</head>
<body>
<nav class="navbar navbar-expand-md navbar-dark fixed-top bg-dark">
<a class="navbar-brand" href="#">สต็อคสินค้าร้านเซียงกง</a>
<button class="navbar-toggler" type="button" data-toggle="collapse" data-target="#navbarCollapse" aria-controls="navbarCollapse" aria-expanded="false" aria-label="Toggle navigation">
<span class="navbar-toggler-icon"></span>
</button>
<div class="collapse navbar-collapse" id="navbarCollapse">
<ul class="navbar-nav mr-auto">
<li class="nav-item active">
<a class="nav-link" href="/">หน้าแรก <span class="sr-only">(current)</span></a>
</li>
<li class="nav-item">
<a class="nav-link" href="/list_items">รายการสินค้า</a>
</li>
<li class="nav-item">
<a class="nav-link" href="/add_items">เพิ่มรายการสินค้า</a>
</li>
</ul>
<form class="form-inline mt-2 mt-md-0">
<input class="form-control mr-sm-2" type="text" placeholder="Search" aria-label="Search">
<button class="btn btn-outline-success my-2 my-sm-0" type="submit">Search</button>
</form>
</div>
</nav>
<main role="main" class="container">
<div class="jumbotron">
<h1>รายการสินค้า</h1>
<form method='POST' action=''>{% csrf_token %}
{{form|crispy}}
<input type="submit" value='Search'/>
</form>
<br>
<table class='table'>
<thead>
<tr>
<th>รายการสินค้า</th>
<th>ประเภทสินค้า</th>
<th>ชื่อสินค้า</th>
<th>รหัสสินค้า</th>
<th>ชื่อร้าน</th>
<th>ราคา/หน่วย</th>
<th>จำนวนที่มีอยู่ในร้าน</th>
</tr>
</thead>
{% for instance in queryset %}
<tr>
<td>{{forloop.counter}}</td>
<td>{{instance.category}}</td>
<td>{{instance.item_name}}</td>
<td>{{instance.id_product}}</td>
<td>{{instance.shop_name}}</td>
<td>{{instance.price}}</td>
<td>{{instance.quantity}}</td>
</tr>
{% endfor %}
</table>
</div>
</main>
<!-- Bootstrap core JavaScript
================================================== -->
<!-- Placed at the end of the document so the pages load faster -->
<script src="https://code.jquery.com/jquery-3.3.1.slim.min.js" integrity="sha384-q8i/X+965DzO0rT7abK41JStQIAqVgRVzpbzo5smXKp4YfRvH+8abtTE1Pi6jizo" crossorigin="anonymous"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.14.3/umd/popper.min.js" integrity="sha384-ZMP7rVo3mIykV+2+9J3UJ46jBk0WLaUAdn689aCwoqbBJiSnjAK/l8WvCWPIPm49" crossorigin="anonymous"></script>
<script src="https://stackpath.bootstrapcdn.com/bootstrap/4.1.3/js/bootstrap.min.js" integrity="sha384-ChfqqxuZUCnJSK3+MXmPNIyE6ZbWh2IMqE241rYiqJxyMiZ6OW/JmZQ5stwEULTy" crossorigin="anonymous"></script>
</body>
</html>
This is url.py
"""djangoproject URL Configuration
The `urlpatterns` list routes URLs to views. For more information please see:
https://docs.djangoproject.com/en/4.0/topics/http/urls/
Examples:
Function views
1. Add an import: from my_app import views
2. Add a URL to urlpatterns: path('', views.home, name='home')
Class-based views
1. Add an import: from other_app.views import Home
2. Add a URL to urlpatterns: path('', Home.as_view(), name='home')
Including another URLconf
1. Import the include() function: from django.urls import include, path
2. Add a URL to urlpatterns: path('blog/', include('blog.urls'))
"""
from django.contrib import admin
from django.urls import path
from stockmgmt import views
urlpatterns = [
path('', views.home, name='home'),
path('list_items/', views.list_items, name='list_items'),
path('add_items/', views.add_items, name='add_items'),
path('update_items/<str:pk>/', views.update_items, name="update_items"),
path('admin/', admin.site.urls)
]
This is my error in command promopt
In forms.py
from django import forms
from .models import Stock
# Create your forms here
class StockForm(forms.Form):
class Meta:
model = Stock
# incase you want all fields
fields = '__all__'
In views.py
from .forms import StockForm
from .models import Stock
from django.http import HttpResponseRedirect
from django.shortcuts import render
from django.urls import reverse
from django.contrib import messages
def update_entry(request, pk):
try:
queryset = Stock.objects.get(id=pk)
except Stock.DoesNotExist:
messages.error(request, "The request entry does not exist.")
# Redirect back some page incase of invalid pk
return HttpResponseRedirect(reverse("app2:listing"))
# Populate the form with old data
form = StockForm(instance=qs)
context = {"form": form}
# When method is post
if request.method == "POST":
# Populate the form with newly posted data
form = StockForm(request.POST, instance=qs)
# Checking data validity in form
if form.is_valid():
form.save()
# Always use HttpResponseRedirect after successfull post request
return HttpResponseRedirect(reverse("some-url-name"))
# When form is not valid re-render page
else:
messages.error(request, "Invalid form received.")
# Update form in context dictionary
context["form"] = form
return render(request, "update-stock.html", context)
# When method is not post
else:
return render(request, "update-stock.html", context)
In update-stock.html
<div class="container-fluid">
<!-- Loop over messages rendered from views -->
{% for message in messages %}
<div class="alert alert-warning alert-dismissible fade show" role="alert">
<strong>{{ message }}</strong>
<button type="button" class="btn-close" data-bs-dismiss="alert" aria-label="Close"></button>
</div>
{% endfor %}
<form method="post" action="" class="row g-1">
{% csrf_token %}
{{ form }}
<input type="submit" class="btn btn-primary">
</form>
</div>
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!
I am trying to create a simple to-do list app using Django. But face this error will running the server ValueError: Field 'id' expected a number but got 'index.html'.
models.py
from django.db import models
class List(models.Model):
item = models.CharField(max_length=200)
completed = models.BooleanField(default=False)
def __str__(self):
return self.item + '|' + str(self.completed)
urls.py
from . import views
urlpatterns = [
path("index",views.index, name="home"),
path("delete/<list_id>/", views.delete , name="delete"),
]
views.py
from django.http import HttpResponse
from django.shortcuts import render, redirect
from .models import List
from .forms import ListForm
from django.contrib import messages
# Create your views here.
def index(request):
if request.method == 'POST':
form = ListForm(request.POST or None)
if form.is_valid():
form.save()
all_items = List.objects.all
messages.success(request,('Items has been Added to List !!'))
return render(request,'home.html', {'all_items': all_items})
else:
all_items = List.objects.all
return render(request,'index.html',{'all_items': all_items})
def delete(request, list_id):
item = List.objects.get(pk=list_id)
item.delete()
messages.success(request,('Item has been deleted'))
return redirect('index')
index.html
{% extends 'home.html' %}
{% block content %}
{% if messages %}
{% for message in messages %}
<div class="alert alert-warning alert-dismissable" role="alert">
<button class="close" data-dismiss="alert">
<small><sup>x</sup></small>
</button>
{{ message }}
</div>
{% endfor %}
{% endif %}
{% if all_items %}
<table class="table table-bordered">
{% for things in all_items %}
<tr>
<td>{{ things.item }}</td>
<td><center>{{ things.completed }}</center></td>
<td><center>Delete</center></td>
</tr>
{% endfor %}
</table>
{% endif %}
{% endblock content %}
home.html
<!doctype html>
<html lang="en">
<head>
<!-- Required meta tags -->
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no">
<!-- Bootstrap CSS -->
<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">
<title>Home</title>
</head>
<body>
<nav class="navbar navbar-expand-lg navbar-dark bg-dark">
<a class="navbar-brand" href="{% url 'home' %}">To-Do Lists</a>
<button class="navbar-toggler" type="button" data-toggle="collapse" data-target="#navbarSupportedContent" aria-controls="navbarSupportedContent" aria-expanded="false" aria-label="Toggle navigation">
<span class="navbar-toggler-icon"></span>
</button>
<div class="collapse navbar-collapse" id="navbarSupportedContent">
<ul class="navbar-nav mr-auto">
</ul>
<form class="form-inline my-2 my-lg-0" method="POST">
{% csrf_token %}
<input class="form-control mr-sm-2" type="search" placeholder="Add Items" aria-label="Search" name="item">
<button class="btn btn-outline-secondary my-2 my-sm-0" type="submit">Add To List</button>
</form>
</div>
</nav>
<br/>
<div class="container">
{% block content %}
{% endblock content %}
</div>
<!-- Optional JavaScript -->
<!-- jQuery first, then Popper.js, then Bootstrap JS -->
<script src="https://code.jquery.com/jquery-3.3.1.slim.min.js" integrity="sha384-q8i/X+965DzO0rT7abK41JStQIAqVgRVzpbzo5smXKp4YfRvH+8abtTE1Pi6jizo" crossorigin="anonymous"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.14.7/umd/popper.min.js" integrity="sha384-UO2eT0CpHqdSJQ6hJty5KVphtPhzWj9WO1clHTMGa3JDZwrnQq4sF86dIHNDz0W1" crossorigin="anonymous"></script>
<script src="https://stackpath.bootstrapcdn.com/bootstrap/4.3.1/js/bootstrap.min.js" integrity="sha384-JjSmVgyd0p3pXB1rRibZUAYoIIy6OrQ6VrjIEaFf/nJGzIxFDsf4x0xIM+B07jRM" crossorigin="anonymous"></script>
</body>
</html>
migration file 0001_intial.py
# Generated by Django 3.1.1 on 2020-09-27 05:07
from django.db import migrations, models
class Migration(migrations.Migration):
initial = True
dependencies = [
]
operations = [
migrations.CreateModel(
name='List',
fields=[
('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')),
('item', models.CharField(max_length=200)),
('completed', models.BooleanField(default=False)),
],
),
]
here is my note app page
Error that I getting
can anybody tell me where I made the mistake?
thanks in advance
Try replacing "{% url 'delete' things.id %}" with "{% url '<appname>:delete' things.id %}" the appname should be replaced by your app name. The same format works for me in Django 2.x.
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