Menu
  • HOME
  • TAGS

Django-cms Placeholder naming from template variable

django,django-templates,django-cms

From looking through the codebase here: https://github.com/divio/django-cms/blob/develop/cms/templatetags/cms_tags.py#L284 it appears that the 'name' argument to the placeholder template tag is always interpreted as a string, so, it cannot currently be a variable assignment. Its not completely clear what you intend to do here, but I wonder if you should instead look...

Django block inclusion not working. What did I miss?

django,django-templates

Django templates do not use inclusion so much as template inheritance. The idea is you set up a hierarchy of templates, specializing some common thing. For instance: you could have a base.html that has some basic page structure, common to all pages of your website. you could then have a...

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

django,python-2.7,django-templates,django-staticfiles

Try this: STATICFILES_DIRS = ( ... os.path.join(os.path.dirname(__file__),'static'), ) TEMPLATE_DIRS = ( ... os.path.join(os.path.dirname(__file__),'templates'), ) ...

Better errors message if template is missing

python,django,debugging,django-templates

To be honest, I've always used the mechanisms the other posters suggested with a live server. However, since you are looking for a solution that might work in Jenkins and your stack shows you are going through debug.py, I had a look at the debug data there. I notice that...

django error TemplateDoesNotExist

python,django,django-templates

Your problem is with your settings. You currently have: TEMPLATE_DIRS = ( os.path.join(BASE_DIR, 'templates'), ) This is how you set up template directories in Django 1.7.x and below. In Django 1.8.x, change your TEMPLATES [] to read like this: TEMPLATES = [ { 'BACKEND': 'django.template.backends.django.DjangoTemplates', 'DIRS': [ os.path.join(BASE_DIR, 'templates'), ],...

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

django,django-templates

A fairly simple way to do this is to pass in context data from the view instead of using the request.path. Here is a similar example that deals with li items. <ul> <li class="{% if active_tab == 'tab1' %} active{% endif %}"><a href="#">Tab 1</a></li> <li class="{% if active_tab == 'tab2'...

How to translate this raw query to Django ORM

sql,django,django-models,django-templates

Candidate.objects.filter( Q(Q(languagelevel__language__id__in=(1, 2, 3)) & Q(languagelevel__language__level__gte=1)) | Q(Q(languagelevel__language__id__in=(4, 5)) & Q(languagelevel__language__level__gte=3)) | Q(Q(languagelevel__language__id=6) & Q(languagelevel__language__level__gte=2)) )).values('id').annotate(total=Count('id')) values will only return the id of each candidate with a calculated total as total. If you want to get all of the fields (not only id), you can remove .values('id') as: Candidate.objects.filter(...

Django CMS bootstrap navbar always collapsed in IE8

django,twitter-bootstrap,internet-explorer-8,django-templates,django-cms

Had to add respond.js to page, but i thought the cms and django would take care of that

Django template looks up?

python,django,django-templates

It doesn't have one, but the template doesn't know that until it tries. The point the documentation is trying to make is that the template will try all three kinds of lookup, so that you can pass a dictionary, an object, or a list and access them in the same...

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

json,django,d3.js,django-templates,directory

Django doesn't serve up static pages that way. Because every request that goes to the Django server (in your case http:localhost:8888) gets routed through Django's URL Dispatcher (https://docs.djangoproject.com/en/1.7/topics/http/urls/), you need to setup Django url routes to handle EVERY url you might want, otherwise Django will just 404 the request. In...

Get the first image src from a post in django

django,django-templates,django-views

Here's a basic approach you can tweak for your convenience: Add a first_image field to your model: 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) first_image = models.CharField(max_length=400, blank=True) Now all you have to do is populate your first_image field on save, so...

Radio button layout messed up in Django template

html,css,django-templates,radio-button

Changed the above code to the following: <form method="post" action=""> {% csrf_token %} {{ form.bio.errors }}<p> {{ form.bio.label_tag }}{{ form.bio }}<p> {{ form.mobilenumber.errors }}<p> {{ form.mobilenumber.label_tag }}{{ form.mobilenumber }}<p> {{ form.age.errors }}<p> {{ form.age.label_tag }}{{ form.age }}<br> {{ form.gender.errors }} {{ form.gender.label_tag }}<br>{% for radio in form.gender %}<table><tr><label for="{{ radio.id_for_label...

Unable to access upvote/downvote input in a Django template

html,django,django-forms,django-templates

type="input" is not a valid button type. I'd get rid of the hidden input altogether, and change the buttons to inputs: <form method="POST" action="{% url 'vote' %}" class="vote_form"> {% csrf_token %} <input type="submit" name="btn1" value="upvote"> <input type="submit" name="btn1" value="downvote"> </form> Then, in your view, you can use: if request.method ==...

reverse url of the blog article in template

django,django-templates,django-views,django-urls

its either: {% url 'article' article.slug article.pk %} or {{ article.get_absolute_url }} The latter will only work, if in your model you have something like this: class Article(models.Model): slug = models.SlugField() ... def get_absolute_url(self): return reverse('article', args=[self.slug, self.pk]) ...

Django constant argument on URL

django,url,django-templates

If the {% url %} tag you should pass the values for regex groups (the expressions in the round brackets) only so this will work just fine: {% url 'events_from_client' email.value count.value %} ...

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

python,django,forms,django-templates

Having consulted with a few colleagues, it seems the most likely thing to do is this {{ form.password.errors }} <label for="{{ form.password.id_for_label }}"></label> <input id="{{ form.password.id_for_label }}" name="{{ form.password.name }}" placeholder="password" type="password" /> It's a reasonable balance between letting django do the work and so being robust against future changes...

NoReverseMatch at /resetpassword/ in Django

django,django-templates,passwords,reset

Actually your regex for the token parameter is matching a single or multiples commas. You can use <token>.+ for match any character. Also your pattern is looking for a - between the uidb64 and token, and this line {% url 'password_reset_confirm' uidb64=uid token=token %} is passing both parameters without the...

Create angular page in Django to consume data from JSON

angularjs,django,django-templates

You can add the angular app as a simple template view in Django views.py def index(request): return render(request, 'yourhtml.html', {}) urls.py .... url(r'^your_url/$', views.index), .... Then the index.html file can have your angular code...

Display a specific template when Django raises an exception

python,django,exception,django-templates

Most likely such errors will return HTTP 500 server error. In django you can write your own custom view to handle such cases and return your own page with the html that you like. The 500 (server error) view explains writing server error views. There are more types of errors...

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

django,apache,django-templates,mezzanine,imagefield

You can use the .url() method of ImageField. I assume that you have a ForeignKey to User in your Profil model, so the template code should be: <img src="{{ user.profil.user_pic.url }}"> ...

Problems with rendering page on Django framework

python,django,django-templates,django-views

On CategoryNews view add news to render context. This will make news items available in templates. def CategoryNews(request, categoryslug): category = Category.objects.get(slug=categoryslug) news = News.objects.filter(category=category) return render (request, 'news/category_news.html', {'category' : category, 'newsitems': news}) Add named group to category url to make it dynamic. Rewrite url(r'^kids-garden/$', views.CategoryNews, name='category'), to url(r'^category/(?P<categoryslug>\w+)/$',...

Return address in ListView

django,listview,django-templates,django-context

Resolved. {{ dealership.address.address }} ...

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

django,django-templates,django-views,django-urls,django-template-filters

You can just add the fragment identifier right after the URL returned by the {% url %} template tag: <a href="{% url 'home' %}#tips">home</a> ...

Slice and attribute in django template

django,django-templates,slice

If you are accessing a single element of a list, you don't need the slice filter, just use the dot notation. {{ somelist.1.name }} See the docs for more info. ...

Django hosting static files on the server

django,django-templates,django-staticfiles,django-statistics

In production you need first to define STATIC_ROOT and then run collectstatic in order to have your static files collected there. After running collectstatic you should be able to cd to the dir associated to STATIC_ROOT and see the files. EDIT: the code below should be added in he Apache...

Access image urls from Django ForeignKey relationship

django,image,django-models,django-templates,django-views

You only need to provide Object to your template to access ObjectImages. They will be available this way: all_objects = Object.objects.all() context = {'all_objects': all_objects} render(render, your_template.html, context) And in your template, like this: {% for each_object in all_objects %} {% for each_image in each_object.objectimage_set.all %} {{ each_image.image }} {%...

How to make an object slider in django?

django,django-templates

An example using bootstrap's carousel: <!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>Example of Bootstrap 3 Carousel</title> <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.4/css/bootstrap.min.css"> <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.4/css/bootstrap-theme.min.css"> <script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.2/jquery.min.js"></script> <script...

How to loop over datetime range in django templates

python,django,django-templates

You can solve it using custom template tag: Firstly create the file structure. Go into the app directory where the tag is needed, and add these files: templatetags templatetags/init.py templatetags/custom_tags.py The templatetags/custom_tags.py file: from django import template register = template.Library() @register.daterange def daterange(start_date, end_date): start_date = datetime.date.today() end_date = start_date...

objects.all() query not working

python,django,django-templates,django-views

You have to pass context to the html: from django.shortcuts import render from django.http import HttpResponse from TasksManager.models import Supervisor, Developer # View for create_developer def page(request): error = False # If form has posted if request.POST: if 'name' in request.POST: name = request.POST.get('name', '') else: error=True if 'login' in...

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

django,django-templates

I usually set up an application-wide object in my base template that you can extend in other templates if you need: # base.html (upper-most HTML template) . . . <script> var myApp = { staticUrl: '{{ STATIC_URL }}', distributorsSearchDistUrl: '{% url "distributors:search_dist" %}' } </script> </body> Which you can then...

Django non-ASCII chars in template tags values

python,django,tags,django-templates,python-unicode

Try replacing return "Here it is: {my_var}".format(my_var=my_var) by return u"Here it is: {my_var}".format(my_var=my_var) In Python 2.7, "Here it is: {my_var}" is a str object, an encoded string, my_var is a unicode object, a decoded string, when formatting, Python will try to encode my_var so it matches the type of the...

how to have some contexts all over a project?

python,django,django-templates

You could create a context processor in a module myapp.context_processors.py def team(request): team = None if request.user.is_authenticated(): try: # fetch the team managed by the logged in user team = Team.objects.get(manager=request.user) except (Team.DoesNotExist, Team.MultipleObjectsReturned): pass return {'team': team} Add myapp.context_processors.team to your list of context processors in your settings. Then,...

Generating html pages off Django database entries

django,django-templates,django-views

You would need to name both arguments in your regular expression: url(r'^user/(?P<username>\w+)/list/(?P<listname>\w+)/$', mylistpage, name='lists'), More on that on Django documentation: URL Dispatcher: Named groups. Update: answering on the comments, to redirect to 404 if no username or listname, this would be handled in the view. For instance: User.objects.get_object_or_404(username=username) and from...

How to output django_filters.RangeFilter text boxes inline?

django,twitter-bootstrap,django-templates,django-filter

Try this: {{ filter.form|bootstrap_inline }} OR <form action="" method="get" class="form-inline"> To use class="form-inline" on the form element, also change the "|boostrap" template tag to "|bootstrap_inline"....

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

django,django-templates

You don't need to. Django already comes with a forloop.counter, as well as a forloop.counter0. You can use it directly: <tr{{ row.attr_string|safe }}> {% spaceless %} {% for cell in row %} {% if forloop.counter < 4 %} {% include "horizon/common/_data_grid_cell.html" %} {% else %} {% include "horizon/common/_data_table_cell.html" %} {%...

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

python,django,django-templates

You need to follow the instructions in the Code Layout section of the docs, there isn't any way around it. Therefore, you need to include {% load my_template_tags %} inside the template string, and include the app that includes the templatetags/my_template_tags.py module in your INSTALLED_APPS setting. You may find it...

How to compare inner for iterator with outer for iterator

python,django,django-templates

Don't include the curly braces when using a variable inside a template tag: {% if forloop.parentloop.counter == forloop.counter %} Including {{f.fname}} doesn't make sense if fs is the list ['a', 'b', 'c']. Those strings don't have an fname attribute. Finally, including {{ item}}, means that the final item in the...

How to resolve the following HTML error?

html,html5,django-templates

HTML tags must be structured in a directly hierarchic manner. Closing a tag that was opened inside previously closed elements is incorrect and will often produce errors and issues. Enclose the form inside the table data, like this: <td class="right"> <form method="post" action="." class="cart"> <label for="quantity">Quantity:</label> <input type="text" name="quantity" value="{{...

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

python,django,django-models,django-templates,django-views

You haven't said what you have tried to do to solve this, why you think it's "way overly complicated", or why it's causing you frustration. The thing to understand is that a view is entirely responsible for a page, ie the view creates the entire response when a URL is...

How to pass around variables without url parameters in Django?

django,django-templates,url-parameters

You can use GET parameters. Example: <a href= "{% url .....%}?class_id={{c.class_id}}">{{ c.class_id }}</a> To retrieve the parameter from the Django view, use: param_value = request.GET['param_name'] ...

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

django,django-models,django-templates

{{ object.pub_date|date:"D d M Y" }} {{ object.pub_date|time:"H:i" }} all options explained: documentation...

Template Tag in Javascript

javascript,django,django-templates,django-template-filters

You might consider using an assignment tag: from collections import Counter @register.assignment_tag(takes_context=True) def get_resource_types(context): values = dict(Counter(list(map(str, ResourceType.objects.values_list('data_type', flat=True))))) return {'resource_types': values} This will give you a count of each data_type string in the values list, such as: {'data type 1': 3, 'data type 2': 10, 'data type 3': 47}...

Django include template tag alternative in python class

python,django,django-templates

I think you might be looking for render_to_string. from django.template.loader import render_to_string context = {'foo': 'bar'} rendered_template = render_to_string('template.html', context) ...

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

django,django-templates

Your router name has a number in it, which doesn't match your regex. You should probably use \w, which matches all alphanumeric characters. r'rollbackAAI/(?P<router_name>\w+)$' ...

Show message when there's no excerpt - Django templates

python,django,django-templates,django-template-filters

Your problem is with your if/else tags. You have this: {{ % if ... %}} ... {{% else %}} ... First off, you need to surround if/else by {% %}, not {{% %}}. Secondly, you don't have an endif. An if/else block should look like this: {% if ... %}...

get rows count from django_tables2

django,django-templates,django-tables2

You can check if there are any rows using the table's rows attribute {% if participations_table.rows %} {% render_table participations_table %} {% endif %} In the django template, you can get the number of rows with the length filter {{ participations_table|length }} Or in the view, simply len(participations_table.rows) Alternatively, you...

Django - Template Tags, display
    -

python,html,django,django-templates

get_music_tags returns a queryset - a collection of (in this case) all Music objects. The queryset itself doesn't have isactive, audio or cover properties: only the individual items inside the queryset do. You need to iterate through them: {% get_musikk_tags as all_musikk %} {% for musikk in all_musikk %} {%...

django does not match pattern called in template

python,regex,django,django-templates,django-urls

The clue is in the error message, specifically and keyword arguments '{}' not found.. Your pattern has keyword matching, the result will be mapped to the keyword team_id, however you are passing a positional argument of 1 (that's why your team id is showing in the tuple (1,)). To fix...

How to deal with my login_required url?

python,django,django-templates

Firstly remove the dollar sign when including other url patterns. url(r'^', include('distributors.urls', namespace='distributors')), Secondly, you are missing a closing bracket where you are using login_required. url(r'^links/$', login_required(views.LinkListView.as_view()), name='links'), ...

Image input missing from POST request

html,django,post,django-templates

It turns out that I somehow I copied the rendered HTML wrong! The real problem was that the form id used in input was incorrect and this was the reason for the file not getting uploaded.

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

It sounds like what you want is something more along the lines of: {% with foo=excessively_verbose.chain_of_long.nested_references %} {% if foo %} {{ foo }} bar {% endif %} {% endwith %} ...

Button updates text of first element instead of selected element

javascript,jquery,html,django,django-templates

Every photo has the same id for its like count: {% for photo in photos %} <a href="#" id="like_count">0</a> {% endfor %} Therefore, only the first is recognized as the 'real' #like_count Since you have a primary key for the photo, you could make the ids distinct by incorporating the...

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

python,django,django-templates,django-views

I had success with the following snippet by GitHub user mhulse. This allowed me to call {% allow_tags ad_tag %} in my template and process any Django template tags found in that field. from django import template from django.utils.safestring import mark_safe register = template.Library() # http://www.soyoucode.com/2011/set-variable-django-template # http://djangosnippets.org/snippets/861/ # http://stackoverflow.com/questions/4183252/what-django-resolve-variable-do-template-variable...

Looping in django template with variable parameter

python,django,django-templates

This how I would do it. 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) c.update({'materials': material_array}) return render_to_response('add_material.html', c) else: return HttpResponseRedirect('/user') template {% for material in materials %} <tr> <td>{{ material.subject }}</td> <td>{{ material.topic }}</td> <td>{{ material.user.username }}</td>...

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

python,django,django-templates

Use the {% include ... with ... %} syntax: {% for car in user.favorite_cars.all %} {% include "car.html" with name=car.name year=car.year %} {% endfor %} Another alternative is the {% with %} tag: {% for car in user.favorite_cars.all %} {% with name=car.name year=car.year %} {% with color=car.color %} {% include...

F() Expression strange behavior with Django

python,django,django-models,django-templates,django-template-filters

random.choice does not guarantee to produce non-repeating items. import random random_camps = random.sample(current_campaigns, amount) is the way to go here. Update If you're worried about the speed, this question addresses quick random row selection in postgres....

How Django's url template tag works?

django,django-templates,templatetags

You've misunderstood a few things here. In particular, you've mixed up the name of the URL pattern, and the parameters you need to pass to it. For instance, if you wanted to capture the ID of a post in your blog and pass it to a detail view, you would...

Why is Django widgets for TimeInput not showing

django,django-forms,django-templates,django-views

The Django admin uses AdminTimeWidget to display time fields, not the TimeInput widget that you are using in your code. There isn't a documented way to reuse the AdminTimeWidget outside of the Django admin. Getting it to work is very hacky (see the answer on this question, which is probably...

Accessing Specific Dictionary Values by Key in Django Template

python,django,django-templates

You cannot do that out of the box, but you can do with a custom template tag. Please see this old Django ticket for a possible solution, and for the reason the idea got rejected:Accessing dict values via a value of a variable as key...

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

django,django-forms,django-templates,dry

There can be two ways to accomplish this:- 1) Make the name field required inside the model by adding 'blank=False'. name = models.CharField(blank=False) 2) If you don't want to modify blank setting for your fields inside models (doing so will break normal validation in admin site), you can do the...

Substring in a django template? [duplicate]

django,django-templates

Use the slice template filter: {{ obj.name|slice:"0:3" }} ...

Django view variable not presenting any data in html

python,django,django-templates

Can you try like this ? in python: def index(request): context = "Temp = {0} *C".format(sensor.read_temperature) return render(request, 'hud/index.html', {"context": context}) in template: <h1>{{ context }}</h1> you should send variables with dictionaries {"context": context} is our dictionary. In Django templates, data passed by key, so we can get it with...

How to access all dictionary keys in template

python,django,django-templates

check without using the items.keys, just {% if i in mydict %} ok {% endif %} or, if you really want to use keys {% if i in mydict.keys %} ok {% endif %} ...

Insert separator only if didn’t insert one before

python,django,django-templates

You should compose the condition. It looks simple, perhaps is not this that your are asking for. {% for product in product_list %} {% if not forloop.first and product.tracks %} <li class="separator"></li> {% endif %} {% for track in product.tracks %} <li>{{track}}</li> {% endfor %} {% endfor %} If this...

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

django,django-models,django-templates

Is that what you are looking for ? {% for article in user.article_set.all() %} {{article.article_title}} {% endfor %} Maybe you will need to prevent this code if user is anonymous : {% if user.is_authenticated() %} {% for article in user.article_set.all() %} {{article.article_title}} {% endfor %} {% else %} # Do...

Django does not render my forms' fields

django,django-models,django-forms,django-templates,django-views

Your form inherits from forms.Form, which does not know anything about models and ignores the Meta class. You should inherit from forms.ModelForm.

Render in django can't passing an argument

django,django-forms,django-templates,django-views

The render statement isn't expecting a trailing comma like when you're defining a tuple, which is most likely what's causing the error, however your code could use some refactoring.... from django.contrib.auth.decorators import login_required from django.contrib.auth.models import User from django.core.urlresolvers import reverse from django.http import HttpResponseRedirect # assuming you're using your...

How to tell a Django view who called it?

django,django-templates,django-views

You can have a part of the URL to be used as a parameters. Each parameter will be set based on the regex provided. an example here. One view can handle all your urls that contain the three parameters you mentioned. url(r'^members/near/(?P<from_uid>\d+)/profile/(?P<to_uid>\d+)/from//(?P<view_name>\W+)/$', MyView.as_view(), name = 'my_named_view') Then in your view...

Operational error while using stripe with profile app

django,python-2.7,django-templates,stripe-payments

It's kind of weird. But when I followed "No Such Table error" and tested DB it was still empty. So this time I deleted DB but also migrations. Problem is fixed and its just working fine.

forloop.last not working in Django

django,django-templates

I suspect that the last person in loop has person.actionid != visit.actionid. So the check for forloop.last is not executed.

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

python,django,django-templates,django-views

You cannot do this like that. Views are glorified functions. They have a single entry point (dispatch()) that is invoked by Django internals, and invokes the correct method on itself, depending on the HTTP method (here, get()). Casting the view to a string will just display its name, not call...

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

django,django-templates

Try this: import re regex = re.compile(r'\n+') regex.sub('\n', template) This will replace consecutive newlines with single one....

Templates Django (Does not exist at/)

python,django,templates,django-templates,views

P.S: Please edit your question instead of adding an answer to your question with a question :P Coming to the error, From your directory structure, you have two template directories, one in the main project and other in the polls app at mysite/polls/mysite/. Django is looking for templates in the...

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

django,django-templates

All the images were set as featured and that was causing issue. Thanks for help @f43d65. Also consulted project on Github at: https://github.com/codingforentrepreneurs/ecommerce/blob/master/ecommerce/templates/products/single.html.

Django - How do form template tags work?

django,django-forms,django-templates

{{ form }} is not a template tag, it is a context variable. By default Form instances are rendered using the Form.as_table() method. So you have to pass such variable to the template in the render() call: from django.shortcuts import render def add_task(request): if request.method == "POST": form = addtaskForm(request.POST)...

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

You need to define a custom template tag which returns the type of data. from django import template register = template.Library() @register.filter def data_type(value): return type(value) Then use it inside your template like this: {% for key, value in leasee.items %} <p> {{key}} </p> <ul> {%if value|data_type == 'dict' %}...

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

python,django,django-templates

The solution that @catavaran answered before works: using a relative import like from ..utils import myfunction The problem was that the templatetag module recaptcha.py and the django app recaptcha had both the same name, so when I type from recaptcha import utils it tries to find it from itself instead...

Passing checkboxes values to view in django

django,checkbox,django-templates,django-views

views.py if request.method == 'POST': #gives list of id of inputs list_of_input_ids=request.POST.getlist('inputs') Hope this solves pretty much of your problem.Check out this link Checkboxes for a list of items like in Django admin interface ...

Correct

django,django-forms,django-templates,django-views

Since your form is submitting to the same url, you can simply use action="". If you prefer, you can use action="/surveyone/" If you don't want to hardcode the url in your template, then you need to name your url patterns: url(r'^surveyone/$', SurveyWizardOne.as_view([ SurveyFormIT1, SurveyFormH, ... ]), name="survey_one"), You can then...

Django-Angular's djng_rmi template tags do not expand

django,angularjs,django-templates

The {} for the function declaration confuse django when it looks for tags to inject. By moving it outside of the function declaration, it should work fine. {% load djangular_tags %} … <script type="text/javascript"> var tags = {% djng_current_rmi %} my_app.config(function(djangoRMIProvider) { djangoRMIProvider .configure( tags ); }); </script> ...

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

json,django,django-templates,django-rest-framework

model.py: class Day(models.Model): date = models.DateField(default=date.today) def get_todo_list(self): return self.day_todo_set.order_by('-id')[:5] class ToDo(models.Model): date = models.ForeignKey(Day, related_name="day_todo_set") name = models.CharField(max_length=100) very_important = models.BooleanField(default=False) finished = models.BooleanField(default=False) In serializers.py class ToDoSerializer(serializers.ModelSerializer): class Meta: model = ToDo field = ('id', 'date', 'name', 'very_important', 'finished') class...

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

django,django-templates,django-views,html-form

It's a bad idea to try and parse/modify the existing URL. But there's no reason to. Your template presumably already has access to the post itself, so you should use this to construct the URL via the normal {% url %} tag. <form action="{% url "submit_comment" post_id=post.id %}" method="POST"> assuming...

How do i cache bust with Django's staticfiles?

django,django-templates,django-staticfiles

To solve the encoding either write your own version of the static tag or simply move the parameters beyond the tag. {% load staticfiles %} <img src="{% static 'poll/img/test.jpg' %}?v2"> ...

How to create Django form for a photo grid?

python,django,django-forms,django-templates,django-views

On the contrary, this is exactly a job for formsets: 'multiple identical form "components" all within the same form' is precisely what they are. class ReviewPhotosForm(forms.Form): DECISION_CHOICES = ( ('approve', 'Approve'), ('reject', 'Reject') ) ROTATE_CHOICES = ( ('none,', 'None'), ('right', 'Right'), ('left', 'Left'), ('flip', 'Flip') ) # hidden field to...

Django CMS losing data from draft to live

django,python-3.x,django-templates,django-cms

You need to implement a copy_relationships method within your plugin model. When publishing you are literally duplicating the model row. You need to tell the related model how to copy its records and associate them to the correct instance. The CMS allows you to define a method copy_relations which you...

How should I show results of BeautifulSoup parsing in Django?

python,django,django-templates,django-views,beautifulsoup

what's the result that you print out? have you try to use this? soup.title.string if you have to send html in to templates try: {% autoescape off %}{{ title }}{% endautoescape %} ...

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

python,django,forms,django-templates,django-urls

<script> function changeAction() { var profile_form = document.getElementById('profileform'); if(profile_form) { var txt = "http://www.example.com/"; var i; for (i = 0; i < profile_form.length; i++) { txt = txt + profile_form.elements[i].value + "/"; } profile_form.action = txt; }} </script> And in your html, you need something like this: <form action="" method="get"...

Accessing list item in django template

python,django,django-templates,django-template-filters

The best option is to use choices attribute for the rating field: RATING_CHOICES = list(enumerate(['', 'Disappointed', 'Not Promissing', 'OK', 'Good', 'Awesome'])) class Review(models.Model): ... rating = models.IntegerField(..., choices=RATING_CHOICES) And then use it in the template: {{ review.get_index_display }} The other option is to use custom template filter: @register.filter def get_by_index(lst,...

Check if member value is different than in previous iteration

python,django,django-templates

Use the {% ifchanged %} template tag: {% for membership in group_memberships %} {% ifchanged %} <h1>{{ membership.product.name }}</h1> {% endifchanged %} <p>{{ membership.group.name }}</p> {% endif %} ...

Django - View Other user profile

django,python-3.x,django-models,django-templates,django-views

Django has a default set of permissions (change, add, delete) for each model. You can use them in your template to hide the buttons or use a simple check if the user shown is also the user viewing the page. {% if perms.accounts.change_user %} Edit {% endif %} or {%...

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

django,django-templates,django-views

Index View First of all, when you are using Django Generic List View the object list in the template is called object_list. Check the above link to see django documentation. So to show all the IceCream names in the Index template you should do: {% for item in object_list %}...

Django template rendering extend tag incorrectly

django,django-templates

If you extends a base.html template, no content not surrounded by {% block %} will be rendered at all. You could create additional {% block precontnet %}{% endblock %} in base.html, and wraps Pink/Yellow/Red in user_links.html Or you can put Pink/Yellow/Red in {% block content %} if user_links.html and use...

Using image in a template django

django,django-templates

Something that I would like to bring to your notice. static stores your css,js and images that are needed for the website frontend. media stores all the images uploaded by the user. So, in your settings define, MEDIA_URL = 'media/' Then, inside your template append /{{MEDIA_URL}} in front of {{item.photo}}....