form object does not load in a template - django-forms

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

Related

Why Symfony Controller return template snipped with <html> and <body> tags?

I have a controller-action:
/**
* Get the template for the notifications in the user-navbar
*
* #Route("/notification/get-template", name="get_notifications_template")
* #param Request $request
* #return Response
*/
public function getNotificationsTemplateAction(Request $request)
{
if (!$request->isXmlHttpRequest()) {
return $this->redirect($this->generateUrl('homepage'));
}
return $this->render('Menu/_notifications_block.html.twig');
}
I want to do an AJAX call with to get this template:
refreshNotifications() {
$.ajax({
url: this.$wrapper.data('refresh-action-path'),
method: 'POST',
}).then(function (data) {
// remove old notifications
this.$wrapper.remove();
// append data to the container
$('#user-notifications-container').append(data);
console.log(data);
}.bind(this))
}
The problem is now - that the Symfony container sends a whole html page:
the template is that:
{% if app.user is not null and is_granted('ROLE_USER') %}
{% if app.user|notifications|length != 0 %}
{% set notifications = app.user|notifications %}
{% set all_notification_count = notifications|length %}
<li class="nav-item mx-2 dropdown js-notification-wrapper data-refresh-action-path="{{ path('get_notifications_template') }}"">
<a href="#" class="icon-wrapper nav-link btn-lg" data-toggle="dropdown">
<span class="icon icon-mail" aria-hidden="true"></span>
<span class="badge badge-notification">{{ all_notification_count }}</span>
</a>
<ul class="dropdown-menu dropdown-menu-right notification-list">
{% if app.user is not null and is_granted('ROLE_USER') and all_notification_count != 0 %}
{% for notification in notifications %}
<div class="notification-text">
<div class="d-flex">
<div class="col-10 px-0">
Kurszugang: {{ notification.courseAction.course }} ({{ notification.courseAction.course.school }})
- {{ notification.courseAction.schoolUser }}
</div>
<div class="col-2">
<button class="btn btn-sm btn-success" id="js-accept-course-action" data-course-action-path="{{ path('course_action_accept_join_request', {'courseAction' : notification.courseAction.id}) }}">
<i class="icon icon-thumbs-up"></i>
</button>
<button class="btn btn-sm btn-secondary" id="js-decline-course-action" data-course-action-path="{{ path('course_action_decline_join_request', {'courseAction' : notification.courseAction.id}) }}">
<i class="icon icon-thumbs-down"></i>
</button>
</div>
</div>
</div>
</li>
{% endfor %}
{% endif %}
</ul>
</li>
{% endif %}
{% endif %}
Can somebody tell me - why I can't only the snipped but a whole html page?
I can not append this whole page to the container ...
The way I understand it render returns a complete response(with headers), while renderView will just return the html.
Try changing this line:
return $this->render('Menu/_notifications_block.html.twig');
to this:
return new JsonResponse([
'html'=> $this->renderView('Menu/_notifications_block.html.twig')
]);
then in the ajax function change:
$('#user-notifications-container').append(data);
to this:
$(data.html).appendTo('#user-notifications-container');

How to use JSON data in a nunjucks template?

js return list =
<ul><li data-name="{id:1,name:'a'}">a</li><li data-name="{id:2,name:'b'}">b</li></ul>
{{list|dump}} Why does it show?
<ul><li data-name=\"[object Object]\">a</li><li data-name=\"[object Object]\">b</li></ul>
you can use raw
you can use a {% raw %} block and anything inside of it will be output as plain text.
Your code:
<ul>
<li data-name="{id:1,name:'a'}">a</li>
<li data-name="{id:2,name:'b'}">b</li>
</ul>
Example:
{%
set list = [
{name: 'a', id: 'yourId1'},
{name: 'b', id: 'yourId2'}
]
%}
<ul>
{% for item in list %}
<li data-name="{{item.name}}" id="{{item.id}}">{{item.name}}</li>
{% endfor %}
</ul>
Output:
<ul>
<li data-name="a" id="yourId1">a</li>
<li data-name="b" id="yourId2">b</li>
</ul>

Django1.10 - /i18n/setlang/ CSRF token missing or incorrect

After selecting a language in a language switcher form, I got a CSRF error:
The form is in base.html
<form action="{% url 'set_language' %}" method="post" class="form-inline">
{% csrf_token %}
<input name="next" type="hidden" value="" />
<div class="form-group">
<div class="input-group">
<div class="input-group-addon"><i class="fa fa-globe" aria-hidden="true"></i></div>
<select name="language" class="form-control" id="lang-switcher">
{% get_current_language as LANGUAGE_CODE %}
{% get_available_languages as LANGUAGES %}
{% get_language_info_list for LANGUAGES as languages %}
{% for language in languages %}
<option value="{{ language.code }}"{% if language.code == LANGUAGE_CODE %} selected="selected"{% endif %}>
{{ language.name_local }} ({{ language.code }})
</option>
{% endfor %}
</select>
</div>
</div>
</form>
I submit the form with JS:
jQuery('#lang-switcher').change(
function(){
jQuery(this).closest('form').trigger('submit');
});
my template file art.html is as follow:
{% extends "base.html" %}
{% load staticfiles %}
{% load i18n %}
{% block content %}
....
{% endblock %}
views.py is as follow:
from django.template import RequestContext
from django.shortcuts import render_to_response
from .models import Exhibition, Picture
def index(req):
highlight = Exhibition.objects.latest()
exhibitions = Exhibition.objects.all()[1:]
return render_to_response('art.html', RequestContext(req,{'highlight': highlight, 'exhibitions': exhibitions}))
urls.py is as follow:
urlpatterns = [
url(r'^i18n/', include('django.conf.urls.i18n')),
url(r'^admin/', admin.site.urls),
url(r'^art/', index),
url(r'^$', views.flatpage, {'url': '/home/'}, name='home')
]
I can load the page w/o problems, then when I submit the form to switch language I get the CSRF error.
edit
I must add that the form works well when I'm on root.
I finally solved it by using a different render function in my view:
return render(req, 'art.html', {'highlight': highlight, 'exhibitions': exhibitions})

Add likes and page visit counts to Django project

I'm trying to give users ability to like/dislike objects (using ajax), and to count page visits. I've written functions and changed the templates but there's a mistake somewhere. The result of likes and views is always 0. It seems to me that the mistake is in views.py functions, but maybe I'm wrong, I'm a beginner in Django. Now according to the functions it is allowed for a user to like an object more then one time. I would like to let the user not to do so, but to give an ability to dislike the object. But first I would like at least a simple to work properly. First I tried to count the number of visits of user page and to add likes for model Day.
Could you please tell me how to correct my files?
This is a part of view:
#login_required
def like_day(request):
day_id = None
if request.method == 'GET':
if 'day_id' in request.GET:
day_id = request.GET['day_id']
likes = 0
if day_id:
day = Day.objects.get(id=int(day_id))
if day:
likes = day.likes + 1
day.likes = likes
day.save()
return HttpResponse(likes)
def track_url(request):
person_id = None
url = '/friends_plans/users/'
if request.method == 'GET':
if 'person_id' in request.GET:
person_id = request.GET['person_id']
try:
person = Person.objects.get(id=person_id)
person.views = person.views + 1
person.save()
url = person.url
except:
pass
return redirect(url)
This are list.html (there must be a number of page views for each user)
{% extends 'friends_plans/base.html' %}
{% load staticfiles %}
{% block title %} Users {% endblock %}
{% block content %}
<div id ="left">
<div id="toptitle"> Friends' Plans members:</div>
<table class="table">
<thead>
<tr>
<th>Photo</th>
<th>Name</th>
<th>Occupation</th>
<th>Days</th>
<th>Places</th>
<th>Wiews</th>
</tr>
</thead>
<tbody>
{% for person in users %}
<tr>
<td><span> <img class="small_cat" src={% static 'images/cat3.jpg' %} /> </span></td>
<td>{{ person.username|upper }}</span></td>
<td><span>Student at {{ person.place_of_work_or_study}}</span></td>
<td>{{person.day_set.all.count}}</td>
<td>{{person.wish_list_set.all.count}}</td>
<td>{{person.wish_list.comment_to_wish_list_set.all.count}}</td>
<td>{% if person.views >= 0 %}
{{person.views}} views
{% elif person.views == 1 %}
{{person.views}} view
{% endif %}
</td>
</tr>
{% endfor %}
</tbody>
</table>
<div class="pagination">
<div id="listing">
<span class="step-links">
{% if users.has_previous %}
previous
{% endif %}
<span class="current">
Page {{ users.number }} of {{ users.paginator.num_pages }}.
</span>
{% if users.has_next %}
next
{% endif %}
</span>
</div>
</div>
</div>
{% endblock %}
This is day.html (there's a like button there)
<!DOCTYPE html>
{% load staticfiles %}
<html >
<head>
<title> {{person.username}} </title>
<meta charset ="utf -8" />
<link rel="stylesheet" href="{% static 'css/style_day.css' %}">
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.12.2/jquery.min.js"> </script>
<script src="{% static 'js/friends_plans-jquery.js' %}"></script>
<script src="{% static 'js/friends_plans-ajax.js' %}"></script>
</head>
<body>
<div id ="container">
<div id ="header">
<ul id ="menu">
<span><a href ="" >Friends' Plans</a></span>
<span><a href ="{% url 'friends_plans:user' request.user.pk %}" >My Page</a></span>
<span><a href ="{% url 'friends_plans:listing' %}" >Users</a></span>
<span><a id="helpbutton" href ="" >HELP</a></span>
</ul>
</div>
<div id ="left">
<div id="border">
<div><a class="button" href="{% url 'friends_plans:user' person.pk %}">{{person.username}}</a></div>
<img class="cat" src={% static 'images/cat5.jpg' %} />
</div>
<div id="info">
<div class ="name"> {{person.email}} </div>
<div class ="name"> {{person.phone_number}} </div>
<div class ="name"> Student of {{person.place_of_work_or_study}} </div>
</div>
<div id="empty"> </div>
</div>
<div id ="right">
<div class="sep">
<div class="title"> {{person}}'s plans for {{day}}: </div>
<div class="value"> Status: {{day.level_of_business}} </div>
{% for event in day.event_set.all %}
<div class="title1"> <a class="button" href ="">Business: {{event.business}}</a></div>
<div class="title1"> Type: {{event.type}}</div>
<div class="title1"> Period of time: {{event.start_time}}-{{event.end_time}}</div> <br />
{% endfor %}
</div>
<p>
<strong id="like_count">{{ day.likes }}</strong> users like this day
{% if user.is_authenticated %}
<button id="likes" data-catid="{{day.id}}" class="btn btn-primary" type="button">
<span class="glyphicon glyphicon-thumbs-up"></span>
Like
</button>
{% endif %}
</p>
<div>
{% if person.id == request.user.id %}
Add event
{% endif %}
</div>
</div>
<div id ="footer"> Copyright </div>
</div>
</body>
</html>
And this is ajax file:
$('#likes').click(functin()){
var catid;
catid = $(this).attr("data-catid");
$.get('/friends_plans/like_day/', {day_id: catid}, function(data){
$('#like_count').html(data);
$('#likes').hide();
});
});
And these are my models, Person:
class Person (AbstractUser):
phone_number = models.CharField(max_length=30)
place_of_work_or_study = models.CharField(max_length=100)
img = models.ImageField(upload_to='photos/', null=True, blank=True)
url = models.URLField(null=True, blank=True)
views = models.IntegerField(default=0)
class Meta:
verbose_name = 'Person'
verbose_name_plural = 'Users'
def __unicode__(self):
return self.username
And Day:
class Day(models.Model):
person = models.ManyToManyField(Person)
date = models.DateField()
url = models.URLField(null=True, blank=True)
views = models.IntegerField(default=0)
likes = models.IntegerField(default=0)
levels = (
('busy', 'busy'),
('has_suggestions', 'has_suggestions'),
('waiting_for_suggestions', 'waiting_for_suggestions')
)
level_of_business = models.CharField(choices=levels, max_length=40, default='waiting_for_suggestions')
def __unicode__(self):
return unicode(self.date)
The syntax of your AJAX code is not correct. It should be
$('#likes').click(function(){
var catid;
catid = $(this).attr("data-catid");
$.get('/friends_plans/like_day/', {day_id: catid}, function(data){
$('#like_count').html(data);
$('#likes').hide();
});
});
Furthermore, please note that you should not use GET to manipulate data on the server. This can be abused by CSRF attacks. Use POST instead.
If you choose to use POST you should not forget to generate a csrf-token in the template and send it together with the request either as a X-Header or inside a cookie.
The solution for the problem was to add $(document).ready( function(){})to AJAX request.

How to hide unavailable product variants in Shopify?

I'm trying to make only the available product variants visible in drop downs for products like this one. For example, say you choose 2012 in the first drop down, it would only show the available choices in the second. If you then chose Wed 25th July in the second, it would only show the available variants in the third. At the minute it shows all choices and states 'We don't offer the product in this combination' for an unavailable choice.
So far, my product.liquid page has this code:
<div class="col-7 product-description clearfix">
<h1>{{ product.title }}</h1>
{{ product.description }}
{% include 'addthis' %}
<br/><br/>
{% if product.available %}
{% if product.variants.size > 1 %}
<!-- If the product only has MULTIPLE OPTIONS -->
<form action="/cart/add" method="post" class="product-variants">
<div id="options">
<select id="product-select" name='id'>
{% for variant in product.variants %}
<option value="{{ variant.id }}">{{ variant.title }}</option>
{% endfor %}
</select>
<div class="select-wrapper">
<label for="region">DVD Region</label>
<select id="color" required>
<option value="NTSC">NTSC</option>
<option value="PAL/SECAM" selected="selected">PAL/SECAM</option>
</select>
</div>
<p>Click Here find out more about your region.</p>
</div> <!-- options -->
<div class="price-field"></div>
<input type="submit" name="add" value="Add to cart" id="purchase" />
</form>
{% else %}
<!-- If the product only has ONE variant -->
<form action="/cart/add" method="post" class="product-variants">
<div class="price-field"> {{ product.price | money }}</div>
<input type="submit" name="add" value="Add to cart" id="purchase" />
<input type="hidden" id="{{ variant.id }}" name="id" value="{{ product.variants[0].id }}" /> <!-- passes variant id -->
</form>
{% endif %}
{% else %}
<p>This product is not available</p>
{% endif %}
</div><!-- .col-7 -->
<div class="col-5 last product-thumbs">
<ul>
{% for image in product.images %}
{% if forloop.first %}
<li class="featured-image" >
<a class="zoom " href="{{ image | product_img_url: 'large' }}" title="{{ product.featured_image.alt | escape }}">
<img src="{{ image | product_img_url: 'large' }}" alt="{{ product.featured_image.alt | escape }}" />
</a>
</li>
{% else %}
<li>
<a class="zoom" href="{{ image | product_img_url: 'large' }}" title="{{ image.alt | esacpe }}">
<img class="" src="{{ image | product_img_url: 'small' }}" alt="{{ image.alt | escape }}" />
</a>
</li>
{% endif %}
{% endfor %}
</ul>
</div><!-- .col-5 -->
<script type="text/javascript">
// <![CDATA[
var selectCallback = function(variant, selector) {
if (variant && variant.available == true) {
// selected a valid variant
jQuery('#purchase').removeClass('disabled').removeAttr('disabled'); // remove unavailable class from add-to-cart button, and re-enable button
jQuery('#purchase').fadeIn();
jQuery('.price-field').html(Shopify.formatMoney(variant.price, "{{shop.money_with_currency_format}}")); // update price field
} else {
// variant doesn't exist
jQuery('#purchase').addClass('disabled').attr('disabled', 'disabled'); // set add-to-cart button to unavailable class and disable button
jQuery('#purchase').fadeOut();
var message = variant ? "Sold Out" : "We don't offer the product in this combination";
jQuery('.price-field').text(message); // update price-field message
}
};
// initialize multi selector for product
jQuery(document).ready(function() {
new Shopify.OptionSelectors("product-select", { product: {{ product | json }}, onVariantSelected: selectCallback });
{% assign found_one_in_stock = false %}
{% for variant in product.variants %}
{% if variant.available and found_one_in_stock == false %}
{% assign found_one_in_stock = true %}
{% for option in product.options %}
jQuery('.single-option-selector:eq(' + {{ forloop.index0 }} + ')').val({{ variant.options[forloop.index0] | json }}).trigger('change');
{% endfor %}
{% endif %}
{% endfor %}
$('#options div').addClass("selector-wrapper");
{% if product.options.size == 1 %}
$(".selector-wrapper").append("<label>{{ product.options.first }}</label>");
{% endif %}
});
// ]]>
</script>
Any help?

Resources