Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Possible to use IIS + httpplatformhandler + django?
I'm implementing a django and will deploy to Azure, as the wfastcgi got errors several times before, so I changed it to httpplatformhandler, unfortunately, as I reviewed the log, I always get server error 500 while running, but I really cannot catch the errors where it came from, so, could someone give a big favor to teach me how I can debug line by line within this environment? Or any suggestions on settings that I can simulate the platform locally by using IIS + httpplatformhsndler + django? Or how can I capture errors under httpplatformhandler? I'm using python 3.5.x, django 1.10.x, httpplatformhandler + azure web app, I don't have VM or on-premises network, just deploy to azure web app directly. Very Thankful if someone can let me know how you do so. Thanks a lot at all! -
Django filter a queryset
Just a quick one which I'm trying to solve for some time now ... (sorry in advance for the simple question ... can't find a convenient solution) I have a simple class named Opportunity: class OpportunityStatus(models.Model): status = models.CharField(max_length=100) def __str__(self): return self.status class Opportunity(models.Model): name = models.CharField(max_length=100, default='') director = models.ForeignKey(User) status = models.ForeignKey(OpportunityStatus) I have extracted the list of all the 'director' with the following code: employees = User.objects.filter(profile__title__status='Director') employees_list = list(set(employee.username for employee in employees)) And now I am trying to get - for each of the employees - a dictionary of all the Opportunities.name for a specified status. I tried - without success - something like : status = 'Open' dic = {} for employee in employees_list: deal_list = Opportunity.objects.filter(directeur_username=employee, status__status=status) dic[employee] = deal_list.name I get a nice : Cannot resolve keyword 'director_username' ... don't know how to fetch the Opportunities by filtering the username of the User linked to it as director ... with director instead of director_username EDIT : after some test it seems that the deal_list.name is not working either... An immense amount of thanks in advance for your help :) -
Render JSON response using Django's render()
I am working my way through Django's tutorial but failing to display an API response using Django's render() function. models.py ... class MF_Version(): def get_MF_Version(self): url = 'https://www.mediafire.com/api/1.5/system/get_version.php?response_format=json' r = requests.get(url) return r ... views.py ... def view_Version(request): hr = HttpResponse(MF_Version().get_MF_Version()) return render(request, 'mediafire/version.html', {'hr': hr}) # return hr ... version.html {% if 1 %} {{ hr }} {% endif %} Browser output: <HttpResponse status_code=200, "text/html; charset=utf-8"> MefiaFire response: {"response":{"action":"system/get_version","current_api_version":"1.5","result":"Success"}} If comment out the "return render(...)" in the view.py file and replace it with "return hr" I do see the JSON response from MediaFire, but I cannot figure out how to access "action," "current_api_version" and "result" in the HTML template. Any help is appreciated. -
Is there a better way to write processed data to the file tree in a django app than using a POST statement?
I have an app that exposes some data at an endpoint using the Django Rest Framework. Another application (on the same machine) GET's the data, parses it, processes it, and returns a file (currently a text file, but might become an XSLX). I thought that since I am using the DRF, I would create another endpoint that accepts a file (POST): an UploadFile model with a FileField, a serializer, view, etc. Is there another way that might be more efficient? -
pytest_configure_node hook does not get called in a plugin
I am writing a pytest plugin and want to implement pytest_configure_node from pytest-xdist hook, to initialize each node with specific Device related data. I used following example as reference. https://holgerkrekel.net/2013/11/12/running-tests-against-multiple-devicesresources-in-parallel/ as long as I put pytest_configure_node hook in conftest.py everything work as explained in the above article. But if move "pytest_configure_node" in to a separate plugin and register the plugin from command line then pytest_configure_node does not get called. the code for plugin is exactly same as the one which worked in conftest.py. Is there a reason why I see the behavior with regular plugin but not with conftest plugin. also in pytest_configure(config): the condition if not hasattr(config, "slaveinput"): is never met when the code is in general plugin but this condition met in when this this code is in confetest.py def pytest_configure(config): # this condition met when implemented in conftest.py but not met when implemented in regular plugign if not hasattr(config, "slaveinput"): -
Django - What would the relationship between these two models look like?
I have two models: class Post(models.Model): owner = models.ForeignKey(UserProfile, related_name='posts') caption = models.CharField(max_length=200) # so on class UserProfile(models.Model): # bunch of stuff here I want to create a 'like' and 'comment' feature for each post and don't know how I would do it since Django doesn't have a OneToMany relationship. Any suggestions? -
What am I missing while using WhiteNoise
I'm trying to use WhiteNoise in my Django. It isn't serving any static files. I don't know what I did wrong. This is the only place, I've made changes settings.py DEBUG = False INSTALLED_APPS = [ 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'channels', 'robot_configuration_interface', ] MIDDLEWARE = [ 'django.middleware.security.SecurityMiddleware', 'whitenoise.middleware.WhiteNoiseMiddleware', 'django.contrib.sessions.middleware.SessionMiddleware', 'django.middleware.common.CommonMiddleware', 'django.middleware.csrf.CsrfViewMiddleware', 'django.contrib.auth.middleware.AuthenticationMiddleware', 'django.contrib.messages.middleware.MessageMiddleware', 'django.middleware.clickjacking.XFrameOptionsMiddleware', ] -
Django Admin. Do not show any entries until fill something in search_fields
class PropertyAdmin(ModerationAdmin): search_fields = ('name', 'value', 'job__job_name', 'description') list_display = ('job', 'app', 'name', 'value', 'description', 'pub_date') readonly_fields = ('pub_date',) list_filter = ('app',) I have more than 5000 objects in a model. I do not want to use pagination, also I do not want to see all 5000 objects on one page while "search_fields" or "list_filter" are empty. Is there a way to see only search/filter fields and after that to choose necessary objects by filling this fields? -
ValueError badly formed hexadecimal UUID string django ListView
Assume all imports done. I have a model like this: class Package(models.Model): uuid = models.UUIDField(default=uuid.uuid4, editable=False) name = models.CharField(max_length=400) Then I want to use generic ListView like so: class PackageList(ListView): model = Package template_name = 'package/list.html' All with url like so: url(r'^package/list/$', views.PackageList.as_view(), name='package_list'), When I visit the localhost:8000, I get ValueError at /package/list/ badly formed hexadecimal UUID string However, a DetailView generic view loads the detail based on the uuid successfully, without any issues. The error comes up only when using the ListView. What am I doing wrong? -
'mathfilter' tag 'addition' stopped working since replicating django project - how to resolve?
Recently I moved a Django Project to a new virtual environment. Everything appears to be working fine, with the exception of the following error: TemplateSyntaxError at /profile/ Invalid filter: 'addition' Request Method: GET Request URL: http://example.com/example/ Django Version: 1.9.12 Exception Type: TemplateSyntaxError Exception Value: Invalid filter: 'addition' Exception Location: /opt/example/local/lib/python2.7/site-packages/django/template/base.py in parse, line 516 Python Executable: /usr/local/bin/uwsgi Python Version: 2.7.3 I narrowed this down to this line of code: {% with deeb_percent=stat.deeb_base|addition:stat.deeb_deal %} Further investigation and I found this: https://github.com/dbrgn/django-mathfilters , it appears 'addition' is a custom filter which is part of mathfilters. The documentation I linked says to run: pip install django-mathfilters I have checked with pip freeze, and mathfilters is installed. appdirs==1.4.3 backports.ssl-match-hostname==3.5.0.1 beautifulsoup4==4.5.3 Django==1.9.12 django-appconf==1.0.1 django-autocomplete-light==3.2.1 django-compat==1.0.8 django-compressor==1.6 django-dual-authentication==1.0.0 django-hijack==2.0.1 django-htmlmin==0.8.0 django-ipware==1.1.2 django-mathfilters==0.3.0 django-modelcluster==3.0.1 django-taggit==0.22.0 django-treebeard==4.1.0 django-widget-tweaks==1.4.1 djangorestframework==3.6.2 html5lib==0.9999999 packaging==16.8 Pillow==3.0.0 pyparsing==2.2.0 pytz==2015.7 requests==2.13.0 simplejson==3.10.0 six==1.10.0 slackclient==1.0.5 Unidecode==0.4.20 wagtail==1.9 websocket-client==0.40.0 Willow==0.4 Then add mathfilters to your INSTALLED_APPS. I have also checked INSTALLED_APPS in the project settings.py and mathfilters is also loaded: INSTALLED_APPS = [ ... 'mathfilters', ... ] At the top of the template in question 'mathfilters' is loaded: {% extends "base.html" %} {% load i18n %} {% load static %} {% load extra %} {% load … -
How do I get session data in Django?
Basically, what I'm looking for is the Django/Python equivalent to the PHP session_start(); print_R($_SESSION); That is, I'd like to dump all the information I currently have stored in the session so I can see what's in there. -
Django-hijack or Django-impersonation - Any way for ALL users to be able to 'impersonate'?
I have a small webapp written in Django. I have a database like so: hijacker | can_hijack --------------------------- bob | sally rufus | tom If bob logs in, i would like him to be able to impersonate sally, and so on. However, bob is not a superuser, nor should he be. I went through and installed django-hijack which seemed to imply that i could override the superuser requirement: https://django-hijack.readthedocs.io/en/stable/configuration/#custom-authorization-function I wrote the following authorization function just for testing: def my_authorization_check(hijacker, hijacked): return True And added this line to my settings.py: HIJACK_AUTHORIZATION_CHECK = 'mysite.utils.my_authorization_check' However, whenever I try to "hijack" a user, I get redirected to the admin login screen (which I am interpreting as a sign that I cannot hijack a user without being a superuser). Any suggestions? -
Django used in google graph API
<script type="text/javascript" src="https://www.gstatic.com/charts/loader.js"></script> <script type="text/javascript"> google.charts.load('current', {'packages':['corechart']}); google.charts.setOnLoadCallback(drawChart); function drawChart() { var djangoData = {{ array|safe }}; var data = google.visualization.arrayToDataTable(djangoData); var options = { title: 'My Daily Activities' }; var chart = new google.visualization.PieChart(document.getElementById('piechart')); chart.draw(data, options); } </script> and my python response code m=Employee.objects.get(user_id = request.user.id) all_entries = Category.objects.all().filter(company_name=m.company) for b in all_entries: t=b.category_name array = ['Task', 'Hours per Day'],[t, 11],['antiseptic', 2],['soaps', 2] return render_to_response('company/panel.html', {'array': json.dumps(array)}) and want output like But problem is how i convert static value in dynamic, how and i put database values in such manner that list structure not compromise and display graph data according to fetch values ['Task', 'Hours per Day'],[t, 11],['antiseptic', 2],['soaps', 2] create list like above but using django variable i know it can be solve using for loop, but how ???? no of element which i want to display at graph was not fix number -
Django on Ubuntu server with apache
I've got a VPS with ONLY IPv6 and I want to use it for my Django-based websites. I did everything step by step according to this article LINK and whenever I try to access to server by its IPv6 like this way:http://[ipv6]:8000, It throws an error. If I try to access it like this way: http://[ipv6], it shows me default Ubuntu after-install page. Do you have any ideas or tips how to solve my problem and successfully deploy my djangoApp to VPS ? thank you very much. -
Django ListView not showing recently created items
I have an app with lots of class based views. In some of my ListViews, the items recently created are not being displayed. My models are like: # models.py class Parent(models.Model): name = models.CharField(max_length=10) class Child(models.Model): parent = models.ForeignKey(Parent) name = models.CharField(max_length=10) And # views.py class ChildListView(ListView): model = Child template = 'child.html' The thing is that, whenever I create an object from a CreateView, it doesn't appear in my list view. I thought it was because of sqlite in my developing server, but it happens also in MySQL. If I restart the service, it works normally. Any idea? -
Django: using template tags inside of javascript for Google Maps
I'm trying to use template tags in my javascript to make it dynamic and load maps according to the address sent. My map is working and my geocode as well. I can even pass the latitude and longitude to the template, but when I place it inside of javascritp it doesn't work as expected. For example: if the {{longitude}} is -122,0843845 in the HTML, I get on my alert( {{longitude}} ) only -122. Not sure if it is a float to string issue or something else, I'm quite new to javascript. The code. views.py class ImovelDetail(DetailView): model = Imovel def get_context_data(self, *args, **kwargs): address = "1600 Amphitheatre Parkway, Mountain View, CA" api_key = "AIzaSyAiw0iU0egdeVrOKboOOZ2n1WXS3Os0WgI" api_response = requests.get('https://maps.googleapis.com/maps/api/geocode/json?address={0}&key={1}'.format(address, api_key)) api_response_dict = api_response.json() if api_response_dict['status'] == 'OK': context = super(ImovelDetail, self).get_context_data(**kwargs) latitude = api_response_dict['results'][0]['geometry']['location']['lat'] longitude = api_response_dict['results'][0]['geometry']['location']['lng'] print(latitude) context.update({'latitude': latitude, 'longitude': longitude}) return context template.html {% block js %} <!-- <script> SOMETHING THAT I TRIED var latitude = {{ latitude }}; var longitude = {{ longitude }}; </script> --> <script> function initMap() { var address = {lat: {{latitude}}, lng:{{longitude}} }; var map = new google.maps.Map(document.getElementById('map'), { zoom: 15, center: address }); var marker = new google.maps.Marker({ position: address, map: map }); } … -
Django Permission Denised
I've set up many Django projects in the past but I'm struggling with something tonight. I've just set up a new site on an apache server. I've done it before and I've taken my normal conf file and changed the directory names as appropriate. I've run makemigrations, migrate, collectstatic and createsuperuser. All fine. I can enter the admin site. But when I try and enter the user site I'm getting permission denied for access to any other template and is requiring me to chmod 777 on the files to get access. [Errno 13] Permission denied: '/path/to/app/app/templates/app/index.html' What's going on? -
DjangoAdmin: Accesing the parent instance within an Inline admin
I have a Django admin class which declares an inlines iterable. Something like: @admin.register(Category) class CategoryAdmin(admin.ModelAdmin): ... ... inlines = [CategoryModifiersInline,] ... ... Then I have an Inline admin class like this: class CategoryModifiersInline(admin.TabularInline): model = Category.modifiers.through fk_name = 'category' extra = 1 def formfield_for_foreignkey(self, db_field, request, **kwargs): qs = Product.objects.filter(is_modifier=True).filter(active=True) kwargs['queryset'] = qs return super(CategoryModifiersInline, self).formfield_for_foreignkey(db_field, request, **kwargs) Where I filter the queryset for the foreign key based on some business requirement. This inline is only showed to the user in the change view, that means, when an object of the class Category is created and the user wants to add modifiers to it, never in the add view. What I want to do, is filtering the foreign key by one of the attributes of the Category model, I mean, I want to access the parent object from the formfield_for_foreignkey method. Does anyone know a way to achieve that? -
user and group overlaps in django admin material design
I have applied the django material design to my project. But the user and groups seem to have overlapped each other and turned out to be ugly. How to resolve this issue ? Please help -
How can I get a hello world app running through wsgi and IIS?
Here are the steps I have done thus far: Installed python and django django-admin startproject helloworld IIS Manager > Add Website Site Name: HelloWorld, Physical path: C:\path\to\helloworld, Host: machinename.domain.local Right click directory > Properties > Security > Edit > Add > IUSR python manage.py startapp hello Replace views.py in hello directory with code from http://dfpp.readthedocs.io/en/latest/chapter_01.html import textwrap # won't format correctly... from django.http import HttpResponse from django.views.generic.base import View class HomePageView(View): def dispatch(request, *args, **kwargs): response_text = textwrap.dedent('''\ <html> <head> <title>Greetings to the world</title> </head> <body> <h1>Greetings to the world</h1> <p>Hello, world!</p> </body> </html> ''') return HttpResponse(response_text) 7. Add urls.py from the same source, but with modifications so it actually works: from django.conf.urls import url from hello.views import HomePageView urlpatterns = [ url(r'^$', HomePageView.as_view(), name='home'), ] Modify helloworld/urls.py to read: from django.contrib import admin #again, format isn't working... from django.conf.urls import include, url urlpatterns = [ url(r'', include('hello.urls')), ] So this much works if I run it through and view it at 127.0.0.1:8000 python manage.py runserver But I want it to work through IIS! And at the url I set up through IIS. At this point I am getting a 403.14 error. I'm guessing this has something to do with … -
eval or gettatr to validate objects from Django
I have certain products in my database that are only available in certain locations. I'd like to store a string with each product that evaluates against the user to see if that object should be shown. So for example an object might have [city, 'New York'] meaning I want to check that the user.profile.city == New York. Or [country, 'CA'] meaning user.profile.country == CA. I suspect I need to use getattr but I'm a little lost about both storing the string properly and how to compare them against my user object. Any suggestions? -
Django: revert merge migration
Let's suppose we have migrations with the following dependency graph (all applied): Initial state Now, for some reason we want to revert database schema to the state after applying migration 0006_f. We type: ./manage.py migrate myapp 0006_f and now we have the following state: One branch reverted The problem is that Django does not revert the right branch, so now we have some migrations applied from left branch and some from the right one. One way to avoid it is to migrate back to 0002_b and forward to 0006_f but this can cause data loss. Also some of migrations 0006_f, 0005_e, 0004_d, 0003_c can be irreversible. Another way is to run the following: ./manage.py migrate myapp 0006_f ./manage.py migrate myapp 0004_d1 Now, to achieve the desired state we only have to revert the migration 0004_d1 and I do not see a way to undo 0004_d1 without undoing 0006_f, 0005_e and 0004_d except for opening DB shell and reverting it manually. Is there a way to explicitly undo only one migration? Is there another way to properly undo migrations from parallel branch? Is there some reason for Django not to automatically revert migrations from parallel branch when undoing merge migration? -
IE 11 Downloads Page instead of opening it, works in Chrome and Firefox
I have a Django application running on a Ubuntu, Apache server that works perfectly under Chrome and Firefox, however when I access it via Internet Explorer 11, it will not load. Instead of rendering the HTML in the browser window, I receive the "Do you want to open or save XXXXXX from XXXXXX message. Tried debugging the site in IE, and the console shows a warming: HTML1527: DOCTYPE expected. Consider adding a valid HTML5 doctype: "", however this is the first line of the HTML. In Chrome, this error does not appear but I get a warning about the page including a password field (have not flipped to https yet as I am still in development). The only other thing I can find (in debug) is that the "Content Type" shows up blank, but other sites I review have entries (text/html, etc.) but I don't see how to populate this information. Please advise how I can troubleshoot this further to find the cause of the page not loading. Here is the code: <!DOCTYPE html> <html> <head> <meta content="text/html; charset=UTF-8" http-equiv="content-type"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <title>ops</title> <link rel="stylesheet" type="text/css" href="/static/content/bootstrap.min.css" /> <link rel="stylesheet" type="text/css" href="/static/content/site.css" /> <script src="/static/scripts/modernizr-2.6.2.js"></script> </head> <body> <div … -
Django Template date comparison
I'm using the following within a Django template to compare a date field with the current date. {% if l.expires >= now %} expires is defined within the model as expires = models.DateField Irrespective of the date this is always evaluating to false. How do I get it to evaluate correctly? -
Errno 13 Permission denied when trying to run wkhtmltopdf
Trying to point django to run the wkhtmltopdf in order to generate a pdf file. Running NGINX with UNICORN Using SUPERVISOR Ubuntu 16 in my unicorn_supervisor log i got: Internal Server Error: /invoice/1/pdf Traceback (most recent call last):emphasized text File "/home/instantuser/app/lib/python3.5/site-packages/django/core/handlers/exception.py", line 39, in inner response = get_response(request) File "/home/instantuser/app/lib/python3.5/site-packages/django/core/handlers/base.py", line 217, in _get_respons e response = self.process_exception_by_middleware(e, request) File "/home/instantuser/app/lib/python3.5/site-packages/django/core/handlers/base.py", line 215, in _get_respons e response = response.render() File "/home/instantuser/app/lib/python3.5/site-packages/django/template/response.py", line 109, in render self.content = self.rendered_content File "/home/instantuser/app/lib/python3.5/site-packages/wkhtmltopdf/views.py", line 78, in rendered_content cmd_options=cmd_options File "/home/instantuser/app/lib/python3.5/site-packages/wkhtmltopdf/utils.py", line 186, in render_pdf_from_temp late cmd_options=cmd_options) File "/home/instantuser/app/lib/python3.5/site-packages/wkhtmltopdf/utils.py", line 124, in convert_to_pdf return wkhtmltopdf(pages=filename, **cmd_options) File "/home/instantuser/app/lib/python3.5/site-packages/wkhtmltopdf/utils.py", line 110, in wkhtmltopdf return check_output(ck_args, **ck_kwargs) File "/usr/lib/python3.5/subprocess.py", line 626, in check_output **kwargs).stdout File "/usr/lib/python3.5/subprocess.py", line 693, in run with Popen(*popenargs, **kwargs) as process: File "/usr/lib/python3.5/subprocess.py", line 947, in __init__ restore_signals, start_new_session) File "/usr/lib/python3.5/subprocess.py", line 1551, in _execute_child raise child_exception_type(errno_num, err_msg) PermissionError: [Errno 13] Permission denied The wkhtmltopdf file: -rwxr-xr-x 1 instantuser instantuser 39804584 Nov 22 10:11 wkhtmltopdf Unicorn process: instant+ 2949 0.1 0.5 70344 23216 ? S 18:51 0:00 /home/instantuser/app/bin/python3 ../bin/gunicorn instanthst.wsgi:application --name instanthst --workers 3 --user=instantuser --group=instantuser --bind=unix:/home/instantuser/app/instanthst/run/gunicorn.sock --log-level=debug --log-file=- instant+ 2954 0.3 1.2 171712 51992 ? S 18:51 0:00 /home/instantuser/app/bin/python3 ../bin/gunicorn instanthst.wsgi:application …