Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Django django.contrib.auth.views.password_reset_confirm error during template rendering
I am implementing a user password reset using django views and I am getting some error with django.contrib.auth.views.password_reset_confirm The link to reset the password comes through e-mail : MIME-Version: 1.0 Content-Type: text/plain; charset="utf-8" Content-Transfer-Encoding: 7bit Subject: Password reset on 127.0.0.1:8000 From: webmaster@localhost To: progpyftk@yahoo.com Date: Thu, 06 Oct 2016 19:01:30 -0000 Message-ID: <20161006190130.10100.76186@PEAMV57.exprogroup.local> You're receiving this email because you requested a password reset for your user account at 127.0.0.1:8000. Please go to the following page and choose a new password: http://127.0.0.1:8000/account/password-reset/confirm/Mw/4fx-63795155cddbbad87a79 / Your username, in case you've forgotten: Gileno Thanks for using our site! The 127.0.0.1:8000 team When I follow the link I got the following error: TypeError at /account/password-reset/confirm/Mg/4fx-ee6f1fadc877a2279bdc/ string indices must be integers return get_password_validators(settings.AUTH_PASSWORD_VALIDATORS) File "C:\Python34\lib\site-packages\django\contrib\auth\password_validation.py ", line 29, in get_password_validators klass = import_string(validator['NAME']) TypeError: string indices must be integers [06/Oct/2016 16:02:59] "GET /account/password-reset/confirm/Mw/4fx-63795155cddbb ad87a79/ HTTP/1.1" 500 201517 the password_reset_confirm.html {% extends "account/base.html" %} {% block title %}Reset your password{% endblock %} {% block content %} <h1>Reset your password</h1> <!-- We check if the provided link is valid. Django reset password view sets this variable and puts it in the context of this template. If the link is valid, we display the user password reset form. --> … -
How to get actual line number of where python exception occurred?
I have the following python decorator in my file decorators.py def catch_exceptions(function): #Line #1 @wraps(function) #Line #2 def decorator(*args, **kwargs): #Line #3 try: #Line #4 return function(*args, **kwargs) #Line #5 except Exception as e: #Line #6 exc_type, exc_obj, exc_tb = sys.exc_info() #Line #7 fname = os.path.split(exc_tb.tb_frame.f_code.co_filename)[1] #Line #8 print "E=%s, F=%s, L=%s" % (str(e), fname, exc_tb.tb_lineno) #Line #9 return decorator #Line #10 In another file my_file.py, I use the catch_exceptions decorator like this: from decorators import catch_exceptions #Line #1 @catch_exceptions #Line #2 def my_method() #Line #3 print (10/0 - 5/0) #Line #4 When I run it, I get the following output: E=integer division or modulo by zero, F=decorators.py, L=5 Instead of it reporting the exception location as decorators.py, line #5, How can I get it to report the actual file and line number of where the exception originally occurred? That would be line #4 in my_file.py. -
Trouble with linebreaks in Django templates using a SQL database
Okay so I had a project that was passed to me. My school adviser is interested in adding bullet lists with line breaks to the output text display for a online quiz. The quiz is powered via django and sqlite3. I am very new to django and db handling. right now I have this as my html template code: <head> <body> <div id="container"> <h2> blank Survey Question {{q.snum}} </h2> <!-- It appears that {{q.snum}} isn't being used--> <div class="question"> <span id = qspan> {{surv.text}} </span> <br> <br> <span id = m_info> {{surv.more_info|linebreaks}} </span> </div> <div id="ready_set_go" class "gq"> </div> <div id="Back_Button" class "Back"> </div> <div id="debug" data-gameid="{{g.id}}"></div> </div> </body> </html> The linebreak filter in the m_info works per say. However, the output is this: <p> "<pre>{{Examples: Consumables, energy, ect..'\*well''\• Hello People'\ • I miss you' }}</pre>" </p> I have tried a multitude of ways manipulating the text in the db table, but it seems to throw it in quotes and not linebreak at all. Lastly, it should be noted that I wrote a dummy string to test the linebreaks functionalalty but that also did not work. example {{'hello \n world'|linebreaks}} I apologize if this is coming off very noobish. -
How to use react build websites without using react-router ?
I'm building a website with Django and react, and since Django itself has a routing system, and I don't want to discard that, so I decide not to use javascript routing libraries. I'm using webpack to bundle my files, but since I'm not using react router, there's a lot of webpack entry files, and a lot of bundled files (almost one per page), and I'm not sure if this is a 'correct' way. And since there's one javascript file per page, the states or other things between different pages are not shared, every page is independent of each other. Can I have some 'shared' things without using react-router? I know Facebook itself and Airbnb don't use react-router either, so how do they use react? How do they handle a lot of bundled files? Can anyone work for a company that does not use react-router share your company's solutions? -
Execute migrations in models inside egg dependency
I have a Django project that itself does not have apps. All apps come in through egg dependencies installed in a pyvenv environment. Those apps have models but do not have 'manage.py' or database settings (just a plain app). I am now struggling to create the migrations for the apps in the eggs. When I execute 'python manage.py makemigrations' I get 'No changes detected' even though I wiped the DB before. When I then run the server it tells me that I have 13 unapplied migrations from Django core modules such as 'auth', 'sessions' etc. I can apply them running 'python manage.py migrate'. I tried creating a dummy app, added it to INSTALLED_APPS and added an import of a model from an egg to models.py of that app. Didn't work either, still 'No changes detected'. Those egg dependencies are apps I created. Is 'egg' the wrong format here? What are the alternatives? Can I tell the 'makemigrations' module where to look? What else could be the cause? -
Python Django ModelFormset queryset field overwrite
My Code class EducationalDetailForm(forms.ModelForm): class Meta: model = EDetailModel fields = ['name','year','education'] def Edu_view(request): EModelFormset = modelformset_factory(EDetailModel,form = EDetailForm,extra = 0) forms = EModelFormset(queryset = user_data) I am passing data in EModelFormset through queryset. I want to edit forms field data. I have tried to pass instance but it is giving error. e.g. forms = EModelFormset(queryset = user_data, instance = [{'name': 'ABPS'}]). Giving data in initial is putting values in extra forms. I want to initialize formset through queryset as I did then wants to overwrite some fields of formset like forms['form-0-name'] = 'AASD' -
How to catch a PermissionDenied(403) from Django with Ajax?
So im trying to handle a GET request with AJAX instead of Django so I can display a simple pop-up/modal with jQuery when a 403 Forbidden (Given by Django) is raised, however im not sure how to continue right now. This is my Javasscript that handles the request: Just gets a button in my html and waits for Click event. main.js $(document).ready(function(){ $("#users_page").click(function(e){ e.preventDefault(); $.ajax({ "method": "GET", "url": "/dashby/users/", "beforeSend": function(xhr, settings){ console.log("Before send"); }, "success": function(result){ window.location.href = "/dashby/users/"; }, "error": function(xhr, textStatus, error){ console.log(error); }, }); }); }); my view.py for this matter class AllUsersViews(UserPassesTestMixin, View): template_name = 'all_users.html' raise_exception = True # Raise PermissionDenied(403) def test_func(self): #Only superusers can access this view. if self.request.user.is_superuser: return True def get(self, request): context = {'users': User.objects.all()} return render(request, self.template_name, context) So right now if im a superuser i do get redirected to the page I want but I want to be able to basically display a message to the user (A pop-up or a modal) saying that they do not have permission if the PermissionForbidden is raised by Django. Also, I dont want the page to refresh when this happens or that the Chrome Console displays the 403 Forbidden Message. … -
FullCalendar in Django
So, I have an appointment models class Appointment(models.Model): user = models.ForeignKey(User) date = models.DateField() time = models.TimeField() doctorName = models.CharField(max_length=50)` And I want to implement this in the FullCalendar tool. I'm not sure how to even begin. Any help is appreciated. Thanks. -
Django - value too long for type character varying (but appears to be within max_length limit)
I'm getting a really strange database error: psycopg2.DataError: value too long for type character varying(4) This occurs when I'm trying to save a Question in my survey app. The odd thing is: I believe I am only trying to save 4 chars to that field! The .save(update_fields=['question_type', 'question_text', 'quota']) call passes ModelForm validation, so I went to my db to see if it actually matched the model, and it does: db=# \d surveyapp_question; Table "public.surveyapp_question" Column | Type | Modifiers ---------------+------------------------+----------- uuid | uuid | not null question_type | character varying(4) | not null question_text | character varying(255) | order | integer | quota | smallint | As you can see, there's only one varchar(4) in the model: question_type. The value I'm trying to save to that column is "text". The POST data shows "text". If I put a print(form.cleaned_data['question_type'] in form_valid it also shows text. So I looked at the postgres log: tail -f /var/log/postgresql/postgresql-9.4-main.log ... UPDATE "surveyapp_question" SET "question_type" = '(''text'',)' WHERE... Sooo ... that doesn't look right? What's with the "''text''"? Why don't I have "text" in that tuple? Is that what's causing the error? I'm running django 1.10, psycopg2 2.6.2 and PostgreSQL 9.4.7. -
passing radio buttons from javascript to django views as a paramater
I have a html page where I am passing the selected checkboxes to django views as parameter which works completely fine. layout.html <form action="{% url 'URL Which calls view' %}" method="post"> {% csrf_token %} <label class="checkbox"> <input type="checkbox" name="checks" value="REG_AGREED_SUITE01">REG_AGREED_SUITE01 </label> <hr> <label class="checkbox"> <input type="checkbox" name="checks" value="REG_AGREED_SUITE02">REG_AGREED_SUITE02 </label> <hr> <label class="checkbox"> <input type="checkbox" name="checks" value="REG_AGREED_SUITE03">REG_AGREED_SUITE03 </label> <hr> form.py class NameForm(forms.Form): views.py def view(request): if request.method == 'POST': form = NameForm(request.POST) else: form = NameForm() print request.POST.getlist('checks') form = NameForm(request.POST) list1 = request.POST.getlist('checks') TestSuite = ', '.join(list1) Now I have a situation, Where I would like to pass the radio buttons as parameters in django views. I have a json file from which using java script I am pulling the values and displaying on html. Is there any way, when ever I select a radio button, I can pass them as a parameter in django views as above case? or is it the best approach to create a form in Django? temp.json [ {"STBStatus": "1", "RouterSNo": "R1", "STBLabel": "STB#1", "STBSno": "M11435TDS144"}, {"STBStatus": "1", "RouterSNo": "R1", "STBLabel": "STB#2", "STBSno": "M11543TH4292"}, {"STBStatus": "0", "RouterSNo": "R1", "STBLabel": "STB#3", "STBSno": "SN005"}, {"STBStatus": "1", "RouterSNo": "R1", "STBLabel": "STB#4", "STBSno": "M11509TD9937"}, {"STBStatus": "1", "RouterSNo": "R1", "STBLabel": … -
Django - Template tags not working properly after form validation
I am having a form which takes some value as input, and I am processing the input and returning the required output. Now when I tried to display the output it not displaying on the webpage. The following is my forms.py: class CompForm(forms.ModelForm): class Meta: model = Comp fields = ('inp',) The following is my views.py: def index(request): form = CompForm(request.POST or None) context = { 'form': form, } print context if form.is_valid(): ... ... outData = "The values you gave is correct" errData = "The values you gave is incorrect" print context context['outData'] = outData context['errData'] = errData print context return render(request, 'comp/index.html', context) The following is my index.html: {% extends "comp/base.html" %} {% load crispy_forms_tags %} {% block content %} <div class="row"> <div class="col-md-8 col-md-offset-2"> <form method="post" action=""> {% csrf_token %} {{ form|crispy }} <input class="btn btn-primary" type="submit" name="Submit" /> </form> </div> </div> {% if outData %} {{ outData.as_p }} {% endif %} {% if errData %} {{ errData.as_p }} {% endif %} {% endblock %} In the terminal I am able to get the outData and errData in the dictionary, but its not getting displayed in the webpage. What might be the mistake? Kindly help. -
Django: How do you associate an Object_PK in the URL to the Foreign_Key relation field when creating a new object?
I am building an FAQ system. The models extend from Topic -> Section -> Article. When creating a new Article the User will select a Topic then a Section then the create Article button. The url will look something like //mysite.org/Topic_PK/Section_PK/Article_Create In Django it should look like this: url(r'^ironfaq/(?P<pk>\d+)/(?P<pk>\d+)/article$', ArticleCreateView.as_view(), name=’article-create’) What I am looking to do is to associate the Section_PK to the Article when the user submits the Article. I have the Section_PK in the URL I need help to figure out how to use it to do this. Alternatively with this set up I can have a form rendered with a choice selection from the Section_FK in the Articles Model. If when creating the Article upon rendering the template if I could limit the Section choices by the Topic in the form.py this will also work for my needs The url will look something like //mysite.org/Topic_PK/article/create In Django the url should look like this: url(r'^ironfaq/(?P<pk>\d+)/article/create$', ArticleCreateView.as_view(), name=’article-create’) Both these methods require the Passing of the Topic or Section PK to the view or form thru the URL. If there is a better way to do this I am open to other suggestions. In Django I have the … -
When using Q objects in django queryset for OR condition error occured
I want to use filter with OR condition in django. For this i want to use Q objects. My code is this def product(request): try: proTitle = request.GET.get('title') ProDescription = request.GET.get('description') funAria = request.GET.get('funAria') femaleReq = request.GET.get('femaleReq') except: pass list0 = [] result = Product.objects.filter(Q(title__contains=proTitle ) | Q(description__contains=ProDescription ) | Q(functional_area__contains=funAria ) | Q(female_candidate=femaleReq )) for res in result: list0.append(res.project_id) data ={'title result':list0} return HttpResponse(json.dumps(data)) return HttpResponse(json.dumps(data), content_type='application/json') When pass all value that is proTitle,ProDescription,funAria,femaleReq it working fine. If anyone value is going to none it encounter a error Cannot use None as a query value Why this error occured when i am using OR operator into my queryset I am also try this result = Project.objects.filter(title__contains=proTitle) | Project.objects.filter(description__contains=ProDescription ) | Project.objects.filter(functional_area__contains=funAria ) | Project.objects.filter(female_candidate=femaleReq ) but same error occured -
Knockout observables not working as expected when extending a template in Django
Something that i find very weird is happening when i use knockout inside the django templates. I have my knockout js viewmodel like this: function GreenHouse(name, width, height){ var self = this; self.name = name; self.width = ko.observable(width); self.height = ko.observable(height); } function GreenHouseMapViewModel(){ var self = this; self.greenhouse = ko.observable(new GreenHouse('name',700,700)); } ko.applyBindings(new GreenHouseMapViewModel()); Then, my html that extends the base.html template: {% extends 'base.html' %} {% load staticfiles %} {% block css %} <link rel="stylesheet" type="text/css" href="{% static 'css/components.css' %}"> <link rel="stylesheet" type="text/css" href="{% static 'css/greenhouse.css' %}"> {% endblock %} {% block content %} <div class="greenhouse-container"> <div class="greenhouse-bg" data-bind="style: { width: greenhouse().width()+'px', height:greenhouse().height()+'px' }"> </div> </div> {% endblock %} {% block js %} <script src="{% static 'libs/jquery-3.0.0.min.js' %}" type="text/javascript" charset="utf-8"></script> <script src="{% static 'libs/knockout-3.4.0.js' %}" type="text/javascript" charset="utf-8"></script> <script src="{% static 'js/knockout/greenhouse.js' %}" type="text/javascript" charset="utf-8"></script> {% endblock %} The base.html: {% load staticfiles %} <!DOCTYPE html> <html> <head> <meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=1, user-scalable=no"> {% block css %}{% endblock %} {% block head_js %}{% endblock %} </head> <body> <div class="main-content"> {% block content %}{% endblock %} </div> {% block js %}{% endblock %} </body> </html> The specific problem is this line: <div class="greenhouse-bg" data-bind="style: { width: greenhouse().width()+'px', height:greenhouse().height()+'px' }"> … -
Django PermissionRequiredMixin redirect to login template with message
I got this view and im using PermissionRequiredMixin on it...it works fine but when i redirect to login template (set in settings LOGIN_URL) i need it shows a message there like "You don't have permission to do this". Any idea how to do it without creating a custom decorator, just using PermissionRequiredMixin itself ? from django.contrib.auth.mixins import PermissionRequiredMixin class MyView(PermissionRequiredMixin,View): template = 'myapp/item_detail.html' permission_required = 'myapp.change_item' def get(self, request, *args, **kwargs): #Query here return render(request, self.template) What do i need to add in order to achieve that ? Thanks in advance !! -
Pushing local Postgres data to Heroku DB. pg_hba.conf errors
The issue started with trying to push local PostgresSQL data to the remote Heroku DB for a Django project using: heroku pg:push localdbname DATABASE_URL --app herokuappname After dealing with a lot of: psql:FATAL:password authentication failed for user 'Anthony' I was then lead to this solution: Heroku pg:push psql: FATAL: password authentication failed for user Following the above solution, I kept on running into: FATAL: no pg_hba.conf entry for host "XXX.XX.XXX.XXX", user "X", database "X", SSL off So then I tried messing around with the pg_hba.conf file by adding all of the following: host all postgres XXX.XX.XXX.XXX/32 md5 host all all XXX.XX.XXX.XXX 255.255.255.255 trust host all all 0.0.0.0/0 md5 I think they all kind of do the same thing but I keep on getting the same "no pg_hba.conf" error. There seems to be a lot of these types of questions but none of the solutions have worked so far. Any help would be greatly appreciated. -
Load two divs with a single Ajax call
I'm trying to use load() to load two divs #follow-x and #follow-y ajaxly with a click of a button.This is what I have tried in success function,but doesn't work,but works if I remove one of the function,so it loads only one div but I want it to load both.Thanks in advance $('#follow').click(function(){ $.ajax({ type: "POST", url: "{% url 'follow_class' %}", data: {'pk': '{{class.pk}}' , 'csrfmiddlewaretoken': '{{ csrf_token }}'}, dataType: "json", success: function(){ $('#follow-x').load("{% url 'class_details' %} #follow-x");} function(){ $('#follow-y').load("{% url 'class_details' %} #follow-y");} }); }); </script> Dont mind the tags{} I'm using Django -
django-autocomplete-light - how to return a different field then a models primary key?
I am using django-autocomplete-light I have a form where I want to add a value to a field other then the models id. It should ba another field in the model. actually it is the same model then the form I am filling. for one field I want to use autocomplete to fill it. The query set from autocomplete however returns the ID and I want to fill it with the field "projektnummer". Any clue how I can setup autocomplete so that it returns not the primay key of the model but some other field? views.py class SearchProjectinFormAutocomplete(autocomplete.Select2QuerySetView): def get_queryset(self): qs = KombiPublikation.objects.filter(typid__in=[222, 223, 224]).filter(zeigen=1) if self.q: qs = qs.filter(Q(projektnummer__contains=self.q)) return qs -
Passing a JSON string to django using JQueary and Ajax
I'm a bit new to Django and trying to understand it. Currently, I'm creating a network topology visualiser (think routers and switches connected together). It works fine and all of the data is saved in a javascript object. I want to have the ability to, when a user clicks a button, send this javascript object to django so that it can be parsed and handled appropriately. I did a lot of research and found a bunch of similar implementation which use a combination of JQuery and ajax to POST a JSON string. This is some of my code currently: mainapp/urls.py from django.conf.urls import include, url from django.contrib import admin urlpatterns = [ url(r'^NetworkTopology/', include('OpenAutomation.NetworkTopology.urls')), url(r'^NetworkTopology/json/', include('OpenAutomation.NetworkTopology.urls')), url(r'^admin/', admin.site.urls), ] NetworkTopology/urls.py from django.conf.urls import url from . import views urlpatterns = [ url(r'^$', views.index, name='index'), url(r'^json/$', views.returnjson, name='returnjson'), ] NetworkTopology/views.py from django.http import HttpResponse from django.shortcuts import render_to_response def index(request): return render_to_response('index.html') def returnjson(request): if request.is_ajax(): request_data = request.POST print("Raw Data: " + request_data.body) return HttpResponse("OK") JavaScript function (return JSON button is pressed): function returnJsonTop(){ $(document).ready(function() { $.ajax({ method: 'POST', url: '/NetworkTopology/json', dataType: 'json', data: JSON.stringify(nodes.get(),null,4), success: function (data) { //this gets called when server returns an OK response alert("it worked!"); … -
Django template doesn't show model items
I'm very new to Django and I'm currently trying to create a movie database for a few of my favorite directors. I've been following tutorial videos, and I'm currently trying to get my detail view to display all the added movies for each director. However when I go into the director, it does not display their films. director/models.py from django.db import models class Director(models.Model): photo = models.CharField(max_length=250, default='none') name = models.CharField(max_length=250) born = models.CharField(max_length=250) birth_date = models.CharField(max_length=20) married = models.CharField(max_length=1) def __str__(self): return self.name class Films(models.Model): director = models.ForeignKey(Director, on_delete=models.CASCADE) title = models.CharField(max_length=50) year = models.IntegerField(default=0) rating = models.DecimalField(max_digits=2, decimal_places=1, default=0) budget = models.CharField(max_length=20) def __str__(self): return self.title director/urls.py from django.conf.urls import url from . import views urlpatterns = [ url(r'^$', views.index, name='index'), url(r'^(?P<name_id>[0-9]+)/$', views.detail, name='detail'), ] director/views.py from django.shortcuts import render from django.http import HttpResponse from .models import Director, Films def index(request): all_directors = Director.objects.all() return render(request, 'director/index.html', {'all_directors': all_directors}) def detail(request, name_id): try: direct = Director.objects.get(pk=name_id) except Director.DoesNotExist: raise Http404("Director not found") return render(request, 'director/detail.html', {'direct': direct}) director/detail.html <h3 align="center"> {{ direct }} </h3><br> <img src="{{ director.photo }}"> <h4>Film List</h4> <ul> {% for films in director.films_set.all %} <li>{{ direct.title }} - {{ direct.rating }}</li> {% endfor %} </ul> … -
user database and authentication with Django and MediaWiki
My website has two subdomains. One is using framework MediaWiki which is on PHP, another is using Django which is on Python. I thought they should use separate database, but everything is ok besides the user authentication. Since MediaWiki and Django both have their user database, should I only use one user database and which one should I use? Also, how to keep session when redirecting from one subdomain to another? -
MethodField containing Serialized Object does not return proper Object's MethodField results
I have two serializers like this. class CourseSerializer(serializers.ModelSerializer): pk = serializers.IntegerField(read_only=True) name = serializers.CharField(required=True, max_length=30, allow_blank=False) chapters = serializers.SerializerMethodField() def get_chapters(self, obj): queryset = Chapter.objects.all().filter(course=obj.pk) serializer_class = ChapterSerializer(queryset, many=True) return serializer_class.data class ChapterSerializer(serializers.ModelSerializer): pk = serializers.IntegerField(read_only=True) name = serializers.CharField(required=True, max_length=30, allow_blank=False) course = serializers.StringRelatedField() cards_count = serializers.SerializerMethodField() cards_learned_count = serializers.SerializerMethodField() cards_still_to_go = serializers.SerializerMethodField() cards_not_learned = serializers.SerializerMethodField() def get_cards_learned_count(self, obj): user = None request = self.context.get("request") if request and hasattr(request, "user"): user = request.user queryset = Card.objects.all().filter(chapter=obj.pk) card_count = 0 for q in queryset: card_detail = UserCardDetail.objects.all().filter(card=q, user=user, learned=True) card_detail.count() card_count += card_detail.count() return card_count Now when I get the course serializer instead of getting the proper values in the chapter field, I get zeroes, but when I call the chapter serializer I get the right values. I noticed that the MethodField works with obj - however shouldn't that be passed already? Is there something extra I have to pass to the chapters field? -
Django: how to add compare condition in annotate queryset
I want to add compare operations in annotate queryset to calculate value for specific field. How can I do that? This is my annotate queryset sale_item_list = OrderItem.objects.filter(order_id=order.id) \ .values('item__name') \ .annotate(price=F('price')) \ .annotate(exchange_rate=F('exchange_rate')) \ .annotate(quantity=F('quantity') \ .annotate(amount=Case( When(F('quantity') < F('inventory'), then=Sum(F('quantity') * F('price'))), When(F('quantity') > F('inventory'), then=Sum(F('inventory') * F('price'))), output_field=IntegerField())) -
Mezzanine / Cartridge custom product category admin link goes to wrong place
I am trying to follow along with the Mezzanine guide to creating a custom content type (http://mezzanine.jupo.org/docs/content-architecture.html#creating-custom-content-types) to try and extend my existing Cartridge product category to include an image. So far I've got the following code: products/models.py from django.db import models from cartridge.shop.models import Product, Category from mezzanine.pages.models import Page from s3direct.fields import S3DirectField class Product(Product): cadfile = S3DirectField(dest="files", blank=True, null=True) pdffile = S3DirectField(dest="files", blank=True, null=True) class Category(Category): category_image = S3DirectField(dest="images", blank=True, null=True) products/admin.py from copy import deepcopy from django.contrib import admin from cartridge.shop.admin import ProductAdmin, CategoryAdmin from cartridge.shop.models import ProductVariation, ProductOption, Order from mezzanine.conf import settings from mezzanine.core.admin import DisplayableAdmin from mezzanine.pages.admin import PageAdmin from django.utils.translation import ugettext_lazy as _ from .models import Product, Category # Register your models here. """ Product admin, to include our additional fields. Fieldsets have been simply cut and paste from cartridge/shop/admin.py, but this is the simplest way to get it running. May need refactoring at some point? """ option_fields = [f.name for f in ProductVariation.option_fields()] product_fieldsets = deepcopy(DisplayableAdmin.fieldsets) product_fieldsets[0][1]["fields"].insert(2, "available") product_fieldsets[0][1]["fields"].extend(["content", "categories", "pdffile", "cadfile"]) product_fieldsets = list(product_fieldsets) other_product_fields = [] if settings.SHOP_USE_RELATED_PRODUCTS: other_product_fields.append("related_products") if settings.SHOP_USE_UPSELL_PRODUCTS: other_product_fields.append("upsell_products") if len(other_product_fields) > 0: product_fieldsets.append((_("Other products"), { "classes": ("collapse-closed",), "fields": tuple(other_product_fields)})) product_list_display = ["admin_thumb", "title", "status", … -
django sqlite strftime & parametric SQL query
I have a django based web application doing, among others, analyses of time histories. I am currently using sqlite as db backend. I typically group slices of data in blocks of ten minutes, thus I aggregate to get my final results. To obtain ten minutes blocks of data I have the following queryset blocks = qs.extra({'ten_min' : u"strftime('%Y%m%d%H0', date) + strftime('%M', date)/10"})\ .values('ten_min').annotate(mop.Sum('event_val1'),mop.Sum('event_val2')).all() which I also possibly restrict on given time intervals, e.g. qs.get(date__gte = last_midnight) While the two queries work perfectly while separated, they do not work chained. The final parametric SQL query string that django generates cannot be rendered as the % in the strtftime of sqlite are misinterpreted as element to be replaced while rendering the string. Let me report the entire query for clarity: params = (u"'2016-10-06 00:00:44.054382'",) sql = u'SELECT (strftime(\'%Y%m%d%H0\', date) + strftime(\'%M\', date)/10) AS "ten_min", SUM("event_logger_event"."event_val1") AS "event_val1__sum", SUM("event_logger_event"."event_val2") AS "event_val2__sum" FROM "event_logger_event" WHERE "event_logger_event"."date" >= %s GROUP BY (strftime(\'%Y%m%d%H0\', date) + strftime(\'%M\', date)/10)' the query is rendered as sql % params which gives an error. In fact the system tries to replace elements such as %Y%m%d rather than the correct ... "date" >= %s ... Any suggestion on how to deal with …