Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
How do template languages/engines like DTL and Jinja express and manage the relationships between various template files?
I'm specifically using Django and Jinja2. This is my first foray into using templates without the help of a CMS to pick which ones and put them all together. For some reason, I can't seem to comprehend how a bunch of pieces fit together. I feel comfortable with these concepts: A template engine processes a template and a model to produce a useful result. A template file describes how model data should be fitted into it to produce that result. An application developer programmatically interacts with the engine and template objects which represent template file. The programmer is responsible for selecting a template file, providing the data, and handing it all to the engine. And then doing something with useful result the engine gives back. But what I'm struggling with is this: Templates files can be written to inherit from each other, promoting DRY. Templates files contain information about their inheritance. And now I fall down. How does that work? Where in the system is this relationship used? If I'm passing a base template to the engine, how does the engine know which child templates should be used? If I'm passing a child template to the engine, okay, that template … -
Python Django no module named 'app' in eclipse, urls.py
I got this error message. It seems like it can't recognize app. Isn't there any way to fix this problem? error message. pydev debugger: starting (pid: 5628) pydev debugger: starting (pid: 3504) Performing system checks... Unhandled exception in thread started by <_pydev_bundle.pydev_monkey._NewThreadStartupWithTrace instance at 0x0478C210> Traceback (most recent call last): File "C:\Users\jeon hyun joo\.p2\pool\plugins\org.python.pydev_5.5.0.201701191708\pysrc\_pydev_bundle\pydev_monkey.py", line 574, in __call__ return self.original_func(*self.args, **self.kwargs) File "C:\Python27\lib\site-packages\django-1.10.5-py2.7.egg\django\utils\autoreload.py", line 226, in wrapper fn(*args, **kwargs) File "C:\Python27\lib\site-packages\django-1.10.5-py2.7.egg\django\core\management\commands\runserver.py", line 121, in inner_run self.check(display_num_errors=True) File "C:\Python27\lib\site-packages\django-1.10.5-py2.7.egg\django\core\management\base.py", line 374, in check include_deployment_checks=include_deployment_checks, File "C:\Python27\lib\site-packages\django-1.10.5-py2.7.egg\django\core\management\base.py", line 361, in _run_checks return checks.run_checks(**kwargs) File "C:\Python27\lib\site-packages\django-1.10.5-py2.7.egg\django\core\checks\registry.py", line 81, in run_checks new_errors = check(app_configs=app_configs) File "C:\Python27\lib\site-packages\django-1.10.5-py2.7.egg\django\core\checks\urls.py", line 14, in check_url_config return check_resolver(resolver) File "C:\Python27\lib\site-packages\django-1.10.5-py2.7.egg\django\core\checks\urls.py", line 24, in check_resolver for pattern in resolver.url_patterns: File "C:\Python27\lib\site-packages\django-1.10.5-py2.7.egg\django\utils\functional.py", line 35, in __get__ res = instance.__dict__[self.name] = self.func(instance) File "C:\Python27\lib\site-packages\django-1.10.5-py2.7.egg\django\urls\resolvers.py", line 313, in url_patterns patterns = getattr(self.urlconf_module, "urlpatterns", self.urlconf_module) File "C:\Python27\lib\site-packages\django-1.10.5-py2.7.egg\django\utils\functional.py", line 35, in __get__ res = instance.__dict__[self.name] = self.func(instance) File "C:\Python27\lib\site-packages\django-1.10.5-py2.7.egg\django\urls\resolvers.py", line 306, in urlconf_module return import_module(self.urlconf_name) File "C:\Python27\lib\importlib\__init__.py", line 37, in import_module __import__(name) File "C:\Users\jeon hyun joo\workspace\blog\blog\blog\urls.py", line 19, in <module> from blog.polls import views ImportError: No module named polls seems like there is problem in urls.py, but I can't find which part causing this problem. urls.py … -
Dyanamically populating Django select / Choice Field / ModelChoiceField via AngularJS
The Problem I am unable to populate a Django Choicefield with returned data from a function. I did have this working with angular templating however the problem was I was unable to validate this form field as I had hardcoded the fields into my html. The Code html <div class="notification-group"> <label class="input-label">Select department</label> <div class="notification-input"> {{ form.department }} </div> </div> <div class="notification-group"> <label class="input-label">Select notification type</label> <div class="notification-input" ng-controller="selectNotificationTypeCtlr"> <select class="input-element" ng-change="getNotfications()" ng-model="selectedNotificationType"> <option ng-repeat="i in notificationTypes" value="{[{ i.pk }]}">{[{ i.fields.notification_type }]}</option> <!-- fields.notification_type --> </select> </div> </div> app.js selectNotification.controller('selectDepartmentCtlr', function($scope, $http, notificationTypesService) { $scope.getNotificationType = function() { var id = $scope.selectedDepartment; var notificationTypes = []; $http({ method : "GET", url : id }).then(function success(response) { $scope.notificationTypes = response.data; }, function error(response) { var errorMessage = "Oops it looks like something went wrong. Please try again."; }); }; }); As you can see I understand the process, its just integrating it with Django forms. views.py @login_required(login_url="/login/") def get_notification_types(request, id): if request.method == "GET": department = Department.objects.get(id=id) notification_types = NotificationType.objects.filter(department=department.id) return HttpResponse(serializers.serialize('json', notification_types)) forms.py from django import forms from notifications.models import Department from notifications.models import NotificationType class SelectNotificationForm(forms.Form): department = forms.ModelChoiceField(queryset=Department.objects.all(), widget=forms.Select(attrs={'class':'input-element', 'ng-change':'getNotificationType()', 'ng-model':'selectedDepartment'})) #widget=forms.Select(attrs={'class': 'add_class_here'}) # ChoiceField(widget=forms.Select() notification_type = forms.ModelChoiceField(queryset=NotificationType.objects.none(), … -
python cant find pydev even though the egg is already in the path
so I'm getting this error: ImportError at /path No module named 'pydev' Request Method: GET Request URL: http://localhost:8080/path Django Version: 1.10.5 Exception Type: ImportError Exception Value: No module named 'pydev' Exception Location: ./path/urls.py in <module>, line 7 Python Executable: /usr/local/bin/uwsgi Python Version: 3.5.2 Python Path: ['.', '', '/vagrant/site/python/pythonapp/pythonapp', '/vagrant/site/python/pycharm-debug.egg', '/usr/lib/python35.zip', '/usr/lib/python3.5', '/usr/lib/python3.5/plat-x86_64-linux-gnu', '/usr/lib/python3.5/lib-dynload', '/home/vagrant/.local/lib/python3.5/site-packages', '/usr/local/lib/python3.5/dist-packages', '/usr/lib/python3/dist-packages'] as you can see pycharm-debug.egg is already in the path list and yet it's still complaining that it can't find pydev I have this in my urls.py from pydev import pydevd pydevd.settrace('localhost', port=4444, stdoutToServer=True, stderrToServer=True) I'm using django on vagrant How do I get pydev to work so that I can do remote debug? -
TypeError <django.http.response.HttpResponse object at xxxx> is not JSON serializable
I am trying to show exception on html page to the user. My code looks like this - Excpetion class: class ParseError(Exception): pass some code throws exception: raise ParseError("We got an exception") When this exception is caught, I am returning HTTpResponse like this - def show_error(self, exception): return render_to_response('formtools/upload/show_error.html',{'error' : data }) On this step if I Print exception using print format(exception), I get correct output. But in HttpResponse it is always throwing TypeError not JSON serializable" exception. I have tried using json.dumps, serializer but nothing seems to work. I just want to show an html page with the text from the exception. Any help on how I can fix this is greatly appreciated. Using Django1.7 -
Celery Django celerybeat.pid permissions
Running Celery with Django on Debian production server under user that can't write in project' dir, but while initialization celery beat needs to create file to store pid (celerybeat.pid). > File > "/webapps/bookingsoft2016/lib/python3.5/site-packages/celery/platforms.py", > line 213, in write_pid > pidfile_fd = os.open(self.path, PIDFILE_FLAGS, PIDFILE_MODE) celery.platforms.LockFailed: [Errno 13] Permission denied: > '/path_to_project/celerybeat.pid' How can I change location of that file? --pidfile=/var/run/celery/celerybeat.pid - doesn't seems to work Or any other solution to avoid this? Thanks -
vscode html autoformat on django template
I love VSCode on save autoformat until it messed up with my template code. It wrongly formats my django template syntax into one line code (sometimes really long line). So instead of having this code {% for row in 'ABCDEFGH' %} <tr> {% for col in '123456789012345' %} <td> {% with forloop.counter|stringformat:"s" as counter %} {% with row|add:counter as seat_num %} {% if seat_num not in oc_seats %} <input type="checkbox" value="{{ row }}{{ forloop.counter }}" name="seats"> {% endif %} <br> {{ seat_num }} {% endwith %} {% endwith %} </td> {% endfor %} </tr> {% endfor %} I end up have this code {% for row in 'ABCDEFGH' %} <tr> {% for col in '123456789012345' %} <td style="text-align: center; border: 1px solid #aaa;"> {% with forloop.counter|stringformat:"s" as counter %} {% with row|add:counter as seat_num %} {% if seat_num not in oc_seats %} <input type="checkbox" value="{{ row }}{{ forloop.counter }}" name="seats"> {% endif %} {{ seat_num }} {% endwith %} {% endwith %} </td> {% endfor %} </tr> {% endfor %} I tried to disable format on save by changing user settings into {"editor.formatOnSave": false} but still haven't gotten any luck. Is there any plugin or configuration that I can use … -
Django tutorial 1 not showing polls
I am taking a test Driven Development course for python (which is awesome) Obeythetestinggoat and so my Django needs work. So I'm taking the Djangoproject.com course and I get all the code entered and the server runs but the polls won't change. The home page http://127.0.0.1:8000 shows "It worked! Congratulations on your first Django-powered page." Which is great but it won't show the polls or the admin buttons and I've run out of ideas on how to redirect it but not sure the problem. from django.conf.urls import include, url from django.contrib import admin urlpatterns = [ url(r'^polls/', include('polls.urls')), url(r'^admin/', admin.site.urls), ] I'm rather proud that I figured out the server and other areas but I just don't know what I am missing to get the page to show the polls. https://docs.djangoproject.com/en/1.10/intro/tutorial01/ -
Django excel save_book_to_database() broken in latest version using Django 1.8
I've been going through the django excel documentation using Django 1.8, but haven't been able to get save_book_to_database(...) to work. It either fails silently or gives the following error: 'tuple' object has no attribute '_meta' I have followed the syntax from the docs, but I have no idea why it keeps breaking or failing silently: http://django-excel.readthedocs.io/en/latest/ -
Django - put value from one view to another
This is a part of my template file: {% for tag, value in tags.items %} <a style="color: {{value.1}}; font-size: {{value.2}}px " href="{% url 'tags' tag|slugify %}">{{ tag }}</a> ({{value.0}}), {% endfor %} Url looks like: http://127.0.0.1:8000/tag/my-simple-url/ I need to get "my-simple-url" as my "simple url" in my next view. Now it looks like: def tags(request, slug): context = {} tags = Tags().tag_filer_sites(slug.replace('-', ' ')) context['slug'] = slug context['tags'] = tags['sites'] return render(request, 'mainapp/all_tags.html', context) but I have to use full name instead of slug. How can I achieve that? I need to find a way to put tag into url or get it in different way but I don't know how can I do this. -
How to safely store users' credentials to third party websites when no authentication API exists?
I am developing a web app which depends on data from one or more third party websites. The websites do not provide any kind of authentication API, and so I am using unofficial APIs to retrieve the data from the third party sites. I plan to ask users for their credentials to the third party websites. I understand this requires users to trust me and my tool, and I intend to respect that trust by storing the credentials as safely as possible as well as make clear the risks of sharing their credentials. I know there are popular tools that address this problem today. Mint.com, for example, requires users' credentials to their financial accounts so that it may periodically retrieve transaction information. LinkedIn asks for users' e-mail credentials so that it can harvest their contacts. What would be a safe design to store users' credentials? In particular, I am writing a Django application and will likely build on top of a PostgreSQL backend, but I am open to other ideas. For what it's worth, the data being accessed from these third party sites is nowhere near the level of financial accounts, e-mail accounts, or social networking profiles/accounts. That said, I … -
Django runserver - can't serve video files
When running Django in local mode using the runserver command video files are not loaded in the browser properly. I get the error "An error occurred trying to load the resource." All other static files serve fine such as images, javascript and css. -
Django cart_add cart.py Don't show items
I want to create cart in my django-shop.i start new app named cart and add new file to this app cart.py. In this file i created class Cart and add some function. This is cart.py class Cart(object): def __init__(self, request): """ Inicjaliazacja koszyka na zakupy. """ self.session = request.session cart = self.session.get(settings.CART_SESSION_ID) if not cart: # pusty koszyk w sesji cart = self.session[settings.CART_SESSION_ID] = {} self.cart = cart def add(self, product, quantity=1, update_quantity=False, size=None, upd_size=False): """ Dodanie produktu i zmiana ilości """ product_id = str(product.id) if product_id not in self.cart: self.cart[product_id] = {'quantity': 0, 'size': None, 'price': str(product.price)} if update_quantity: self.cart[product_id]['quantity'] = quantity else: self.cart[product_id]['quantity'] += quantity if upd_size: self.cart[product_id]['size'] = size else: self.cart[product_id]['size'] += size self.save() def save(self): self.session[settings.CART_SESSION_ID] = self.cart self.session.modified = True def remove(self, product): """ Usunięcie produktów z koszyka """ product_id = str(product.id) if product_id in self.cart: del self.cart[product_id] self.save() def __iter__(self): """ Iteracja przez elementy na zakupy i pobranie z bazy danych """ product_ids = self.cart.keys() products = Product.objects.filter(id__in=product_ids) for product in products: self.cart[str(product.id)]['product'] = product for item in self.cart.values(): item['price'] = Decimal(item['price']) item['total_price'] = item['price'] * item['quantity'] yield item def __len__(self): """ Obliczanie liczby wszytskich elementów w koszyku. """ return sum(item['quantity'] for item in … -
Raw query must include the primary key error even though I'm doing SELECT *
in accordance with https://docs.djangoproject.com/en/1.10/topics/db/sql/ I have query = "SELECT * FROM model_name" objs = [] for obj in models.ModelName.objects.raw(query): objs.append(obj) yet it complains Raw query must include the primary key error why is this happening ModelName code: class ModelName(ModelBase): fielda = models.CharField(max_length=255) class ModelBase(models.Model): id = models.IntegerField(primary_key=True) -
Django: form as image
I have a simple form in my template, index.html: {% if stripped_thumbnail_file_list %} {% for thumbnail_name in stripped_thumbnail_file_list %} <div class=""> <div class=""> This is my form <form class="" action="{% url 'index' %}" method="post"> {% csrf_token %} <input type="image" value="{{ thumbnail_name }}" src="{{ MEDIA_URL}}thumbnails/{{ thumbnail_name }}.jpg"> </form> </div> </div> {% endfor %} {% else %} <p>No videos are available.</p> {% endif %} I want the index view to pull the {{ thumbnail_name }} value from this form and use it as a variable when the index view redirects to a different view that will use that name to play a matching video. I have been unsuccessful in trying to pull that value from the form as I have it. I suspect this may because I'm not creating a Django form object. I tried to create that object, but I can't find any examples of a Django form object as an image like I have in my form. What should that look like? Or, can someone make a recommendation on how to pull the value from the form as is? -
Add a simple button to django admin to run a python script or function
What is the easiest way to add a simple button or link to django admin that runs a python script or a function. But no admin action because they always need items to be selected. -
Django, need pointers to a working out-of-the-box app with CRUD admin
as i newbie, i decided to go learning Django and did tutorials. i would like now to study a working app with CRUD capacity for an admin site, but would prefer finding some using integrated CSS or responsive frameworks like Bootstrap. the trick is that it seems i found none of them working. i tried the django-crudbuilder, django-crud and django-bootstrap-crud-templates but none of them provide a working out-of-the-box demo and even if i was fighting to have something working , i did not manage to have any chance with none. it seems it can also be due to having too far different versions of Django, mine is the one quite up-to-date with python 2.7.13 and django 1.10.5 can someone help me and point me to a out-of-the-box working apps for that? is it that to build something working using most of the library one should stay with very old django like 1.8 ? (it seems that most of the book are based on such old version.) (i guess that my question is not really in the technical format for stackoverflow, but i am stuck and it seems to me that lots of tutorials on the web for Django i had … -
Purging/Deleting rows from django_admin_log table
I have a django application running since 2010. The size of the django_admin_log table is almost 1 GB which is half the size of my database (2 GB). The table contains audit logs of changes made by users in the admin interface. I do not care about logs from 2010. I'd rather just keep logs from the last 1 year and delete the rest. I believe it should not be a trouble to setup an archiving plan to purge data from the django_admin_log table frequently so the size of the database can be reduced and improve performance. Can someone suggest if they have gone through this process before and if there's anything I need to worry about before deleting old rows from django_admin_log table? -
How to send Base64 Image Encoder to Django with Ajax
I used Cropit to crop Image, and automatically save what the users do. var imageData = $('.image-editor').cropit('export'); I don't know how send the Cropped Image to Django using ajax. My work is: var formData = new FormData(); formData.append("photo",imageData); $.ajax({ url: "", type: 'POST', data:formData, async: false, success: function (data) { // }, cache: false, contentType: false, processData: false }); -
Django+Nginx+Gunicorn loading larger files
I have search and tried many things but can't seem to find a similar case. My setup: Django + nginx + gunicorn on ubuntu 16.04.1 The issue: I have a site that allow internal user to upload zip file to server. The upload uses HTML with POST to read and save the file to server, nothing fancy. The application works great with smaller files (~30 mb is the largest I tested). When larger files are loading you will see the status going from 0% to x% then restart at 0% again, it will do this twice then I will get an error. Timing this, each interval is at 30 seconds which led me to conclude that it is gunicorn that is timing out. The question: I setup my service to execute this way: /home/ubuntu/.virtualenvs/myenv/bin/gunicorn --workers 3 --timeout 240 --bind unix:/home/ubuntu/myproj/myapp.sock myproj.wsgi:application No matter what I try, it still reset at 30 seconds. Any ideas? Thanks in advance! -
Annotate over month django
I'm trying to build a table with 12 months, a row with total project income per month, so in my ListView I'm annotating my price like this from django.db import connection def get_context_data(self, **kwargs): context = super(ProjectStatisticsList, self).get_context_data(**kwargs) truncate_month = connection.ops.date_trunc_sql("year", "month") total_price_per_month = Project.objects.extra({"month": truncate_month}).values("month").\ annotate(sum_price=Sum("price") I'm little confused on how to for loop over month in template and display total_price_per_month for each month? I know there is a lot of posts regarding this issue, but please bare with me because I'm really stuck on this one, and I want to learn something out of this, thanks. -
access to result of mocked method with autospec
Have in integration test: with mock.patch.object( EmailMultiAlternatives, 'send', autospec=True, side_effect=EmailMultiAlternatives.send ) as mocked_mail_send: method_using_that_send() mocked_mail_send # how to access here send's return value ? Mocking purpose is to verify if my method will call external method, but I don't want mock entirely that send method and overwrite original return_value. -
rqworker redis.exceptions.ResponseError: NOAUTH Authentication required
running rqworker from terminal results in redis.exceptions.ResponseError: NOAUTH Authentication require -
django display profile of a particular user
I want to display a profile of a single user only viwes.py class ViewProfile(generic.DetailView): model = User slug_field = 'username' template_name = 'profile/profile_view.html' def get_context_data(self, **kwargs): ctx = super(ViewProfile, self).get_context_data(**kwargs) ctx['profile'] = Profile.objects.all().first() return ctx urls.py url(r'^(?P<slug>[\w.@+-]+)/$', views.ViewProfile.as_view(),name="user_profile"), i am using username as slug no matter what username i change to i get the profile of same user. any solution for this? -
django how to display a tag only if the value coming from the database is not null?
The logic for showing a tag {% if profile.facebook is not None %}<i class="facebook icon"></i>{% endif %} i want to show the facebook icon only when the user has provided the link. if not i dont want to display the icon.