Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Load a Django template from a different app
Django 1.9 How can I load "control/templates/control/emails/fuselage_job_complete" template from "fuselage/views.py"? I want to use this template for django-emailit. I tried to call it like this: emailit.api.send_mail([task.user.email], {'task': task}, 'emails/fuselage_job_complete') I got the django.template.exceptions.TemplateDoesNotExist error. Also tried this: emailit.api.send_mail([task.user.email], {'task': task}, 'control/emails/fuselage_job_complete') I got django.template.exceptions.TemplateSyntaxError: 'site' takes at least one argument (path to a view). My project structure: web/ βββ control β βββ admin.py β βββ apps.py β βββ forms.py β βββ handlers.py β βββ __init__.py β βββ management β β βββ commands β β β βββ create_researcher.py β β β βββ __init__.py β β β βββ search_alerts.py β β β βββ sync_omop_tree.py β β β βββ sync_users.py β β βββ __init__.py β βββ managers.py β βββ migrations β β βββ __init__.py β βββ models.py β βββ signals.py β βββ templates β β βββ control β β βββ emails β β β βββ fuselage_job_complete.body.html β β β βββ fuselage_job_complete.body.txt β β β βββ fuselage_job_complete.subject.txt β β βββ json β β β βββ jsontree.json β β β βββ omoptree.json β βββ templatetags β β βββ controltags.py β β βββ __init__.py β βββ tests.py β βββ urls.py β βββ user.py β βββ views.py βββ db.sqlite3 βββ manage.py βββ static β βββ css β β¦ -
Django QuerySet Avg returns None for datetime.timedelta data
Using Django queries I have a QuerySet (called length) with a time difference and a callid, for example: {'diff': datetime.timedelta(0, 1991), 'callid': u'1360702222246142'} {'diff': datetime.timedelta(0, 5), 'callid': u'1382327574714345'} {'diff': datetime.timedelta(0, 6), 'callid': u'1397809525083955'} As the last step I want to find the average diff value for all the ids in the QuerySet. The "verbose" way works fine and returns the right result: count = length.count() length = length.aggregate(sum=Sum('diff', output_field=DurationField())) avg = length['sum'].total_seconds() / count But if I do: length.aggregate(avg=Avg('diff', output_field=DurationField())) I get: {'avg': None} What is the difference between these two ways? Why Avg returns None in this case? -
YADCF multi_select filter dropdown element matching as exact match or startsWith match
I'm using yadcf with server side processing in django: The initialisation of the filter I'm trying to work with is like this : { column_number : 4, filter_type: "multi_select", select_type:"select2", sort_as:"none", filter_match_mode:"exact" }, Basically I want the search value entered by the user to be matched with the elements in the drop down list as a "startsWith" or an "exact" match but currently they are being matched as "contains". This is related to just the matching in the dropdown list and the value entered in the input box on top and not the actual filtering of the table. and the kind of behaviour i'm looking for can be found here : https://select2.github.io/examples.html#matcher -
textbox for foreignkey field in django
So I have a form where user can post "Parent" details also form for Kid for a different model. what i need is : In Kid_form I'd like to allow the user to type the "family field" instead of dropdown list allow users to add a Parent object in case it doesn't exist. (if it's possible to be auto-complete field would be great) allow all users to link child to any other user's Parent object models.py : class Parent(models.Model): title = models.CharField(max_length=250) class Kid(models.Model): family = models.ForeignKey(Parent) title = models.CharField(max_length=250) age = models.CharField(max_length=250) views.py def add_family(request): if request.method == 'POST': parent_form = ParentForm(request.POST) kid_form = KidForm(request.POST) if parent_form.is_valid() and kid_form.is_valid(): parent = parent_form.save(commit=False) parent.save() kid = kid_form.save(commit=False) kid.family = parent kid.save() return redirect('index') else: parent_form = ParentForm() kid_form = KidForm() template = 'add_family.html' context = {'parent_form': parent_form, 'kid_form': kid_form} return render(request, template, context) template: <form method="post"> {% csrf_token %} {{ parent_form.title }} {{ parent_form.address }} <button type="submit">Send</button> <form method="post"> {% csrf_token %} {{ kid_form.family }} {{ kid_form.title }} {{ kid_form.age }} <button type="submit">Send</button> </form> any idea? -
How to set the project root url when Wagtail is integrated as an app in a Django-project
I'm integrating Wagtail in a pre-existing Django project. My project tree is as follows: /adjangoproject/ /anapp /blog/ urls.py /anotherapp urls.py My adjangoproject/urls.py urlpatterns = patterns('', url(r'^blog/', include('geonode.blog.urls')), [...] My adjangoproject/blog/urls.py urlpatterns = patterns('', url(r'^cms/', include(wagtailadmin_urls)), url(r'', include(wagtail_urls)), ) While [adjangoproject_rooturl]/blog/cms correctly shows the wagtail admin, the path [adjangoproject_rooturl]/blog/ (the base location where the pages of my wagtail blog shall be served) gives: Request Method: GET Request URL: http://127.0.0.1:8000/blog/ Raised by: wagtail.wagtailcore.views.serve Could you help me? -
continuous integration and deployment for Django
Please, tell me what tools I can use and how oranise the process of continuous integration and deployment for my Django project? -
How to display many to many relationship fields (if the many to many relationship is using 'through') in the Django Admin Area?
I know it is easy to display fields for foreign keys in the admin area, but how do I display fields for many to many relationships if through is used? Models.py: class Pizza(models.Model): toppings = models.ManyToManyField(Topping, through='PizzaTopping') class Topping(models.Model): topping = models.CharField(max_length=255) class PizzaTopping(models.Model): pizza = models.ForeignKey(Pizza) topping = models.ForeignKey(Topping) Admin.py: class PizzaAdmin(admin.ModelAdmin): fieldsets = ( (None, { 'fields': ('toppings') }), }) ) This produces the following error: <class 'pizzas.admin.PizzaAdmin'>: (admin.E013) The value of 'fieldsets[0][1]["fields"]' cannot include the many-to-many field 'toppings' because that field manually specifies a relationship model. I want to display a box or listbox which allows me to select a topping. Is this possible? Thanks -
django send_main not working
I am just trying to send Emails as part of a django contact page. from django.shortcuts import render from django.shortcuts import render from django.http import HttpResponse, HttpResponseRedirect from django import forms from django.core.mail import send_mail, EmailMessage from StudioHanel.forms import ContactForm import traceback import time def index(request): return render(request, 'StudioHanel/index.html') def contact(request): send_mail( 'Subject here', 'Here is the message.', 'xx@gmail.com', ['xx@gmail.com'], fail_silently=False, ) mystack = '' if request.method == 'POST': form = ContactForm(request.POST) if form.is_valid() or True: subject = form.cleaned_data['subject'] message = form.cleaned_data['message'] sender = form.cleaned_data['sender'] # recipients = ['cordelia@studio-hanel.com', 'sylvia@studio-hanel.com', 'admin@studio-hanel.com'] recipients = [ 'xx@gmail.com'] send_mail(subject, message, sender, recipients, fail_silently=False) time.wait(10) # EmailMessage(subject, message, sender, to = recipients) return HttpResponse('success') else: form = ContactForm() return render(request, 'StudioHanel/contact.html', { 'form': form, 'mystack': mystack }) It doesn't do anything. The response to the request is 200. No stacktrace. I have the following settings in settings.py. # Email settings DEFAULT_FROM_EMAIL = 'xx@gmail.com' SERVER_EMAIL = 'xx@gmail.com' EMAIL_USE_TLS = True EMAIL_HOST = 'smtp.gmail.com' EMAIL_PORT = 587 EMAIL_HOST_USER = 'xx@gmail.com' EMAIL_HOST_PASSWORD = 'xx' The email account is able to send email via software. I tested that already with import smtplib fromaddr = 'xx@gmail.com' toaddrs = 'xx@gmail.com' msg = 'Why,Oh why!' username = 'xx@gmail.com' password = 'xx' β¦ -
Django Rest-Framework right Design
Hello everybody I have created a REST API with Django. Actual i want to know if my design is valid or are there better options to design it. def get_data(self, username): try: address = Adresse.objects.get(user=username) return AdressenSerializer(adress).data except Adresse.DoesNotExist: raise Http404 except MultipleObjectsReturned: adressen = Adresse.objects.filter(user=username) return AdressenSerializer(adressen, many=True).data def get(self, request, format=None): serialized_data = self.get_data(self.request.user) return Response(serialized_data, status=status.HTTP_200_OK) def post(self, request, format=None): ... if serializer.is_valid(): serializer.save() return Response(serializer.data, status=status.HTTP_201_CREATED) return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST) This code works. My question is: Is this design correct or is it better to create a new file(service.py) an put there the serializer and else ? I somebody have improvement suggestions he could telle it me please to improve my code. Thanks everybody. -
Why does Django wrap INSERT and DELETE statements in BEGIN/COMMIT?
I've found from the docs that Django uses autocommit by default when talking to the database. I haven't changed this setting. However, in the db query log I can see that it still wraps each INSERT or DELETE in BEGIN/COMMIT, while SELECTS are not being wrapped. I wonder why is this necessary? Any links to the docs would be appreciated. -
CRUD in Django template rendering ProgrammingError 42S22
I am trying to create CRUD project in Django. I successfully connected with database in MS SQL SERVER, also successfully made migration with my model. Now when I tried I to show list of data in webpage I have next ERROR: ProgrammingError ('42S22', '[42S22] [Microsoft][ODBC SQL Server Driver][SQL Server]οΏ½"id". (207) (SQLExecDirectW)') Error during template rendering in extraction_list.html: {% for extraction in object_list %} I tried with Function Based Views and also with Class Based Views but result was the same. Can someone help me to fix this problem?! view.py def extraction_list(request, template_name='extraction_list.html'): extractions = Extraction.objects.all() data = {} data['object_list'] = extractions return render(request, template_name, data) class ExtractionsList(ListView): model = Extractions urls.py urlpatterns = ( url(r'^$', views.extraction_list, name='extraction_list'), # *** ) extraction_list.html <h1>Extractions list</h1> <ul> {% for extraction in object_list %} <li>ExtractionID-{{ extraction.id_extraction }} Date-{{ extraction.name_extraction }} <a href="{% url 'crud:extraction_edit' extraction.id_extraction %}">edit</a> <a href="{% url 'crud:extraction_delete' extraction.id_extraction %}">delete</a> </li> {% endfor %} </ul> <a href="{% url 'crud:extraction_new' %}">New</a> models.py class Extraction(models.Model): id_extraction = models.CharField(db_column='ID_Extraction', max_length=36, blank=True, null=True) name_extraction = models.CharField(db_column='Name_Extraction', max_length=150, blank=True, null=True) class Meta: managed = False db_table = 'Extraction' -
django_admin database creation, after sql command depreciated
I was using django 1.3 and python 2.4 for a big scale project. Decided to update it to django 1.9 and python 2.7. Since django_admin's sql parameter is depreciated at the 1.9 update database creation method is changed a lot. I am using the command : "python /usr/local/django//manage.py migrate --fake-initial --noinput --run-syncdb" for table creation. But my tables does not created without printing an error. I am suspecting that INSTALLED_APPS does not include my tables, but I have appended my application to the list in my settings.py. I got suspicious that I need to add my separately to the installed_apps list. I have followed recommended procedure by django itself while updating the system. If my suspicions are true how could I add models to installed apps or any other suggestion would be great? -
Tagulous and prefetch_related, how to optimize tagulous queries
I don't success to prefetch tagulous things. There is always queries to tables like "app_fieldnametag" import tagulous from django.db import models class ProjectGroupTag(tagulous.models.TagModel): class TagMeta: initial = "" space_delimiter = False protect_all = True class Project(models.Model): project_group = tagulous.models.TagField( blank=True, to=ProjectGroupTag, ) class Task(models.Model): project = models.ForeignKey( Project, related_name='tasks' ) type = models.CharField(max_length=100) The following query will perform a lot of SQL queries on a table "app_projectgrouptag" (1 for each task) Task.objects.filter(type="blop").prefetch_related('project__project_group') SQL Query I want to avoid : SELECT "app_projectgrouptag"."id", "app_projectgrouptag"."name", "app_projectgrouptag"."slug", "app_projectgrouptag"."count", "app_projectgrouptag"."protected" FROM "app_projectgrouptag" INNER JOIN "app_project_project_group" ON ("app_projectgrouptag"."id" = "app_project_project_group"."projectgrouptag_id") WHERE "app_project_project_group"."project_id" = 104 ORDER BY "app_projectgrouptag"."name" ASC Which prefetch_related argument should use to prefetch tagulous ? -
How can I limit the choices in an InlineAdmin based on the current instance?
I have a database of articles that are reused across multiple Django sites. There is also some site-specific information for each Article, stored in the SiteArticle model. One bit of information is a list of site-specific tags for each SiteArticle. Here's the models.py: class Article(models.Model): sites = models.ManyToManyField(Site, through='SiteArticle') class SiteArticle(models.Model): site = models.ForeignKey(Site) article = models.ForeignKey(Entiteit) tags = models.ManyToManyField('Tag', blank=True) class Tag(models.Model): name = models.CharField(max_length=255) site = models.ForeignKey(Site, related_name='tags') I use an inline admin to edit and add the SiteArticle objects of each Article. Here's admin.py: class InlineSiteArticle(admin.StackedInline): model = SiteArticle @admin.register(Article) class ArticleAdmin(admin.ModelAdmin): inlines = [InlineSiteArticle] When editing an article, I would like the inline SiteArticle forms to only display the tags of the relevant site. I tried overriding the formfield_for_manytomany() method, but here I don't have access to instance variable (which should be an instance of the current SiteArticle) that I need to filter the queryset: def formfield_for_manytomany(self, db_field, request, **kwargs): if db_field.name == "tags": kwargs["queryset"] = instance.site.tags.all() ^^^^^^^^ return super(InlineSiteArticle, self).formfield_for_manytomany(db_field, request, **kwargs) I already looked at this Stack Overflow answer which solves a very related problem. In my case, however, I do not need access to the "parent" instance, but simply to the instance of β¦ -
Django: insert something into the middle of an indexed SQlite database
I am new to Django, using Python 3 and the default Django SQLite database. I am creating a database of sequential data where sometimes I might have to insert something in between. So I created a table: class Some_data(models.Model): some_text = models.CharField(max_length=200) some_info = models.CharField(max_length=200) auto_increment_id = models.AutoField(primary_key=True) I guess auto incrementation will not achieve what I am trying to do... How do I create an integer field that auto increment the count of rows as an "index". What to deal with it the logic behind when I need to actually insert a record in the middle of the table? which I suppose there will be a function to loop through all index > current index and +1 into the "index" field? What would be the best way to present the above feature in the view? -
Manual token with Django Rest Framework JWT
I'm currently using Django Rest Framework JWT for authentication on a project. I have already implemented BasicAuthentication, SessionAuthentication and JSONWebTokenAuthentication where users can request a token by using the POST method for every new session. However, I would like the token to be created (and possibly viewable in the admin section) immediately after each user is created. I took a look at the Django Rest Framework JWT documentation where it states that tokens can be manually created using: from rest_framework_jwt.settings import api_settings jwt_payload_handler = api_settings.JWT_PAYLOAD_HANDLER jwt_encode_handler = api_settings.JWT_ENCODE_HANDLER payload = jwt_payload_handler(user) token = jwt_encode_handler(payload) I tried putting this code snippet in views.py, models.py and serializers.py but I keep getting a reference error on the "user". Any help on how to correctly implement this code snippet or an alternative method will be greatly appreciated. Thanks -
How to do pagination without losing form values?
I have a page that returns a query. There is a form with check-mark boxes that are filters to the query. Without pagination, if I select 5 filters, the page displays the filtered results and keeps the check-marked boxes so the user knows the filters that have been applied. Then, I implemented pagination. Each page number is passed through the url (like ?pg=1). When I apply filters and get the filtered list, after I click page 2, the page reloads, all filters are lost and I see page 2 with unfiltered results. How could this be fixed? -
How to make Django truncate tables when using TransactionTestCase?
I'm trying to use TransactionTestCase in my Django tests so that all tables are truncated after each test. However, looking into the db query log I see that only a subset of tables is truncated, e.g. LOG: statement: TRUNCATE "auth_user_user_permissions", "auth_group", "django_admin_log", "auth_user", "auth_permission", "auth_group_permissions", "django_content_type", "django_session", "auth_user_groups"; I have more models/tables defined in models.py of my app. Why may those not get truncated? -
How to make GetStream post activities of Facebook page
I would like to use GetStream to create customizable Facebook Page Plugin to display all the recent activities on the website (same as this https://developers.facebook.com/docs/plugins/page-plugin).However I have no idea how to connect GetStream with particular Facebook page. How do I get ID of a page and where do I put it inside the code so it pulls all the recent activities and post them on he website? -
adding a new record from django-autocomplete-light?
I am trying to add new record from django-autocomplete-light. below I describe how I set it up django-autocomplete-light displays empty dropdown in the form I am reading the docs and a bit confused (I usually use only function views and this is probably why). Can someone please provide some example ? -
in diango1.10, set a time to do the signals.post_save.connection()
in diango1.10, when upload a image file from website, then the database will insert a record which has a item is "is_execute", if not this image file will be executed by a function. I use the signals.post_save.connetion(), but I don't want to do this immediately, I hope this function can be execute at the midnight -
How to serialize empty ImageField to JsonResponse?
I have model: class Item(models.Model): title = models.TextField(verbose_name='Title', default='Default title') photo = models.ImageField( verbose_name='Photo', upload_to='media/', blank=True, ) def __str__(self): return self.title I am trying to serialize this model object to json response to frontend. Let's look to my test view: from app.models import Item from django.forms.models import model_to_dict from django.http import JsonResponse def get(self, request, *args, **kwargs): item_object = Item.objects.first() to_json = model_to_dict(item_object) return JsonResponse(to_json) But if i haven't download photo yet, JsonResponse throw TypeError: is not JSON serializable [16/Nov/2016 13:51:15] "GET /items/?item_id=9&shop_id=4 HTTP/1.1" 500 129160 Internal Server Error: /items/ Traceback (most recent call last): File "/home/lamberk/python/picasel/rc_cross_upsell/venv/lib/python3.5/site-packages/django/core/handlers/exception.py", line 39, in inner response = get_response(request) File "/home/lamberk/python/picasel/rc_cross_upsell/venv/lib/python3.5/site-packages/django/core/handlers/base.py", line 187, in _get_response response = self.process_exception_by_middleware(e, request) File "/home/lamberk/python/picasel/rc_cross_upsell/venv/lib/python3.5/site-packages/django/core/handlers/base.py", line 185, in _get_response response = wrapped_callback(request, *callback_args, **callback_kwargs) File "/home/lamberk/python/picasel/rc_cross_upsell/venv/lib/python3.5/site-packages/django/views/generic/base.py", line 68, in view return self.dispatch(request, *args, **kwargs) File "/home/lamberk/python/picasel/rc_cross_upsell/venv/lib/python3.5/site-packages/django/views/generic/base.py", line 88, in dispatch return handler(request, *args, **kwargs) File "/home/lamberk/python/picasel/rc_cross_upsell/CrossUpsell/apps/items/views.py", line 54, in get 'up_sells': up_sells, File "/home/lamberk/python/picasel/rc_cross_upsell/venv/lib/python3.5/site-packages/django/http/response.py", line 520, in __init__ data = json.dumps(data, cls=encoder, **json_dumps_params) File "/usr/lib/python3.5/json/__init__.py", line 237, in dumps **kw).encode(obj) File "/usr/lib/python3.5/json/encoder.py", line 198, in encode chunks = self.iterencode(o, _one_shot=True) File "/usr/lib/python3.5/json/encoder.py", line 256, in iterencode return _iterencode(o, 0) File "/home/lamberk/python/picasel/rc_cross_upsell/venv/lib/python3.5/site-packages/django/core/serializers/json.py", line 118, in default return super(DjangoJSONEncoder, self).default(o) File β¦ -
How to connect android app with website written on Django
I am junior android developer and I have some troubles. How I can connect my android app with my website, which is written on python by using Django? For example list of deals in website can be shown also in android app. I read about this, approximately 80% of information is about connecting android app with website written on php. Thanks for a help ! -
Where to put a Mixin that's used by multiple apps?
I'm sorry if this is a basic question, but I have a mixin I want to use in multiple apps. Is there a best practice on where this mixin should go? Thanks -
Django - summary page after creating orders
I'm trying to figure out how to make a orders summary (calculation) page. There can be created multiple orders in order form (depends on multiplechoice language field). After submitting the form I want user to see a **summary ** page so there is each order and it's price visible. Then confirm. I think the best way is to save those orders in a view and rembember their id's in some list which is then converted to get parameters of the summary page. The problem is that save() method doesn't return anything so I can't get those id's. Do you know how to get id's? Or a better way how to do the summary page? VIEW def new_order(request): new_order_form = NewOrderForm(request.POST or None) if request.method == 'POST': if new_order_form.is_valid(): orders = [] for target_language in new_order_form.cleaned_data.get('target_languages'): ord = new_order_form.save(request.user,target_language) orders.append(ord) print orders # [None,None...] params = '?ord='+'ord='.join(str(x.id) for x in orders) return HttpResponseRedirect(reverse("order_summary")+params) return render(request, 'ordersapp/new-order.html',context={'new_order_form':new_order_form}) FORM class NewOrderForm(forms.ModelForm): target_languages = forms.ModelMultipleChoiceField(queryset=Language.objects.all()) class Meta: model = Job fields = ['language_from', 'topic', 'target_languages', 'level', 'stylistics', 'file_output_format', 'visual_form', 'file', 'notes'] def save(self,user,target_language): self.instance.customer = user self.instance.language_to = target_language super(NewOrderForm,self).save()