FAQ Database Discussion Community


Django include template tag alternative in python class

python,django,django-templates
I know there is a Django template tag that allows to include other templates like so: {% include 'template.html' %} I am wondering if I could do the same, but in a separate python class (not in the HTML template)? I know that for example the url tag has an...

Django template rendering extend tag incorrectly

django,django-templates
I have three Django templates: base.html: user_links.html user_detail.html I want user_links.html to extend base.html. Next, I want user_detail.html to extend user_links.html and base.html. Here's base.html: <head> <title>Cool App</title> <link rel="stylesheet" type="text/css" href="{{ STATIC_URL }}css/main.css" /> </head> <body> <h1>Cool App</h1> <div class="navbar"> <p> <a href="{% url 'home' %}">HOME</a> | {% if...

How Django's url template tag works?

django,django-templates,templatetags
How does {"% url 'news_id' %"} work? I do have a url pattern url(r'^((?:\w|-)+)/$', 'comments.views.home', name='news_id') but I still get NoReverseMatch. It says Reverse for 'news_id' with arguments '()' and keyword arguments '{}' not found. 1 pattern(s) tried: ['((?:\w|-)+)/$'] views.py from django.shortcuts import render from comments.models import User from django.http...

Django view variable not presenting any data in html

python,django,django-templates
I am trying to pass "Hello World!" from a Django view into index.html view.py (excuse the brevity): def index(request): context = "Hello World!" return render(request, 'hud/index.html', {"context": context}) index.html (brevity): <html> <h1>{{ index.context }}</h1> </html> I am expecting it to print the value of "context" and it does not. I...

Problems with rendering page on Django framework

python,django,django-templates,django-views
I have categories of the news and news and i don't know how to render the page with the list of news that belong to the same category. Hope You will help me with that. this is my model.py file: from django.db import models class Category(models.Model): class Meta: verbose_name_plural =...

django front end customization by designer (without modifying view or form)

python,django,forms,django-templates
I'd really like my front end colleague to handle CSS and other front end things -- indeed, a design principle of django is this separation, that they can mostly modify templates and not need me to change code. And yet, too often it seems the only way I can find...

How to work with django-rest-framework in the templates

json,django,django-templates,django-rest-framework
Please bear with me. I am just learning django-rest-framework. And I really can't seem to grab it. model: class Day(models.Model): date = models.DateField(default=date.today) class ToDo(models.Model): date = models.ForeignKey(Day) name = models.CharField(max_length=100) very_important = models.BooleanField(default=False) finished = models.BooleanField(default=False) normal view: def home(request): days = Day.objects.all() return render(request, 'test.html', { 'days':days })...

Correct

django,django-forms,django-templates,django-views
I have been having some trouble getting a Django SessionWizardView to submit data to my database and I am trying to isolate the issue. I note from the Form documentation As well as its elements, a form must specify two things: where: the URL to which the data corresponding to...

How should I show results of BeautifulSoup parsing in Django?

python,django,django-templates,django-views,beautifulsoup
I'm trying to scrape a web page using BeautifulSoup and Django. Here's my views.py which do this task: def detail(request, article_id): article = get_object_or_404(Article, pk=article_id) html = urllib2.urlopen("...url...") soup = BeautifulSoup(html) title = soup.title return render(request, 'detail.html', {'article': article, 'title':title}) But when I use {{ title }} in django template...

How to tell a Django view who called it?

django,django-templates,django-views
I have two Django views that render two separate templates. Each of these templates will contain a link to the same third view. That third view will render a template that should display one button if the first Django view/template link redirected to it but render a different button if...

Django-cms Placeholder naming from template variable

django,django-templates,django-cms
I am working on generating a menu which allows the user to upload an image, and text description, to each subsection of the menu. Here is the current code (custom template for displaying a menu): {% for lowest in lower.children %} {% with lowest.get_menu_title as title %} <div id="product_box"> <div...

How do I use custom filters when using django as a standalone template engine

python,django,django-templates
I'm trying to use django as a stand alone template engine. This works fine based on this I tried to add a simple filter, but the template isn't able to use it The basic example code is: from django.template import Template, Context, Library from django.conf import settings settings.configure() register =...

Generating html pages off Django database entries

django,django-templates,django-views
I am trying to get a url mapping to follow this example /user/user-name/list/list-name-goes-here I created this regex (unsure if it's correct) url(r'^user/(\w+)/list/(?P<listname>\w+)/$', mylistpage, name='lists'), So users currently have the ability to insert a series of lists and they print onto their main profile page. I want them to click on...

forloop.last not working in Django

django,django-templates
forloop.last is not working as expected. It is actually working as if it belonged to the outermost forloop. When the last visit is printed the last comma in the last is not showing. My code is this: <tbody> {% for visit in SiteVisits %} <tr> <td>Data</td> <td>Other Data</td> <td>More Data</td>...

Insert separator only if didn’t insert one before

python,django,django-templates
I have a template variable product_list, which is a QuerySet of Product objects; Product objects, in turn, have a one-to-many field of Track objects (reverse mapped from Track, of course), which is possible to be empty. I want to create a list of Tracks, grouped by Products like this: {%...

NoReverseMatch at /resetpassword/ in Django

django,django-templates,passwords,reset
I´m getting this error during Reset Password. I have a login page whith the link to reset forgotten password, it shows correctly the templates, but if I write the mail to send the reset link, it shows this error: localhost/resesetpassword NoReverseMatch at /resetpassword/ Reverse for 'password_reset_confirm' with arguments '()' and...

Displaying images “not featured” with featured images in Django template language

django,django-templates
I am trying to display small thumbnail under featured images using django template language but for some reason main image displays fine but not small image. Idea is to display one featured image and rest as "not featured" images. My single-page code to display "Featured Images" with "Not Featured" images...

remove 'year' from a date filtered with 'naturalday'

django,django-templates
I am using the naturalday filter in a template, like {{ reply.createdate| naturalday }} which gives me: yesterday March 1, 2015 February 20, 2015 But that is too long, so I want to remove the year. How can I strip the , 2015?...

How to access all dictionary keys in template

python,django,django-templates
I am passing a dictionary like below to my template: mydict={6:"a",9:"b"} Now I want to check in template if a particular value is in dictionary key.Something like: {% if i in mydict.items.keys %} ok {% endif %} I want to display "ok" if i is either 6 or 9, however...

In Django template how to separate Date and time from DateTimeField?

django,django-models,django-templates
I want to print only the date on my Django template. This is my model. class Comment(models.Model): name = models.ForeignKey(User) body = models.TextField() pub_date = models.DateTimeField(auto_now_add=True) article = models.ForeignKey(Article) Now to print both date and time on a template I can use {{object.pub_date}} to print. But I only want to...

How to deal with my login_required url?

python,django,django-templates
I have: Linker urls: from django.conf.urls import include, url from django.contrib import admin urlpatterns = [ url(r'^admin/', include(admin.site.urls)), url(r'^$', include('distributors.urls', namespace='distributors')), url(r'^accounts/', include('allauth.urls')), ] App urls: url(r'^$', views.Index.as_view(), name='index'), url(r'^links/$', login_required(views.LinkListView.as_view(), name='links'), in my html i have href="{% url 'distributors:index' %}" and href="{% url 'distributors:links' %}" Views: class Index(TemplateView):...

Unable to access upvote/downvote input in a Django template

html,django,django-forms,django-templates
I am reading upvote/downvote from a Django template in the following manner: <form method="POST" action="{% url 'vote' %}" class="vote_form"> {% csrf_token %} <input type="hidden" id="id_value" name="value" class="hidden_id" value="{{ btn1.value }}" /> <button type="input" name="btn1" value="1">upvote</button> <button type="input" name="btn1" value="-1">downvote</button> </form> Note: The object being voted on and the user_id creating...

how to have some contexts all over a project?

python,django,django-templates
I'm trying to have a team model and i want to have access to its fields all over my project like how you use {{user.username}} wherever you want. down here I've put my team model. class Team(models.Model): name = models.CharField(max_length=25) manager = models.ForeignKey(User) coin = models.IntegerField(default=50000) gem = models.IntegerField(default=0) motivation...

How to pass json directory to the template within the django framework?

json,django,d3.js,django-templates,directory
I am new to D3 and django and I hope to combine them for visualization. I download one code example of D3, and it needs the json file as data source. I then write a template in Django like: ` .link { stroke: #ccc; } .node text { pointer-events: none;...

Subtracting two variables in django template [duplicate]

python,django,django-templates
This question already has an answer here: Variable subtraction in django templates 2 answers I have to subtract two values in django templates. How can I do this ? {{ obj.loan_amount }} - {{ obj.service_charge }} ...

Could not parse the remainder django template

django,python-2.7,django-templates
I have a condition within a loop in my template like this: {% for message in message_trash %} <td><a href="#"> {% if request.session.user_email == message.message_user_reciever.user_email %} {{ message.message_user_reciever.user_firstName }} {{ message.message_user_reciever.user_lastName }} {% elif request.session.user_email == message.message_user_sender.user_email %} {{ message.message_user_sender.user_firstName }} {{ message.message_user_sender.user_lastName }} {% endif %} </a><small><a...

In django, can I use 'as' in if tags like so: {% if excessively_verbose.chain_of_long.nested_references as foo%}

python,django,if-statement,django-templates
I'm populating xml from json with an excessively_verbose.chain_of_long.nested_references. Sometimes that parent level isn't there, and in an effort to reduce the padding of my template, I'd like to use something a little like this: {% if excessively_verbose.chain_of_long.nested_references as foo%} I've tried the above and the below: {% if excessively_verbose.chain_of_long.nested_references with...

Accessing list item in django template

python,django,django-templates,django-template-filters
I have a list, rate_text ['', 'Disappointed', 'Not Promissing', 'OK', 'Good', 'Awesome'] in the template rendered from the view. I can access any of the item of that using {{rate_text.index}} like the following: {% for review in reviews %} <div class="panel panel-info" style='border-color:#ffffff;'> <div class="panel-heading" > <h3 class="panel-title lead">{{review.title}}</h3> </div>...

Is it possible to display a specific block from a template in django?

django,django-templates,django-views,django-urls,django-template-filters
Just like in html when you reference a section of a page with for instance<a href="#tips">Visit the Useful Tips Section</a> Would there be a way to do a similar thing in django if for instance I wanted to load my page straight to the tips section? I am extending base.html...

Django template looks up?

python,django,django-templates
I'm looking for an explanation on the django tutorial here and especially the template part it says : The template system uses dot-lookup syntax to access variable attributes. In the example of {{ question.question_text }}, first Django does a dictionary lookup on the object question. Failing that, it tries an...

How to submit POST request to '“current_url”/submit' in HTML's form action using Django templates?

django,django-templates,django-views,html-form
Let's say I have many posts and each post has a url example.com/post_id. Also there is a HTML form after this post where one can submit comment. If I had to submit this comment to this url: example.com/submit , then I could just do <form action="submit/" method="post">. But, I want...

How to pass around variables without url parameters in Django?

django,django-templates,url-parameters
My question is, how could I go about passing information in django from the template to a view without url parameters. I know that sessions can help me do this however, I can't find any resources online that show how to create a key value pair in the sessions from...

Better errors message if template is missing

python,django,debugging,django-templates
If a template is missing deep inside the rendering of a django template, I get a exception like below. After searching very long I found the bogus part: {% include form.template_name %} form.template_name was empty in my context. How can I find the relevant template name without searching for hours?...

Django - Template Tags, display

python,html,django,django-templates
I have a working model.py like this, I am able to add records to this model using Django admin: from django.db import models from django.contrib import admin from audiofield.fields import AudioField # Create your models here. class Music(models.Model): tittel = models.CharField(max_length=20, default = "titel her") artist = models.CharField(max_length=20, default =...

Django hosting static files on the server

django,django-templates,django-staticfiles,django-statistics
I am trying to deploy my Django project on the server. But, when I use it, the static file on Django can not be read correctly I deploy my project on Debian server. The static file of course in same server, I have succeeded in deploying my project. But static...

How do I order dict by iterating list of uuids in django template language?

python,django-templates,uuid
I'm trying to order a dict by using a list containing the order uuids in django - how would I template this out? order = ['uuid1', 'uuid2'] data = { u'uuid1': { u'checked': False, u'deleted': False, u'last_change': u'2014-12-25 09:15:22.155000', u'text': u'Test.' }, u'uuid2': { u'checked': False, u'deleted': False, u'last_change': u'2014-12-25...

Template Tag in Javascript

javascript,django,django-templates,django-template-filters
My Django template tags are not working within my javascript. My latest error is: SyntaxError: expected expression, got '&' var resourceTypes = [&#39;Structural Model&#39;, &#39;X-Ray Diffraction&#39;] How can I get this to work? I need to get these Django variables into the js so that I can create a chart...

How to display uploaded django ImageField in django/mezzanine template?

django,apache,django-templates,mezzanine,imagefield
I don't have a clue here. I've set up a form with ImageField to upload user images via frontend and upload is working fine, though I can't find a way to retrieve the pics url and display it in a template. I did run python manage.py collectstatics. Template files and...

How to intialize the variable and increment it in Django template?

django,django-templates
I am trying to initialize the variable and increment it, in the for for loop but getting the following error? Invalid block tag: 'set', expected 'endspaceless' <tr{{ row.attr_string|safe }}> {% spaceless %} {% set counter = 0 %} {% for cell in row %} {% set counter= counter+1 %} {%...

How to translate this raw query to Django ORM

sql,django,django-models,django-templates
I have a model where we have candidates, languages and language Level entities: class Candidate(models.Model): user = models.ForeignKey(MyUser) telephone = models.CharField(max_length=20, unique=True) postcode = models.CharField(max_length=10) class Language(models.Model): name = models.CharField(max_length=50) class LanguageLevel(models.Model): candidate = models.ForeignKey(Candidate) language = models.ForeignKey(Language) level = models.IntegerField(max_length=1, choices=LANGUAGE_LEVEL, default=0) My raw query is: SELECT c.id, COUNT(c.id)...

How to resolve the following HTML error?

html,html5,django-templates
I have the following lines in my django template file:-cart.html:- <td class="right"> <form method="post" action="." class="cart"> <label for="quantity">Quantity:</label> <input type="text" name="quantity" value="{{ item.quantity }}" id="quantity" size="2" class="quantity" maxlength="5" /> <input type="hidden" name="item_id" value="{{ item.id }}" /> </td> <td> <input type="submit" name="submit" value="Update" /> </form> </td> At the first closing tag...

Passing checkboxes values to view in django

django,checkbox,django-templates,django-views
I have a table with some database data <table id="id_list_table" class="table table-condensed"> <caption>Inputs list</caption> <thead> <tr> <th>#</th> <th id="input">Input</th> </tr> </thead> <tbody id="fbody"> {%for input in InputsAll%} <tr> <td>{{ input.input }}</td> <td> <a class="btn btn-primary btn-xs" href="{% url 'edit' %}?input_num={{input.id}}" id="edit">edit</a> <a class="btn btn-danger btn-xs" href="{% url 'delete'...

Django-Angular's djng_rmi template tags do not expand

django,angularjs,django-templates
I'm trying to use Django-Angular's djangoRMIProvider to give my angular app that sits on top of django access to some django methods. The snippet I've copied in (and customised the my_app name), and added a console.log to is: {­% load djangular_tags %­} … <script type="text/javascript"> console.log("djangoRMIProvider: "+djangoRMIProvider); my_app.config(function(djangoRMIProvider) { djangoRMIProvider...

how to pass variable from html template to view method in django via url

django,django-templates
I want to pass a variable from html template to my view method in django so that i can use it in the python view method. Below is my html code: <li><a href="{%url 'Automation:rollbackAAI' router_hostname %}">Rollback</a> My URL mapping: url(r'rollbackAAI/(?P<router_name>[a-z]+)$',views.rollbackAAI, name='rollbackAAI'), My views.py: def rollbackAAI(request, router_name = None, *args, **kwargs):...

Radio button layout messed up in Django template

html,css,django-templates,radio-button
I have Django template where a user fills out her bio, mobile number, age, gender and marital status. Gender and marital status are radio buttons with two options, the former 3 choices are text fields. The template is laid out thusly: <form method="post" action=""> {% csrf_token %} {{ form.bio.label_tag }}{{...

objects.all() queryset not working with view to template; many-to-one relationship

django,django-templates,django-views
I am trying to make this template call a function that has worked in the past with a many-to-many relationship. This time it is a many-to-one. the detail.html template {{ icecreamflavor.name.all }} The view: from django.shortcuts import get_object_or_404, render from django.views import generic from .models import IceCream, IceCreamFlavor # Create...

Django CMS losing data from draft to live

django,python-3.x,django-templates,django-cms
I'm creating a carousel plugin using the filer plugin to access easily images. The carousel is simply made with Bootstrap Carousel. The problem is that my carousel is displayed properly in draft but when I pass to live, only the arrow are remaining. When I try to debug with some...

Display a specific template when Django raises an exception

python,django,exception,django-templates
In my django app, I have multiple places where I raise a specific custom exception DeserializationError. My goal is to show/redirect to a pretty page to show the user this error, including the error message, when this error is raised. Basically, a page that says something like Something went wrong....

Accessing Specific Dictionary Values by Key in Django Template

python,django,django-templates
I know to use '.' notation to access dictionary items in a template (just like this post explained), but when I try to access a particular key, it's not working. What's going wrong? My dictionary: images[mykey] = "the value string" Then in the template, I try to access by key...

Create angular page in Django to consume data from JSON

angularjs,django,django-templates
In an angular controller I have a list of items: app.controller('MainController', ['$scope', function($scope) { $scope.items = [ {"foo":"bar 1"}, {"foo":"bar 2"}, {"foo":"bar n"} ] }]); The following html page, based on angular, displays a list of item: <!DOCTYPE html> <html> <head> <title>list</title> <script src= "http://ajax.googleapis.com/ajax/libs/angularjs/1.3.14/angular.min.js"></script> </head> <body data-ng-app="myApp"> <div data-ng-controller="MainController">...

Django block inclusion not working. What did I miss?

django,django-templates
In my base.html file I have this: {% block menu %}{% endblock menu %} and in base_menu.html I have this: {% extends "base.html" %} {% block menu %} <nav class="navbar navbar-inverse navbar-fixed-top"> ... stuff ... </div> {% endblock menu %} I would expect the menu html to show where the...

User specific data in automatic generated forms

django,django-forms,django-templates
My code is pretty simple and straight forward. These are my forms class LearningObjectiveForm( ModelForm ): class Meta: model = LearningObjective fields = ( 'learning_objective', 'topic', ) this is a snippet from my template <form method="POST" action="."> {% csrf_token %} <table> {{ form }} </table> <input type="submit" value="Speichern"/> </form> this...

django does not match pattern called in template

python,regex,django,django-templates,django-urls
Iam trying to call {% url %} in a template to have dynamic links, but i get an error although the pattern should match. Here are my files: urls.py urlpatterns = [ url(r'^(?P<team_id>[0-9]+)/$', views.detail, name='detail'), url(r'^$', views.index, name='index'), ] template file {% for team in teams_list %} <li><a href="{% url...

Using Django Choices in Template Logic

django,django-templates
I have a model, say: from model_utils import Choices class Day(models.Model): WEATHER = Choices( ('r', 'rainy', 'Rainy'), ('s', 'sunny', 'Sunny'), ) weather = models.CharField(max_length=1, choices=WEATHER) Is there a way, in the presentation, to use the logical keywords e.g.: {% ifequal monday.weather Day.WEATHER.rainy %} It rained monday {% endifequal %} I...

objects.all() query not working

python,django,django-templates,django-views
I am trying to make a form for user creation through django. The user(henceforth developer) can choose from a list of supervisors to get himself registered. Problem is, I am not getting the list of all the supervisors from the query. When I use objects.get(), I receive an error that...

How to move js file out of a template when it uses template's and django's variables?

django,django-templates
Most of SO examples of using django's variables in JS have JS inside HTML. I tried to place JS in a separate file but it stopped working. When I use JS inside template {% url "distributors:search_dist" %} works just fine and it moves me to distributors/search_dist, but when I try...

Substring in a django template? [duplicate]

django,django-templates
This question already has an answer here: Django substr / substring in templates 3 answers How do i display a substring in a django template? The following doesn't seem to work, I am trying to display the first 3 letters and the next 3 in another line: {{ obj.name[0:3]...

Slice and attribute in django template

django,django-templates,slice
I am tried to create a slice in django template and get an attribute. How can i do in django template something like this: python code: somelist[1].name please help...

F() Expression strange behavior with Django

python,django,django-models,django-templates,django-template-filters
I have this template tag that ultimately returns a list of 'active' advertisements (checks if Campaign with the active field is True, then pulls ads from the Campaign with a queryset) @register.assignment_tag def get_current_campaigns(amount): # Get all the campaigns that are active current_campaigns = Campaign.objects.filter(active=True) current_campaigns_count = current_campaigns.count() # To...

How to assign a div class to an element based on url in django template?

django,django-templates
I am using Django I am currently doing this: <a class="{% if request.path == '/messages/' %}current{% endif %}" To style a nav link, or to make it bolder indicating that you are on that page currently. The problem with this is that it only works when the user is at...

How to output django_filters.RangeFilter text boxes inline?

django,twitter-bootstrap,django-templates,django-filter
How to output django_filters.RangeFilter textboxes inline? I use django_filters and django-bootstrap-form My template.html <div class="row"> <div class="col-md-12"> <form action="" method="get" class="form-horizontal"> {{ filter.form|bootstrap_horizontal }} <input type="submit" class="btn btn-info" /> </form> </div> </div> UPDATE I have several text filters in filterset, and I want to place in horizontal, and only RangeFilter...

Button updates text of first element instead of selected element

javascript,jquery,html,django,django-templates
When I select the "Like" button, the button updates properly. However, the "like count" updates the count for the first image only, instead of the image I selected. Any ideas how to make only the selected image's like count update as the button does? Thank you in advance! html: {%...

How to change HTML of models (classes) in Django?

python,html,django,django-models,django-templates
Suppose I have a TrueFalseQuestion model (which only has a question_text) in myproject/myapp/models.py, and I want it to be rendered as, let's say <a>Question Text</a> <input type="radio">True</input> <input type="radio">False</input> (HTML could be wrong, not important) , in this template, only Question Text part changes, the input forms are always constant....

Combining multiple django apps into one view, what am I doing wrong?

python,django,django-templates,django-views
I have a Django project with multiple apps that I need to combine and render as a single page. I have the following sections of code: One of the views I'm trying to aggregate with other views: class ResourceList(generic.View): model = Submissions template_name = 'url_list.html' def get(self, request, *args, **kwargs):...

django error TemplateDoesNotExist

python,django,django-templates
I am new to Django and just follow the Django official document, but here is a problem. I create a new Django project with Django 1.8.2 + PyCharm 4.5.1 + Python 3.4.3 + Windows 8.1 - mysite - main - migrations __init__.py __init__.py admin.py models.py tests.py views.py - mysite __init__.py...

Templates Django (Does not exist at/)

python,django,templates,django-templates,views
I'm trying to use the Django templates but i cant even display a simple html line i don't understand why... I searched to resolve it but after many test, the problem remains. This is my structure: My urls.py (which work i tried it with another fonction in views.py): from django.conf.urls...

Is it possible to process arbitrary content with the Django template processor?

python,django,django-templates,django-views
My web app contains a banner serving API. Abridged banner model: class Banner(models.Model): name = models.CharField(max_length=50) ad_tag = models.TextField() active = models.BooleanField(default=True) priority = models.IntegerField(null=True, blank=False) def __unicode__(self): return self.name The banner serving API accepts some GET parameters and, based on these parameters, returns a Django template that spits out...

Django non-ASCII chars in template tags values

python,django,tags,django-templates,python-unicode
I'm writing a custom Django template tag for a french application. My template tag takes a parameter which is a string: {% mytag "Hello" %} Is works perfect, but fails when trying to put some non-ASCII chars in the value. How would you get this thing work: {% mytag "Êtes-vous...

Render in django can't passing an argument

django,django-forms,django-templates,django-views
i'm new in django and i'm trying to create an application that user can change his/her password based on his/her id. So far is good, but when i'm trying to passing an argument from my views.py, there is a trouble that an argument can't passing to the html template. This...

How to loop over datetime range in django templates

python,django,django-templates
I want to loop from current date to xxx date in columns I'm thinking about using this function: from datetime import timedelta, date def daterange(start_date, end_date): start_date = datetime.date.today() end_date = start_date + datetime.timedelta(days=5) for n in range(int((end_date - start_date).days)): yield start_date + timedelta(n) for single_date in daterange(start_date, end_date): print...

Return address in ListView

django,listview,django-templates,django-context
How to return address in DealershipList with ListView? I try in views.py class DealershipList(ListView): template_name = 'dealership_list.html' model = Dealership def get_queryset(self): pass def get_context_data(self, **kwargs): context = super(DealershipList, self).get_context_data(**kwargs) address = Dealership.objects.get(pk=self.kwargs['address']) context['address'] = self.address return context I need in templates. {% for dealership in dealership_list %} <div class="col-lg-6">...

Django - How do form template tags work?

django,django-forms,django-templates
This is a simple question, but I can't find the answer. The django docs show the following example for calling a form in template just using {{ form }}: <form action="/your-name/" method="post"> {% csrf_token %} {{ form }} <input type="submit" value="Submit" /> </form> This doesn't fully explain how the {{...

Include tag in Django template language — what can I pass in to it?

python,django,django-templates
OK, so again there is likely a "simple" solution to this, but I am a beginner and nothing seems simple to me. I have a view and a template that shows the attributes of an instance of a Car class that I have modeled. This Car class has a ManyToMany...

How do I create pretty url from the GET parameters in Django?

python,django,forms,django-templates,django-urls
my query string is generated by a form with name and age, that looks something like this, www.example.com/?name=Martin&age=19&place=RU the form, <form action="" method="get"> Name: <input type="text" name="name"><br> Age: <input type="text" name="age"><br> Place <input type="text" name="place"><br> <input type="submit" value="Submit"> </form> and I want to make the submitted url to django to...

Django - View Other user profile

django,python-3.x,django-models,django-templates,django-views
I am using Django 1.6 to create a web app.. I have users and user profiles and have designed templates to display the profile information of the user. class UserProfile(models.Model): class Meta: app_label = 'xyz' user = models.OneToOneField(User, related_name='user_profile') description = models.CharField(max_length=200) ... other fields ... I have various edit...

Not able to find static file path page redirect to another page

django,python-2.7,django-templates,django-staticfiles
When first time index page load it give static file path: [04/May/2015 09:16:22] "GET / HTTP/1.1" 200 3536 [04/May/2015 09:16:22] "GET /static/css/bootstrap.min.css HTTP/1.1" 304 0 [04/May/2015 09:16:22] "GET /static/js/jquery.js HTTP/1.1" 304 0 [04/May/2015 09:16:22] "GET /static/js/bootstrap.min.js HTTP/1.1" 304 0 [04/May/2015 09:16:22] "GET /static/css/simple-sidebar.css HTTP/1.1" 304 After click on hyperlink it...

How to create Django form for a photo grid?

python,django,django-forms,django-templates,django-views
I'm trying to create a Django form that will contain a grid of one to ten photos. There will be two radio button groups below each photo, one to indicate if the viewer approves or rejects that photo and a second group to indicate if the photo needs to be...

Looping in django template with variable parameter

python,django,django-templates
I want to get all the details of class Material where user=user_id Here is the models.py: class Material(models.Model): subject = models.CharField(max_length=10) topic = models.CharField(max_length=50) user = models.IntegerField() and my views.py: def add_material(request): c = {} c.update(csrf(request)) if 'user_session' in request.session: user_id = request.session['user_session'] material_array = Material.objects.filter(user=user_id).values() materials_len = len(material_array) c['m_len']...

reverse url of the blog article in template

django,django-templates,django-views,django-urls
{% url 'article' article.get_absolute_url %} wont' work as expected. Got error NoReverseMatch at /blog/ Url pattern is: url(r'^/(?P<slug>[-\w]+)-(?P<id>[-\d]+)/$', article, name='article'), where article is the function name....

Image input missing from POST request

html,django,post,django-templates
I have an input field corresponding to a Django ImageField in a Django template. Rendered, the HTML looks like: <form action="/accounts/username/" method="post" id="profile_form" enctype="multipart/form-data"> </form> ... (other input fields and elements) <input form="profile_form" id="id_profile_pic" name="profile_pic" type="file" /> The corresponding View is an UpdateView. I found request.FILES to be empty and...

How do I loop through a nested context dictionary in Django when I have no idea the structure I will recieve

django,django-templates,django-views
I have a dictionary I am passing to a template that looks something like this: {'leasee': {'respond': {'hour': True, 'day': True}, 'contact': {'phone': True, 'facebook': True, 'email': True, 'other': True, 'text': True}, 'licence': '987654321', 'help': {'beautySupplyProvider': True, 'photographer': True}, 'phoneNumber': '12345678910', 'name': 'Chris', 'certifications': {'yes': True, 'long': 'All of them'},...

Using image in a template django

django,django-templates
I want to view images, in a template, but I don't understand what I'm doing wrong. models.py class Item(models.Model): name = models.CharField(verbose_name = "Название", max_length = 100) TYPE_ITEMS = ( ("shirt", "Футболка"), ("shoes", "Обувь"), ("bags", "Рюкзаки и сумки"), ("heads", "Головные уборы"), ("others", "Другое"), ) type_item = models.CharField(verbose_name = "Тип продукта",...

get rows count from django_tables2

django,django-templates,django-tables2
I'm new at django, and I need to get table row count (best it would be if before rendering table) of table which rendered with django table2 in my template have some code like this: {% load render_table from django_tables2 %} {% block content %} {% render_table participations_table %} {%...

Check if member value is different than in previous iteration

python,django,django-templates
I have a QuerySet of GroupMembership objects ordered by product__name, which is assigned to my template as group_memberships; GroupMembership objects have a product and a group field, both having a name property. In the output I’d like to render a heading tag every time membership.product.name changes: <h1>First Product</h1> <p>One item</p>...

How to compare inner for iterator with outer for iterator

python,django,django-templates
I have the template code set up as : {% for f in fs %} { name: '{{f.fname}}', data: [{% for items in frequencydata %} {% if {{forloop.parentloop.counter}}=={{forloop.counter}} %} {% for item in items %} {{ item}}, {% endfor %} {% endif %} {% endfor %} ] }, {% endfor...

Django constant argument on URL

django,url,django-templates
I have an URL on django with this pattern in my urls.py url(r'^client/(?P<email>[^/]+)/events/(?P<count>[^/]+)/$', login_required(list_events_from_client), name='events_from_client'), As you can see, the url is formatted with first a constant, variable email, constant, and then variable count. The problem is that I have no idea how to generate this url on the template...

Django couldn't find my module if it is imported from a templetetag

python,django,django-templates
I'm upgrading an existing Django project to v1.7 and creating some templatetags to simplify working with templates. I've created some before, but one of them is giving the following error: ImportError raised loading recaptcha.templatetags.recaptcha: No module named utils. This module looks like this: - recaptcha |- templatetags | |- __init__.py...

Django CMS bootstrap navbar always collapsed in IE8

django,twitter-bootstrap,internet-explorer-8,django-templates,django-cms
Hello I am developing a django cms for my company but running into issues with the navbar in IE8. using: -Python 2.7.6 -Django (1, 7, 8, 'final', 0) -django-cms 3.1.0 -boostrap 3.3.4 here is my template {% load cms_tags staticfiles sekizai_tags menu_tags %} <!DOCTYPE html> <html> <head> <title>{% block title...

How to have 2 Models/Views/Templates on one Page in Django?

python,django,django-models,django-templates,django-views
I know this has probably been asked a 1000 times but I still for the life of me can't find a decent answer. Reading tutorials, Stack and even looking at GitHub for examples - nothing is helping or even guiding me in the right direction. I have 2 separate Models/Views/Templates...

How to DRY (myself) in Django form for Create and Edit Form

django,django-forms,django-templates,dry
I created two forms in Django for the same model, named AccountCreateForm and AccountEditForm. The Account model has say three fields and each of them has a few form attributes such as max_length, help_text, error_messages. For example, class AccountCreateForm(forms.Modelform): name = forms.CharField(max_length=50, required=True, label='Account Name', help_text='50 characters max', error_messages={'required': 'Please...

Django does not render my forms' fields

django,django-models,django-forms,django-templates,django-views
I have this model in models.py: class Life_events(models.Model): patient = models.ForeignKey(Demographic) HSCT_date = models.DateField('HSCT date',null=True,blank=True) HSCT_outcome = models.CharField('HSCT outcome',max_length=100, null=True, blank=True) partaker_in_clinical_trial= models.CharField('Partaker in clinical trial',max_length=200, null=True, blank=True) date_of_input= models.DateField(null=True,blank=True) def __str__(self): return str(self.patient) My forms.py contains: class LifeEventsForm(forms.Form): def __init__(self,...

Get the first image src from a post in django

django,django-templates,django-views
I have a model to write blogs. In that I'm using a wysiwyg editor for the Blog's descritpion, through which I can insert an image within the description. class Blog(models.Model): title = models.CharField(max_length=150, blank=True) description = models.TextField() pubdate = models.DateTimeField(default=timezone.now) publish = models.BooleanField(default=False) In the admin it looks like this:...

Get the list of all the models, that current user connected to

django,django-models,django-templates
I hope, that I wrote the Title correctly...))) I have the model article, that can connect to User through ManyToMany field. from django.db import models from django.contrib.auth.models import User from django.db import models class Article(models.Model): class Meta(): db_table = 'article' article_users = models.ManyToManyField(User, null=True, blank=True, default=None) article_title = models.CharField(max_length=200, blank=False,...

Is there a way to strip whitespace around a template tag?

django,django-templates
I have a template for a plaintext email: Here's some info. {% if variable %} Additional info. {% else %} Alternative info. {% endif %} {% if another_variable %} IMPORTANT MESSAGE {% endif %} Final thoughts. Unfortunately, since this is a plaintext template, rather than HTML, the newline characters that...

Operational error while using stripe with profile app

django,python-2.7,django-templates,stripe-payments
I am trying to embed Stripe in custom profile app and using django-registration package for registering users. I need to get users registered and then generate a Stripe ID for new users but getting the error below: OperationalError at /accounts/login/ no such table: profiles_userstripe My complete code for Profile app...

Show message when there's no excerpt - Django templates

python,django,django-templates,django-template-filters
I have this field on a Django template: <p class="border_dotted_bottom"> {{ expert.description|slice:":300" }} <a href="{% url 'profile' expert.username %}">{% trans "read more" %}</a>.... </p> If this object (user) has no 'decription' (a text field) it shows the word 'None', I need to get rid of that, maybe if he doesn't...

Access image urls from Django ForeignKey relationship

django,image,django-models,django-templates,django-views
I currently have a model defined the same way as this one: class Object(models.Model): name = models.CharField(max_length=50) class ObjectImage(models.Model): object = models.ForeignKey('Object', related_name='images') image = models.ImageField(upload_to='./objects') I am trying to access the urls of all the images for each object so that they can be displayed in a template. I...

Why is Django widgets for TimeInput not showing

django,django-forms,django-templates,django-views
I'm trying to create a TimeInput field in a form and noticed that the widget isn't showing correctly. But when I check the localhost:8000/admin, I see the widget showing up correctly. My code is as follows. For models.py, class TimeLimit(models.Model): before = models.TimeField(blank=True, default=time(7, 0)) # 7AM after = models.TimeField(blank=True,...

How do i cache bust with Django's staticfiles?

django,django-templates,django-staticfiles
I have a webpage which includes an image. I wish to cache bust that image using the ? technique. However, staticfiles encodes questionmarks as '%3F', so the path is no longer correct. {% load staticfiles %} <img src="{% static 'poll/img/test.jpg?v2' %}"> Gets compiled as. <img src="/static/poll/img/test.jpg%3Fv2"> There is no test.jpg%3Fv2...

How to make an object slider in django?

django,django-templates
I have written a simple article publishing site in Django 1.8. Here is the model that I'd like to slide: class Article(models.Model): nid = models.IntegerField(default=0) headimage = ImageWithThumbsField(upload_to='images', blank=True, sizes=((200,200),(400,400))) title = models.CharField(max_length=100) author = models.CharField(max_length=100, blank=True) body = models.TextField() teaser = models.TextField('teaser', blank=True) created=models.DateTimeField(default=datetime.datetime.now)...