w3hello.com logo
Home PHP C# C++ Android Java Javascript Python IOS SQL HTML videos Categories
Django, how to use 'group by' and 'max' to get complete row in queryset and display related items in template
Your views.py code is problematic here. It will return only the values of the user columns with annotations, rather than returning an actual queryset which allows you to walk through the relation between Talk_comment and Talk. I believe altering that line to the following will get you closer to your goal. qs = Talk_comment.objects.annotate(max_id=Max('id')).order_by('-max_id')

Categories : Django

Template Django application extending template django project
django-admin.py collectstatic Read docs Files are searched by using the enabled finders. The default is to look in all locations defined in STATICFILES_DIRS and in the 'static' directory of apps specified by the INSTALLED_APPS setting.

Categories : Django

django.template.loaders.app_directories.Loader fails to find the template file
Add them to your settings file. import os PROJECT_ROOT = os.path.dirname(os.path.abspath(__file__)) TEMPLATE_DIRS = ( os.path.join(PROJECT_ROOT, "/apps/myapp/templates/"), )

Categories : Django

Django: Is there a way to display a variable in a Django template like foo.inspect in Rails?
There is a similar thread that has a number of good suggestions. If {% debug %} is unappealing, then it might be easier to inspect the variables in the view prior to the template rendering the page with the variables in question.

Categories : Django

Django: edit template inside another template
If you want your user to be able to edit the template, then you should store the template in the database. There are some packages that do this for you, but it's easy enough to do by yourself # in models.py class EmailTemplate(models.Model): name = models.CharField(max_length=50) template = models.TextField() Then when you need to send an email, you can render it like so: # in views.py from django.template import Template, Context #in your view email_template = get_object_or_404(EmailTemplate, id = template_id) #You should know how to get this somewhere template = Template(email_template.template) email_body = template.render(Context({'my_context':'my_context'}))

Categories : Django

getting template syntax error in django template
Since your artwork_url is a list, the reasonable way would be to access it like this: artwork_url.forloop.counter but it won't work. The Django template language isn't that advanced unfortunately. You should access it like this. {% for track in tracks %} <li><div class="genre-image"> <img src="{{ track.artwork_url }}"> </div> {% endfor %} But that requires that the tracks are mutable and require you to change it in the backend. So if you're not able to modify the track you'd have to implement a custom template filter something like this {{ track.artwork_url|myFormatter:'t300' }} A very small and simple formatter: @register.filter(name='myDate') def myFormatter(value, arg): if arg == 't300': arg = 't300x300' return str(value).replace("lar

Categories : Python

How to post to a view in django from a django template?
In the template unsub.html rendering the form with the button, you should pass the url of your view using the reverse method from django.code.urlresolvers import reverse def unsub_view(request, viewid): if request.method == 'POST': if user_is_subscribed: #Unsubscribe the user. submit_url = reverse('unsub_view', viewid) return direct_to_template(request, '/app/unsub.html', {'user': user, 'submit_url'}) else: #Show error meessage. in your template you can then render the form like follows : ... <form method='post' action='{{ submit_url }}'> {% csrf_token %} <input type="hidden" value="{{ user_id }}" name="user_id" /> <input type="submit" value="unsu

Categories : Python

Using a Radio Button Group in an Editor Template
To add your radio buttons to a group you could change your code to: @Html.RadioButton("GROUPNAMEHERE", "LABEL", BOOLVALUEFORCHECKED) Not sure if you actually need the RadioButtonFor in this instance. EDIT: If you do need RadioButtonFor, try this: @Html.RadioButtonFor(x => x.EVote, true, new { Name = "GROUPNAME" })

Categories : C#

Django Template / on which template I am and using IF for this template
You can use block tag for this purpose. If you find yourself duplicating content in a number of templates, it probably means you should move that content to a {% block %} in a parent template More documentation here in base.html {% block footer_content %} {# contents here #} {% endblock %} and in index.html {% block footer_content %} {# this overwrites the base footer_content to empty block #} {% endblock %} This would remove the contents only in index.html and available on all other pages that inherit from base.html Now, if you wish to add more content to certain pages, {% block footer_content %} {{ block.super }} {# more content here #} {% endblock %}

Categories : Django

Group-By with Django Model
You can group with itertools: from itertools import group_by cs = Compared.objects.all().order_by( 'product__pk' ) ) for p, l in groupby( l , key = lambda x: x.store.pk ): print p.pk #the produt name print [ s.pk for s in l ] #stores pks print ( p.pk, tuple( s.pk for s in l ) ) Notice: syntax not tested. Notice: this grouped 'in memory' but in database. Notice: order by is important.

Categories : Django

Django Group By Weekday?
Well man I did an algorithm this one brings you all the records since the beginning of the week (Monday) until today for example if you have a model like this in your app: from django.db import models class x(models.Model): date = models.DateField() from datetime import datetime from myapp.models import x start_date = datetime.date(datetime.now()) week = start_date.isocalendar()[1] day_week =start_date.isoweekday() days_quited = 0 less_days = day_week while less_days != 1: days_quited += 1 less_days -= 1 week_begin = datetime.date(datetime(start_date.year,start_date.month,start_date.day-days_quited)) records = x.objects.filter(date__range=(week_begin, datetime.date(datetime.now()))) And if you add some records in the admin with a range between June 17 (Monday) a

Categories : Python

Django simple GROUP BY
You should use values() if you want to specify grouping fields: Book.objects.values('category').annotate(total_messages=Count('title')) Here's the query it produces: >>> Book.objects.values('category').annotate(total_messages=Count('title')).query.__str__() Out[11]: u'SELECT "my_app_book"."category", COUNT("my_app_book"."title") AS "total_messages" FROM "my_app_book" GROUP BY "my_app_book"."category"'

Categories : Django

How to use ListView, Layout, item and group template in asp.net with twitter bootstrap
I figured out how to achieve this. <asp:ListView ID="category1" runat="server"> <LayoutTemplate> <div class="categories row"> <asp:PlaceHolder ID="itemPlaceholder" runat="server" /> </div> </LayoutTemplate> <ItemTemplate> <div class="span4"> <div class="category1"> <img class="image1" alt="No Image" src="CatalogueImages/<%# Eval("ImageName") %>" /> </div> <div class="details"> <div class="button"> <button class="square" type="button">Add to Cart</button>

Categories : Asp Net

Django "with" template tag
If photograph_set is the reverse relationship of a ForeignKeyField or if it's a ManyToManyField, you'll need to do {% with album.photograph_set.all.count as numPhotos %}

Categories : Django

how to create a group permission in django
The following answer helped me in setting up groups. from django.contrib.auth.models import User, Group, Permission from django.contrib.contenttypes.models import ContentType content_type = ContentType.objects.get(app_label='myapp', model='BlogPost') permission = Permission.objects.create(codename='can_publish', name='Can Publish Posts', content_type=content_type) user = User.objects.get(username='duke_nukem') group = Group.objects.get(name='wizard') group.permissions.add(permission) user.groups.add(group)

Categories : Django

Django group by id then select max timestamp
How will it work? You neither have filter nor distinct to filter out the duplicates. I am not sure if this can be easily done in a single django query. You should read more on: https://docs.djangoproject.com/en/dev/ref/models/querysets/#django.db.models.query.QuerySet.distinct https://docs.djangoproject.com/en/1.4/topics/db/aggregation/ If you can't do it in 1 raw sql query, you can't do it with an OR mapper either as it's built on top of mysql (in your case). Can you tell me how you would do this via raw SQL?

Categories : Python

Django ORM - Get latest record for group
Put your values clause before the annotate. From the aggregation docs: If the values() clause precedes the annotate(), the annotation will be computed using the grouping described by the values() clause. However, if the annotate() clause precedes the values() clause, the annotations will be generated over the entire query set. In this case, the values() clause only constrains the fields that are generated on output. So this should do it: Meetup.objects.values('language').annotate(latest_date=Max('date'))

Categories : SQL

How multiply and sum two colums with group by in django
Here's what you can do: Triangle.objects.filter(type="normal").values('color').annotate(amount=Sum('id', field="width * height") This will produce the following query (I've simplified for readability): SELECT color, sum(width * height) as amount FROM triangle WHERE type = 'normal' GROUP BY color Note: I've assumed color is a field of Triangle model as other fields.

Categories : Python

Django INNER JOIN with GROUP BY queryset
The django annotation features will do this: from django.db.models import Count tests.objects.annotate(Count('tat')) Optionally, use values_list to select down to just the abbreviation and count, if that's important.

Categories : Python

Django group by dates and SUM values
Hmm you are using Count, you should use Sum, and values() will determine what goes into GROUP BY so you should use values('datetime') only. Your queryset should be something like this: from django.db.models import Sum values = self.model.objects.filter( datetime__range=(self.dates[0], self.dates[1]) ).values('datetime').annotate(data_sum=Sum('data')) although I'm not so sure about the order of the filter(), so it could be this: values = self.model.objects.values('datetime').annotate(data_sum=Sum('data')).filter( datetime__range=(self.dates[0], self.dates[1]) ) I guess you would wanna try both then. If you want to see the raw query of those queryset, use Queryset.query: print self.model.objects.filter( datetime__range=(self.dates[0], self.dates[1]) ).values('datetime').a

Categories : Mysql

Django template for loop
You are passing a string instance.category into the template and then iterating over it's chars. Instead, pass a list to the template: instance.category.split() which will split your words words words string into the list ['words', 'words', 'words']: >>> s = "words words words" >>> s.split() ['words', 'words', 'words'] Or, you can define a custom filter that will split a string into the list: from django import template register = template.Library() @register.filter def split(s, splitter=" "): return s.split(splitter) Then, use it in the template this way: {% for icon in instance.category|split %} <p>{{ icon }}</p> {% endfor %}

Categories : Python

Mouse Over in a django template
There is no string formatting in django templates as there is in python. There is also a template tag which is able to retrieve todays date (https://docs.djangoproject.com/en/dev/ref/templates/builtins/#now). Hope this leads into the right direction. You could try something like this: <span class="green_box" onmouseover="I am Green and today is {% now "d-n-Y" %}">

Categories : Python

Handling u'x00' in django template
Django's templating considers unicodes to be strings; you don't need the u prefix. You used the wrong charset on import; you need to set the charset to UTF-16LE first. bcp "helpfully" outputs NUL rather than an empty string in CSV where the original field is NULL; either tell bcp to knock it off, or perform an UPDATE query that sets each field to NULL where it's equal to ''.

Categories : Python

Set session value in Template Django
I would personnaly use the following view function: def changeLang(request): request.session['lang'] = request.GET['lang'] #'en/' or 'fr/' etc... return render_to_response(request.session['lang'] + 'home.html', {}, RequestContext(request)) Where I have my templates folder ready for the different options for lang. I'm quite aware that django supports internationalization, but it's always more accurate to build a version for each language, especially if one of them is a Right To Left language, which is my case.

Categories : Django

raw template comes up in the screen at django
Yes the problem is that on the templates you have to use {} instead of () for template tags and {{}} for variables {% extends "base.html" %} {% block content %} {% for post in object_list %} <h1>{{ post.title }}</h1> <div class="post_meta"> on {{post.created}} </div> <div class="post_body"> {{post.body|safe|linebreaks}} </div> <div class="tags"> {% for tag in post.tags.all %} <a href="blog/tag/{{tag}}">{{tag}}</a> {% if not forloop.last %}, {% endif %} {% endfor %} </div> {% endfor %} {% endblock %}

Categories : Django

How to add my own html template in django
Template files should go in the templates folder. And DIRNAME has the path to the settings.py. Should probably be something like: DIRNAME = os.path.join(os.path.dirname(__file__), '..') TEMPLATE_DIRS = ( os.path.join(DIRNAME, 'templates/'), } And make sure your index.html is in the templates folder.

Categories : Python

URL name in django template.if statement
Django has this nice built-in feature that you can assign the url to a variable and then use it: {% url 'myview' as my_view %} {% if request.path == my_view %}

Categories : Django

Django humanize outside of template?
Yes you can Lets say you want to call naturalday in views.py you would do from django.contrib.humanize.templatetags.humanize import naturalday natural_day = naturalday(value) You can refer to the source code here for the signature, and options

Categories : Python

how to get template working in django?
As you can see in the Django documentation, django.template.loaders.app_directories.Loader looks for template files in a directory named templates inside the app directory. You said that your template is in "polls/template/polls/index.html", but it should be in "polls/templates/polls/index.html" (notice the added s to templates).

Categories : Django

how to get day name from queryset in django template?
There is a Django date template filter: {{ model.field|date:'l' }} Docs here.

Categories : Python

Error when using django.template
You can't access and run django projects from python shell. Django doesn't know what project you want to work on. You have to do one of these things: 1. python manage.py shell 2. Set DJANGO_SETTINGS_MODULE environment variable in your OS to mysite.settings 3. Use setup_environ in the python interpreter: from django.core.management import setup_environ from mysite import settings setup_environ(settings) The first one is easiest and best method. Run your code in the django shell.

Categories : Django

How to group by events by year and month in django ORM?
I can show you how to group them separately. This is how I would go about it, but please note that my knowledge of django is not the best in the world. Event.objects.filter(end_date__year=2013) This way you will get all the events in 2013. You can further filter them to get the month. Event.objects.filter(end_date__year=2013).filter(end_date__month='01') This would get you all the dates in February. You could simply use a ModelManager to manage these custom queries, since you will be doing them a lot, and then you can just call them in your views. You can make a ModelManager like so: class EventManager(models.Manager): def get_by_year(self, year): Event.objects.filter(date__year=year) And you can simply call it by, Event.objects.get_by_year(2013). You can do this af

Categories : Django

Django template not iterating through list
IMO Courses looks like this: [[[a,b,c],[d,e,f]]] Try this courses = [] comp_course = [] for payment in transactions: if payment.payment_type == "1": unit = Units.objects.get(webducate_id=str(payment.course)) comp_course.append(str(unit.course.webducate_id)) units = Units.objects.filter(course=unit.course) unit_list = [] for unit in units: if unit.webducate_id == payment.course and payment.successfull == "1": courses.append([str(unit.course.webducate_id),'1',str(unit.webducate_id)]) else: courses.append([str(unit.course.webducate_id),'0',str(unit.webducate_id)]) comp_course = list(set(comp_course)) return render_to_response('student-account.html', {'Courses': courses, 'Comp_Course': comp

Categories : Python

Django using template tag to determine which objects should appear
You may want this using for ... empty <div> {% for question in q %} {{question.question}} {%empty%} <div> {% for f in formset %} {{f}} {% endfor %} </div> {% endfor %} </div>

Categories : Django

Django template indentation guideline
Depending your editor, there are ways to set a specific indent width for HTML files. As for the Django tags, it is actually a good thing not to not add a indent level. See that example: <ul> {% for item in items %} <li>{{ item }}</li> {% endfor %} </ul> Would be rendered like so: <ul> <li>Bacon</li> <li>Ninja</li> <li>Tumbleweed</li> </ul> And we do not want the two levels of indent. Instead: {% block content %} <ul> {% for item in items %} <li>{{ item }}</li> {% endfor %} </ul> {% endblock content %}

Categories : Django

Django don't translate several words in template
The string is marked as fuzzy and thus not included by Gettext in compiled translations (which are generated by compilemessages). The strings is usually marked as fuzzy once there was some change in original string, but there might be other reasons as well.

Categories : Django

Django template dir strange behaviour
You specified templates/home.html instead of just home.html. A template name will be appended to a TEMPLATE_DIRS, so /foo/templates/ as TEMPLATE_DIRS will become /foo/templates/templates/home.html if templates/home.html is a template name. Instead, the template name should be just home.html and the resulting template path would be /foo/templates/home.html which is correct.

Categories : Python

What is the right way to check for one or more postbacks in a Django template?
Generally it is a bad practice to include any logic in to your django templates. Templates in django are used only to represent things that has been calculated/processed by your view function. You should do it in your view function eg. using sessions: #----views.py------ from django.shortcuts import render from forms import MyForm def someview(request): form = MyForm() if not 'postbacks' in request.session: request.sesson['postbacks'] = {} if request.path not in request.sesson['postbacks']: request.sesson['postbacks'][request.path] = 1 if request.method == 'POST': form = MyForm(request.POST) if not form.is_valid(): request.sesson['postbacks'][request.path] += 1 else: request.sesson['postbacks'][request.pa

Categories : Python

How to override template in django-allauth?
I eventually resorted to loading my app before django-allauth. In settings.py: INSTALLED_APPS = ( ... 'myapp', 'allauth', 'allauth.account' ) This solution goes against what's presented in example app, but I was not able to solve it in other way.

Categories : Python

How to set cookie in Django and then render template?
def index(request, template): response = HttpResponse('blah') response.set_cookie('id', 1) id = request.COOKIES.get('id') return render_to_response(template,{'cookie_id':id})

Categories : Django



© Copyright 2017 w3hello.com Publishing Limited. All rights reserved.