I don t understand why I have this error as my code seems ok?
my form:
class NewListingForm(forms.Form):
title = forms.CharField(label="Listing title", widget=forms.TextInput(attrs={'class' : 'form-control col-md-8 col-lg-8'}))
description = forms.CharField(label='Description', widget=forms.Textarea(attrs={'class' : 'form-control col-md-8 col-lg-8', 'rows' : 10}))
enddate = forms.DateTimeField(
label='Date ending auction',
input_formats=['%d/%m/%Y %H:%M'],
)
category = forms.ChoiceField(widget=forms.Select(choices=categories_list))
initialBid = forms.DecimalField(label='Inital bid amount', max_digits=12, decimal_places=2)
photo = forms.ImageField(label='Image')
active = forms.BooleanField(label='Is this auction is active?')
edit = forms.BooleanField(initial=False, widget=forms.HiddenInput(), required=False)
class Meta:
model = Listing
my views:
from .models import User, Listing, Bid, Wishing, Comment, Category
from .forms import NewListingForm
#login_required
def newlisting(request):
form = NewListingForm()
if request.method == "POST":
form = NewListingForm(request.POST)
if form.is_valid():
if form.cleaned_data["edit"] is True:
form = form.save(commit=False)
form.save()
messages.success(request,
'listing saved') # message for inform user of success - See messages in html file
return HttpResponseRedirect(reverse("index", kwargs={'title': "list"}))
else:
return render(request, "auctions/newListing.html", {
"form": form,
"existing": True,
'title': "New Listing",
})
else:
return render(request, "auctions/newListing.html", {
"form": form,
"existing": False,
'title': "New Listing",
})
else:
return render(request, "auctions/newListing.html", {
"form": form,
"existing": False,
'title': "New Listing",
})
my template newListing.html:
{% extends "auctions/layout.html" %}
{% block body %}
<h2>{% if not listing_id %}Create Client {% else %} Edit {{ object.name }}{% endif %}</h2>
<form id="create-edit-client" action="" method="post" accept-charset="utf-8">
{% csrf_token %}
{% form %}
<div class="form-actions">
<input type = submit type="submit" value="Save" name="submit">
</div>>
</form>
{% endblock %}
my layout.html:
{% load static %}
<!DOCTYPE html>
<html lang="en">
<head>
<title>{% block title %}Auctions{% endblock %}</title>
<link href="{% static 'auctions/styles.css' %}" rel="stylesheet">
</head>
<body>
<h1>Auctions</h1>
<div>
{% if user.is_authenticated %}
Signed in as <strong>{{ user.username }}</strong>.
{% else %}
Not signed in.
{% endif %}
</div>
<ul class="nav">
<li class="nav-item">
<a class="nav-link" href="{% url 'index' %}">Active Listings</a>
</li>
{% if user.is_authenticated %}
<li class="nav-item">
<a class="nav-link" href="{% url 'logout' %}">Log Out</a>
</li>
{% else %}
<li class="nav-item">
<a class="nav-link" href="{% url 'login' %}">Log In</a>
</li>
<li class="nav-item">
<a class="nav-link" href="{% url 'register' %}">Register</a>
</li>
{% endif %}
</ul>
<hr>
{% block body %}
<h2>{{title}}</h2>
{% if message %}
<div>{{ message }}</div>
{% endif %}
{% endblock %}
</body>
</html>
I try to add {% load form %} but same type of error saying:
django.template.exceptions.TemplateSyntaxError: 'form' is not a registered tag library. Must be one of:
admin_list
admin_modify
admin_urls
thanks for help.
I just change {% form %} to {{ form }} seems working
I am trying to create a popup form for a New Task in my calendar, but I have never get it to work. I am using Ajax for this purpose. Here is my code. The Ajax is located in the static folder under the name "plugin.js"
base.py
{% load static %}
<!DOCTYPE html>
<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">
<title>Bookstore</title>
<link href="{% static 'css/bootstrap.min.css' %}" rel="stylesheet">
</head>
<body>
<div class="container">
{% block content %}
{% endblock %}
</div>
<script src="{% static 'js/jquery-3.1.1.min.js' %}"></script>
<script src="{% static 'js/bootstrap.min.js' %}"></script>
<script src="{% static 'js/plugin.js' %}"></script>
{% block javascript %}
{% endblock %}
</body>
</html>
calendar.html
{% extends 'cal/base.html' %}
{% block title %}
Quality Assurance Calendar
{% endblock %}
{% block content %}
<div class="clearfix">
<a class="btn btn-info left" href="{% url 'cal:calendar' %}?{{ prev_month }}"> Previous Month </a>
<a class="btn btn-info right" href="{% url 'cal:calendar' %}?{{ next_month }}"> Next Month </a>
{% if user.is_authenticated %}
<button type="button" class="btn btn-primary show-form">
<span class="glyphicon glyphicon-plus"></span>
New Task
</button>
{% endif %}
</div>
{{ calendar }}
<div class="modal-fad" id="modal-task">
<div class="modal-dialog">
<div class="modal-content"></div>
</div>
</div>
{% endblock %}
part of the view.py
def task_create(request, task_id=None):
# if not request.user.is_authenticated:
# return redirect('%s?next=%s' % ('account/login/', request.path))
instance = Task()
if task_id:
instance = get_object_or_404(Task, pk=task_id)
else:
instance = Task()
form = TaskForm(request.POST or None, instance=instance)
# form.user = request.user
if request.POST and form.is_valid():
# form = form.save(commit=False)
# form.user = request.user
form.save()
# return HttpResponseRedirect(reverse('cal:calendar'))
# return render(request, 'cal/task_create.html', {'form': form})
html_form=render_to_string('cal/task_create.html', {'form': form}, request=request)
return JsonResponse({'html_form':html_form})
And the plugin.js
$(document).ready(function(){
$('.show-form').click(function(){
$.ajax({
url: '/task/create',
type: 'get',
dataType:'json',
beforeSend: function(){
$('#modal-task').modal('show');
},
success: function(data){
$('#modal-task .modal-content').html(data.html_form);
}
})
})
task_create.html
{% load crispy_forms_tags %}
<button class="btn btn-primary show-form" data-url="{% url 'cal:task_create' %}"></button>
{% csrf_token %}
<!-- Modal Header -->
<div class="modal-header">
<h5 class="modal-title">Create Task</h5>
<button type="button" class="close" data-dismiss="modal" aria-lable ="Close">
<span aria-hidden="True">×</span>
</button>
</div>
{{ form|crispy}}
<div class="modal-body">
Modal body..
</div>
<!-- Modal footer -->
<div class="modal-footer">
<button type="button" class="btn btn-danger" data-dismiss="modal">Close</button>
<button type="button" class="btn btn-primary" >Save changes</button>
</div>
</form>
The new task button has never responded!!!
'''''''''''''''''''''''''''''''''''''''''''''''
sorted out.
I have got all what i need in this tutorial
Here is the link (https://simpleisbetterthancomplex.com/tutorial/2016/08/29/how-to-work-with-ajax-request-with-django.html)
thanks to all for the valuable comments.
i am using CodeIgniter with Twig, i wonder how can i load only the content block
without refreshing the page. I've seen this topic has been discussed but with Sympony Framework which i'm not familiar with.
I want to load only the Block Content area without refresh, I've tried to load the controller with Ajax but it keeps loading the whole page - including the header, footer etc.
Thanks.
Here is the base file - base.twig :
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<title>{{ site_title }} | CRM</title>
{% include 'templates/css.twig' %}
</head>
<body class="skin-blue sidebar-mini" style="height: auto;">
<div class="wrapper">
{% include 'templates/header.twig' %}
{% include 'templates/side_bar.twig' %}
<div class="content-wrapper">
<!-- Main content -->
<section class="content">
<div id="{{ site_title }}">
{% block content %}
{% endblock %}
</div>
</section>
</div>
{% include 'notifications_modal.twig' %}
</div>
{% include 'templates/footer.twig' %}
</body>
</html>
Here is the controller - about.twig
class About extends MY_Controller {
public function __construct()
{
parent::__construct();
}
public function index()
{
$this->data['site_title'] = 'about';
$this->twig->display('about',$this->data);
}
}
And here is the view - about.twig
{% extends "base.twig" %}
{% block content %}
<div class="row">
<div class="col-md-12">
<h1>TO DO {{ site_title }}</h1>
</div>
</div>
{% endblock %}
I'm using django 1.9 and python 3. My english also isn't the best, so excuse the question if it is formulated bad.
I'm working on making my website a single-page application. I need to get the {% block %} contents of a given template, and then send that as a HttpResponse so that ajax can pick it up and inject it into the page.
I've tried using the answer from this question: Django - how to get the contents of a {% block %} tag from a template
But upon trying to fetch the contents of a block in my view like so:
response_data[content] = get_block_source('profile/login.html', 'content')
if request.is_ajax():
return HttpResponse(
json.dumps(response_data),
content_type="application/json"
)
I just get this error from django, no matter what I do:
ValueError at /login/ Template block content not found
The contents of the block don't even make it to the ajax call, what gives?
EDIT:
I'll include my "content" block here:
in my template:
{% extends 'base.html' %}
{% block content %}
<div class="big-title text">Log in</div>
<div class="form-container">
<form name="login-form" id="user" method="post" action="/login/" enctype="multipart/form-data" class="text">
{% csrf_token %}
<div class="title">Enter your credentials</div>
<div class="form-row">
<div class="form-flex">
<div class="field-container">
<div class="field-input-container">
<div class="field-label accent">Username</div>
<div class="field-input">
<input class="field-input-element" type="text" name="username" />
</div>
</div>
<div class="field-help">Your username is always lowercase.</div>
</div>
</div>
<div class="form-flex">
<div class="field-container" style="height: 110px">
<div class="field-input-container">
<div class="field-label accent">Password</div>
<div class="field-input">
<input class="field-input-element" type="password" name="password" />
</div>
</div>
<div class="field-help"></div>
</div>
</div>
</div>
<div class="form-button-container">
<div class="form-error"></div>
<div class="form-message"></div>
<input type="submit" name="submit" value="Accept" class="button form-button"/>
</div>
</form>
</div>
{% endblock %}
In my base (base.html)
<body>
<div id="modal-container">
<div id="modal-overlay">
<div id="modal-items">
</div>
</div>
</div>
<div id="wrapper">
<header>
<div id="header-title" class="text accent">App name</div>
<div id="header-nav">
<nav>
{% if user.is_authenticated %}
Home
Feed {% if request.user.is_superuser %}
Admin {% endif %}
N
<a href="/{{ request.user }}" class="header-avatar-small-a">
<div class="text header-greeting">Hi, {{ user.userprofile.display_name }}</div>
<div class="header-avatar-small">
{% if not user.userprofile.avatar == '' %}
<img src="{{ MEDIA_URL }}users/{{ user }}/avatar" alt=""> {% else %}
<img src="{{ MEDIA_URL }}users/avatar" alt=""> {% endif %}
</div>
</a>
{% else %}
Log in
Create account {% endif %}
</nav>
</div>
<div class="progress">
<div id="header-progress" class="fill"></div>
</div>
</header>
<main>
{% block content %} {% endblock %}
</main>
<footer></footer>
</div>
</body>
</html>
Template source is the template actual HTML, not the file reference
This question already has an answer here:
Django template/view issues with carousel
(1 answer)
Closed 7 years ago.
OK, so here's the deal:
This is currently what I'm working on:
See the two arrows at the top? That's where a carousel of pictures should be. However, there are no pictures in this carousel. That is, until I click the 'Upload' Button.
So, my goal is to make the pictures appear on the first page before I even click the 'upload' button.
How can I fix this problem? I'm kind of a noob at Django, and writing this code is like pulling teeth.
My code:
Index.html
{% extends 'webportal/defaults.html' %}
{% block body %}
{% include 'webportal/carousel.html' %}
<br/>
<div class="container">
<div class="row">
<div class="col-md-12">
<p> So far we have been able to establish what the user tables will be have created or are in process of
creating
the ability to create, update, destroy users.</p>
</div>
</div>
<div class="row">
<div class="col-md-12">
<p> For now this ability is limited to the main user table, however the models will be easily extended
to other
tables as they are needed</p>
</div>
</div>
<div class="row">
<div class="col-md-12">
<p> Also not a lot of thought has gone into styling yet, we know that the page is suppose to resemble
the parent
organizations page. Right now we have been more focused on getting each individual component
working. Later we
will merge them into a whole. </p>
</div>
</div>
</div>
{% include 'webportal/info_row.html' with one=one two=two three=three %}
{% endblock %}
Carousel.html:
{% load staticfiles %}
{% load filename %}
<div class="container">
<div class="row">
<div class="col-md-12">
<div id="myCarousel" class="carousel slide" data-ride="carousel">
<div class="carousel-inner" role="listbox">
{% for document in documents %}
<div class="item {% if forloop.first %} active {% endif %}">
<div class="row">
<div class="col">
<li>{{document.docfile.name}}</li>
<img src = "{{STATIC_URL}}img/{{document|filename}}" >
<p align="center"><form style="text-align:center" action="{% url 'webportal:delete' %}" method="post" enctype="multipart/form-data">
{% csrf_token %}
<p>{{ form.non_field_errors }}</p>
<p>{{ form.Document.label_tag }} {{ form.Document.help_text }}</p>
<p>
{{ form.Document.errors }}
{{ form.Document.docfile }}
</p>
<p><input type="submit" value="Delete" /></p>
</form></p>
</div>
</div>
</div>
{% endfor %}
</div>
<a class="left carousel-control" href="#myCarousel" role="button" data-slide="prev">
<span class="glyphicon glyphicon-chevron-left"></span>
<span class="sr-only">Previous</span>
</a>
<a class="right carousel-control" href="#myCarousel" role="button" data-slide="next">
<span class="glyphicon glyphicon-chevron-right"></span>
<span class="sr-only">Next</span>
</a>
</div>
<!-- /.carousel -->
</div>
</div>
<form action="{% url 'webportal:carousel' %}" 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>
</div>
Views.py:
from django.shortcuts import render
from django.shortcuts import render, redirect, get_object_or_404
from django.contrib.auth import authenticate, login
from webportal.views.authentication import LoginForm
from django.shortcuts import render_to_response
from django.template import RequestContext
from django.http import HttpResponseRedirect
from django.http import HttpResponse
from django.core.urlresolvers import reverse
from django.conf import settings
from webportal.forms.forms import DocumentForm
from webportal.models import Document, DeleteForm
is_server = True
def delete(request, my_id):
Deleted=get_object_or_404(Document, docfile=my_id)
if request.method=='POST':
form=DeleteForm(request.POST, instance=Deleted)
if form.is_valid():
Deleted.delete()
return HttpResponseRedirect('http://127.0.0.1:8000/alzheimers/')
else:
form=DeleteForm(instance=Deleted)
return render_to_response(
'webportal/index.html',
{'documents': documents, 'form': form,},
context_instance=RequestContext(request)
)
# Redirect to the document list after POST
def carousel(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('http://127.0.0.1:8000/alzheimers/')
else:
form = DocumentForm() # A empty, unbound form
# Load documents for the list page
documents = Document.objects.all()
#documents=DocumentForm().
# Render list page with the documents and the form
return render_to_response(
'webportal/index.html',
{'documents': documents, 'form': form,},
context_instance=RequestContext(request)
)
Models.py:
class Document(models.Model):
docfile = models.ImageField(upload_to='webportal/static/img/')
class DeleteForm(ModelForm):
class Meta:
model=Document
fields=[]
Forms.py:
class DocumentForm(forms.Form):
docfile = forms.ImageField(label='Select a file', help_text='max. 42 megabytes')
URls.py:
from django.conf.urls import patterns, url
from webportal.views import views, register, authentication, welcome, search, profile, event, csv_export, role_creation, \
edit_event, reports, accounts
urlpatterns = patterns('',
url(r'^reports', reports.report_page),
url(r'^search/criteria', search.get_criteria),
url(r'^search', search.search_page),
url(r'^register', register.SignUpView.as_view(), name="register"),
url(r'^login', authentication.login_view, name="login"),
url(r'^carousel', views.carousel, name="carousel"),
url(r'^delete', views.delete, name="delete"),
url(r'^profile', profile.ProfileView.as_view(), name="profile"),
url(r'^welcome', welcome.WelcomeView.as_view(), name="welcome"),
url(r'^event/creation', event.Creation.as_view(), name="event_creation"),
# url(r'^role_creation', role_creation.Creation.as_view(), name="role_creation"),
url(r'^csv_export', csv_export.CSVExport.as_view(), name="csv_export"),
url(r'^csv_import', reports.upload_file, name="csv_import"),
url(r'^logout$', 'django.contrib.auth.views.logout', {'next_page': '/alzheimers/'}),
url(r'^edit_event', edit_event.EditView.as_view(), name='edit_event'),
url(r'^parse_ajax', profile.parse_ajax),
url(r'^event/role_ajax', role_creation.ajax),
url(r'^event/all', event.view_all),
url(r'^event/information', event.ajax),
url(r'^accounts/personal', accounts.personal),
url(r'^accounts/create', accounts.create),
url(r'^accounts/edit', accounts.edit),
url(r'^accounts/remove', accounts.remove),
url(r'^$', views.bootstrap),
)
If there is a way to do this, does it involve ajax? I asked this again because of a lack of an adequate answer.
You should pass the documents context variable to the template in the view which handles the /alzheimers/ page.
UPDATE: The view you should change is the views.boostrap(). So rendering of the template will be something like this:
def bootstrap(request):
...
return render_to_response('webportal/bootstrap.html',
{'documents': Document.objects.all()},
context_instance=RequestContext(request)
)